From 807e0531546746fcfb5f8bdb20b6c0609fdd8cae Mon Sep 17 00:00:00 2001 From: wangcaoyu Date: Wed, 19 Feb 2025 14:18:20 +0800 Subject: [PATCH 001/123] =?UTF-8?q?=E4=BF=AE=E6=94=B9ohos=5Fdeclaration=5F?= =?UTF-8?q?ets=E4=BE=9D=E8=B5=96=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangcaoyu --- BUILD.gn | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/BUILD.gn b/BUILD.gn index 9dd538cb9..88a5392a1 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -336,7 +336,8 @@ ohos_copy("ohos_declaration_ets_ark") { deps += [ "//interface/sdk-js:ohos_declaration_ets" ] } - sources = [ root_out_dir + "/ohos_declaration/ohos_declaration_ets" ] + sources = + [ root_out_dir + "/ohos_declaration/${sdk_type}/ohos_declaration_ets" ] outputs = [ target_out_dir + "/../api" ] } -- Gitee From c2c5ea5809aa1ac9437a070ffb2ef73032dcf166 Mon Sep 17 00:00:00 2001 From: seaside_wu Date: Wed, 2 Apr 2025 14:30:38 +0800 Subject: [PATCH 002/123] add UIPlugin Signed-off-by: seaside_wu Change-Id: I79ffd76723b56ddddb963fc3def72c0f285f6917 --- arkui-plugins/.gitignore | 17 + arkui-plugins/BUILD.gn | 43 + arkui-plugins/babel.config.js | 42 + arkui-plugins/build_ui_plugins.py | 79 + arkui-plugins/common/abstract-visitor.ts | 55 + arkui-plugins/common/arkts-utils.ts | 86 + arkui-plugins/common/debug.ts | 69 + arkui-plugins/common/etsglobal-remover.ts | 34 + arkui-plugins/common/gensym-generator.ts | 62 + arkui-plugins/common/plugin-context.ts | 86 + arkui-plugins/common/predefines.ts | 64 + arkui-plugins/common/print-visitor.ts | 34 + arkui-plugins/common/program-visitor.ts | 122 + arkui-plugins/custom-import-plugin.js | 48 + .../interop-plugins/decl_transformer.ts | 88 + .../interop-plugins/emit_transformer.ts | 60 + arkui-plugins/interop-plugins/index.ts | 20 + .../interop-plugins/interop_plugin.ts | 86 + arkui-plugins/interop-plugins/types.ts | 56 + arkui-plugins/jest-test.config.ts | 33 + .../memo-plugins/function-transformer.ts | 443 + .../memo-plugins/import-transformer.ts | 31 + arkui-plugins/memo-plugins/index.ts | 70 + arkui-plugins/memo-plugins/memo-factory.ts | 310 + .../memo-plugins/memo-transformer.ts | 51 + .../memo-plugins/parameter-transformer.ts | 108 + .../memo-plugins/return-transformer.ts | 64 + .../memo-plugins/signature-transformer.ts | 92 + arkui-plugins/memo-plugins/utils.ts | 186 + arkui-plugins/npm_preinstall.sh | 30 + arkui-plugins/package.json | 33 + arkui-plugins/path.ts | 61 + arkui-plugins/test/arktsconfig_gen.js | 57 + arkui-plugins/test/arktsconfig_template.json | 2797 ++++ .../demo/localtest/build_config_template.json | 24 + .../localtest/build_decl_config_template.json | 29 + .../test/demo/localtest/entry/index.ets | 47 + .../test/demo/localtest/entry/new.ets | 69 + .../builder-lambda/instantiate-content.ets | 27 + .../instantiate-multi-content.ets | 29 + .../demo/mock/builder-lambda/instantiate.ets | 24 + arkui-plugins/test/demo/mock/entry.ets | 16 + .../test/demo/mock/struct-to-class.ets | 22 + .../local/@ohos.arkui.component.column.d.ets | 41 + .../local/@ohos.arkui.component.common.d.ets | 55 + ...ohos.arkui.component.customComponent.d.ets | 57 + .../test/local/@ohos.arkui.component.d.ets | 22 + .../local/@ohos.arkui.component.enums.d.ets | 53 + .../@ohos.arkui.component.styledString.d.ets | 32 + .../local/@ohos.arkui.component.text.d.ets | 132 + .../local/@ohos.arkui.component.units.d.ets | 29 + .../local/@ohos.arkui.external.resource.d.ets | 16 + .../@ohos.arkui.stateManagement.common.d.ets | 61 + .../local/@ohos.arkui.stateManagement.d.ets | 18 + .../@ohos.arkui.stateManagement.runtime.d.ets | 62 + .../@ohos.arkui.stateManagement.storage.d.ets | 119 + arkui-plugins/test/localtest_config.js | 51 + arkui-plugins/test/localtest_decl_config.js | 51 + arkui-plugins/test/package.json | 17 + arkui-plugins/test/test.log | 372 + .../test/ut/common/annotation.test.ts | 46 + .../instantiate-content.test.ts | 134 + .../instantiate-multi-content.test.ts | 142 + .../builder-lambda/instantiate.test.ts | 118 + .../transform-struct-to-class.test.ts | 89 + arkui-plugins/test/utils/artkts-config.ts | 334 + arkui-plugins/test/utils/compile.ts | 78 + arkui-plugins/test/utils/global.ts | 98 + arkui-plugins/test/utils/parse-string.ts | 50 + arkui-plugins/test/utils/path-config.ts | 78 + arkui-plugins/test/utils/plugin-driver.ts | 120 + arkui-plugins/test/utils/plugin-tester.ts | 209 + arkui-plugins/test/utils/safe-types.ts | 22 + arkui-plugins/tsconfig.build.json | 28 + arkui-plugins/tsconfig.json | 33 + .../ui-plugins/builder-lambda-transformer.ts | 566 + .../ui-plugins/component-transformer.ts | 407 + .../entry-translators/entry-transformer.ts | 30 + .../ui-plugins/entry-translators/factory.ts | 272 + .../ui-plugins/entry-translators/utils.ts | 88 + arkui-plugins/ui-plugins/index.ts | 88 + .../ui-plugins/preprocessor-transform.ts | 156 + .../ui-plugins/printer-transformer.ts | 29 + .../ui-plugins/property-translators/base.ts | 86 + .../property-translators/builderParam.ts | 113 + .../property-translators/consume.ts | 110 + .../property-translators/factory.ts | 127 + .../ui-plugins/property-translators/index.ts | 91 + .../ui-plugins/property-translators/link.ts | 197 + .../property-translators/localstoragelink.ts | 108 + .../property-translators/localstorageprop.ts | 177 + .../property-translators/objectlink.ts | 98 + .../ui-plugins/property-translators/prop.ts | 146 + .../property-translators/provide.ts | 140 + .../property-translators/regularProperty.ts | 79 + .../ui-plugins/property-translators/state.ts | 112 + .../property-translators/staticProperty.ts | 61 + .../property-translators/storageProp.ts | 157 + .../property-translators/storagelink.ts | 157 + .../ui-plugins/property-translators/types.ts | 40 + .../ui-plugins/property-translators/utils.ts | 285 + .../ui-plugins/property-translators/watch.ts | 130 + .../ui-plugins/struct-transformer.ts | 492 + arkui-plugins/ui-plugins/ui-factory.ts | 198 + arkui-plugins/ui-plugins/utils.ts | 210 + compiler/package-lock.json | 98 +- koala-wrapper/.gitignore | 5 + koala-wrapper/.gitlab-ci.yml | 96 + koala-wrapper/.mocharc.json | 11 + koala-wrapper/BUILD.gn | 45 + koala-wrapper/arktsconfig-memo.json | 18 + koala-wrapper/arktsconfig-print-only.json | 21 + koala-wrapper/arktsconfig.json | 22 + koala-wrapper/babel.config.js | 37 + koala-wrapper/build_ts_wrapper.py | 95 + koala-wrapper/koalaui-transform.js | 46 + .../common/dist/bridges/ohos/chai/index.d.ts | 56 + .../common/dist/bridges/ohos/chai/index.js | 124 + .../common/dist/bridges/ohos/index.d.ts | 19 + .../koalaui/common/dist/bridges/ohos/index.js | 36 + .../common/dist/bridges/ohos/mocha/index.d.ts | 17 + .../common/dist/bridges/ohos/mocha/index.js | 47 + .../koalaui/common/dist/lib/src/Errors.d.ts | 18 + .../koalaui/common/dist/lib/src/Errors.js | 36 + .../common/dist/lib/src/Finalization.d.ts | 21 + .../common/dist/lib/src/Finalization.js | 39 + .../common/dist/lib/src/KoalaProfiler.d.ts | 73 + .../common/dist/lib/src/KoalaProfiler.js | 177 + .../common/dist/lib/src/LifecycleEvent.d.ts | 32 + .../common/dist/lib/src/LifecycleEvent.js | 37 + .../common/dist/lib/src/MarkableQueue.d.ts | 31 + .../common/dist/lib/src/MarkableQueue.js | 94 + .../koalaui/common/dist/lib/src/Matrix33.d.ts | 29 + .../koalaui/common/dist/lib/src/Matrix33.js | 83 + .../koalaui/common/dist/lib/src/Matrix44.d.ts | 80 + .../koalaui/common/dist/lib/src/Matrix44.js | 311 + .../common/dist/lib/src/PerfProbe.d.ts | 114 + .../koalaui/common/dist/lib/src/PerfProbe.js | 279 + .../koalaui/common/dist/lib/src/Point.d.ts | 31 + .../koalaui/common/dist/lib/src/Point.js | 65 + .../koalaui/common/dist/lib/src/Point3.d.ts | 26 + .../koalaui/common/dist/lib/src/Point3.js | 41 + .../koalaui/common/dist/lib/src/index.d.ts | 32 + .../koalaui/common/dist/lib/src/index.js | 79 + .../koalaui/common/dist/lib/src/koalaKey.d.ts | 24 + .../koalaui/common/dist/lib/src/koalaKey.js | 28 + .../koalaui/common/dist/lib/src/math.d.ts | 59 + .../koalaui/common/dist/lib/src/math.js | 100 + .../koalaui/common/dist/lib/src/sha1.d.ts | 39 + .../koalaui/common/dist/lib/src/sha1.js | 311 + .../common/dist/lib/src/stringUtils.d.ts | 21 + .../common/dist/lib/src/stringUtils.js | 30 + .../koalaui/common/dist/lib/src/uniqueId.d.ts | 28 + .../koalaui/common/dist/lib/src/uniqueId.js | 58 + koala-wrapper/koalaui/common/oh-package.json5 | 50 + koala-wrapper/koalaui/common/src/Errors.ts | 31 + .../koalaui/common/src/Finalization.ts | 40 + .../koalaui/common/src/KoalaProfiler.ts | 190 + .../koalaui/common/src/LifecycleEvent.ts | 34 + .../koalaui/common/src/MarkableQueue.ts | 112 + koala-wrapper/koalaui/common/src/Matrix33.ts | 86 + koala-wrapper/koalaui/common/src/Matrix44.ts | 381 + koala-wrapper/koalaui/common/src/PerfProbe.ts | 431 + koala-wrapper/koalaui/common/src/Point.ts | 76 + koala-wrapper/koalaui/common/src/Point3.ts | 53 + koala-wrapper/koalaui/common/src/index.ts | 56 + koala-wrapper/koalaui/common/src/koalaKey.ts | 30 + koala-wrapper/koalaui/common/src/math.ts | 97 + koala-wrapper/koalaui/common/src/sha1.ts | 353 + .../koalaui/common/src/stringUtils.ts | 29 + koala-wrapper/koalaui/common/src/uniqueId.ts | 62 + koala-wrapper/koalaui/compat/README.md | 4 + .../koalaui/compat/dist/src/index.d.ts | 16 + .../koalaui/compat/dist/src/index.js | 47 + .../compat/dist/src/typescript/array.d.ts | 22 + .../compat/dist/src/typescript/array.js | 38 + .../compat/dist/src/typescript/atomic.d.ts | 30 + .../compat/dist/src/typescript/atomic.js | 41 + .../compat/dist/src/typescript/double.d.ts | 21 + .../compat/dist/src/typescript/double.js | 35 + .../dist/src/typescript/finalization.d.ts | 21 + .../dist/src/typescript/finalization.js | 29 + .../compat/dist/src/typescript/index.d.ts | 28 + .../compat/dist/src/typescript/index.js | 43 + .../dist/src/typescript/observable.d.ts | 67 + .../compat/dist/src/typescript/observable.js | 406 + .../dist/src/typescript/performance.d.ts | 26 + .../compat/dist/src/typescript/performance.js | 34 + .../dist/src/typescript/prop-deep-copy.d.ts | 17 + .../dist/src/typescript/prop-deep-copy.js | 88 + .../dist/src/typescript/reflection.d.ts | 17 + .../compat/dist/src/typescript/reflection.js | 24 + .../compat/dist/src/typescript/strings.d.ts | 46 + .../compat/dist/src/typescript/strings.js | 189 + .../dist/src/typescript/ts-reflection.d.ts | 21 + .../dist/src/typescript/ts-reflection.js | 40 + .../compat/dist/src/typescript/types.d.ts | 26 + .../compat/dist/src/typescript/types.js | 18 + .../compat/dist/src/typescript/utils.d.ts | 17 + .../compat/dist/src/typescript/utils.js | 22 + .../koalaui/compat/src/arkts/array.ts | 58 + .../koalaui/compat/src/arkts/atomic.ts | 41 + .../koalaui/compat/src/arkts/double.ts | 33 + .../koalaui/compat/src/arkts/finalization.ts | 31 + .../koalaui/compat/src/arkts/index.ts | 27 + .../koalaui/compat/src/arkts/observable.ts | 311 + .../koalaui/compat/src/arkts/performance.ts | 30 + .../compat/src/arkts/prop-deep-copy.ts | 24 + .../koalaui/compat/src/arkts/reflection.ts | 22 + .../koalaui/compat/src/arkts/strings.ts | 214 + .../koalaui/compat/src/arkts/ts-reflection.ts | 38 + .../koalaui/compat/src/arkts/types.ts | 25 + .../koalaui/compat/src/arkts/utils.ts | 18 + koala-wrapper/koalaui/compat/src/index.ts | 56 + .../koalaui/compat/src/ohos/index.ts | 59 + .../koalaui/compat/src/ohos/performance.ts | 30 + .../koalaui/compat/src/typescript/Types.d.ts | 19 + .../koalaui/compat/src/typescript/array.ts | 36 + .../koalaui/compat/src/typescript/atomic.ts | 40 + .../koalaui/compat/src/typescript/double.ts | 32 + .../compat/src/typescript/finalization.ts | 43 + .../koalaui/compat/src/typescript/index.ts | 27 + .../compat/src/typescript/observable.ts | 404 + .../compat/src/typescript/performance.ts | 30 + .../compat/src/typescript/prop-deep-copy.ts | 95 + .../compat/src/typescript/reflection.ts | 20 + .../koalaui/compat/src/typescript/strings.ts | 205 + .../compat/src/typescript/ts-reflection.ts | 35 + .../koalaui/compat/src/typescript/types.ts | 25 + .../koalaui/compat/src/typescript/utils.ts | 18 + .../dist/lib/src/arkts/ResourceManager.d.ts | 29 + .../dist/lib/src/arkts/ResourceManager.js | 61 + .../lib/src/interop/DeserializerBase.d.ts | 55 + .../dist/lib/src/interop/DeserializerBase.js | 208 + .../dist/lib/src/interop/Finalizable.d.ts | 43 + .../dist/lib/src/interop/Finalizable.js | 100 + .../lib/src/interop/InteropNativeModule.d.ts | 53 + .../lib/src/interop/InteropNativeModule.js | 59 + .../dist/lib/src/interop/InteropOps.d.ts | 22 + .../dist/lib/src/interop/InteropOps.js | 75 + .../dist/lib/src/interop/InteropTypes.d.ts | 32 + .../dist/lib/src/interop/InteropTypes.js | 18 + .../lib/src/interop/MaterializedBase.d.ts | 20 + .../dist/lib/src/interop/MaterializedBase.js | 17 + .../dist/lib/src/interop/NativeBuffer.d.ts | 27 + .../dist/lib/src/interop/NativeBuffer.js | 38 + .../dist/lib/src/interop/NativeString.d.ts | 23 + .../dist/lib/src/interop/NativeString.js | 32 + .../dist/lib/src/interop/Platform.d.ts | 43 + .../interop/dist/lib/src/interop/Platform.js | 69 + .../dist/lib/src/interop/SerializerBase.d.ts | 96 + .../dist/lib/src/interop/SerializerBase.js | 298 + .../interop/dist/lib/src/interop/Wrapper.d.ts | 28 + .../interop/dist/lib/src/interop/Wrapper.js | 54 + .../interop/dist/lib/src/interop/arrays.d.ts | 28 + .../interop/dist/lib/src/interop/arrays.js | 32 + .../interop/dist/lib/src/interop/buffer.d.ts | 24 + .../interop/dist/lib/src/interop/buffer.js | 38 + .../interop/dist/lib/src/interop/index.d.ts | 40 + .../interop/dist/lib/src/interop/index.js | 96 + .../dist/lib/src/interop/loadLibraries.d.ts | 19 + .../dist/lib/src/interop/loadLibraries.js | 45 + .../dist/lib/src/interop/nullable.d.ts | 18 + .../interop/dist/lib/src/interop/nullable.js | 28 + .../dist/lib/src/napi/wrappers/Callback.d.ts | 20 + .../dist/lib/src/napi/wrappers/Callback.js | 27 + .../dist/lib/src/napi/wrappers/Wrapper.d.ts | 24 + .../dist/lib/src/napi/wrappers/Wrapper.js | 46 + .../dist/lib/src/napi/wrappers/arrays.d.ts | 35 + .../dist/lib/src/napi/wrappers/arrays.js | 116 + .../dist/lib/src/wasm/wrappers/Callback.d.ts | 20 + .../dist/lib/src/wasm/wrappers/Callback.js | 81 + .../dist/lib/src/wasm/wrappers/Wrapper.d.ts | 24 + .../dist/lib/src/wasm/wrappers/Wrapper.js | 44 + .../dist/lib/src/wasm/wrappers/arrays.d.ts | 35 + .../dist/lib/src/wasm/wrappers/arrays.js | 147 + .../koalaui/interop/oh-package.json5 | 62 + .../interop/src/arkts/DeserializerBase.sts | 245 + .../koalaui/interop/src/arkts/Finalizable.sts | 100 + .../interop/src/arkts/InteropNativeModule.sts | 58 + .../interop/src/arkts/InteropTypes.sts | 34 + .../interop/src/arkts/MaterializedBase.sts | 21 + .../interop/src/arkts/NativeBuffer.sts | 38 + .../interop/src/arkts/ResourceManager.ts | 69 + .../interop/src/arkts/SerializerBase.sts | 324 + .../koalaui/interop/src/arkts/buffer.sts | 42 + .../koalaui/interop/src/arkts/callback.sts | 92 + .../koalaui/interop/src/arkts/index.sts | 26 + .../interop/src/arkts/loadLibraries.sts | 28 + .../interop/src/cangjie/DeserializerBase.cj | 134 + .../interop/src/cangjie/Finalizable.cj | 33 + .../src/cangjie/InteropNativeModule.cj | 223 + .../interop/src/cangjie/InteropTypes.cj | 24 + .../interop/src/cangjie/ResourceManager.cj | 78 + .../interop/src/cangjie/SerializerBase.cj | 262 + .../koalaui/interop/src/cangjie/Tag.cj | 29 + .../koalaui/interop/src/cangjie/cjpm.toml | 12 + .../interop/src/cpp/DeserializerBase.h | 650 + .../koalaui/interop/src/cpp/SerializerBase.h | 264 + .../koalaui/interop/src/cpp/ani/ani.h | 9062 ++++++++++++ .../interop/src/cpp/ani/convertors-ani.cc | 154 + .../interop/src/cpp/ani/convertors-ani.h | 1378 ++ .../interop/src/cpp/callback-resource.cc | 95 + .../interop/src/cpp/callback-resource.h | 55 + .../interop/src/cpp/cangjie/convertors-cj.cc | 14 + .../interop/src/cpp/cangjie/convertors-cj.h | 875 ++ .../koalaui/interop/src/cpp/common-interop.cc | 469 + .../koalaui/interop/src/cpp/common-interop.h | 71 + .../koalaui/interop/src/cpp/crashdump.h | 43 + .../koalaui/interop/src/cpp/dynamic-loader.h | 110 + .../interop/src/cpp/ets/convertors-ets.cc | 149 + .../interop/src/cpp/ets/convertors-ets.h | 1349 ++ .../koalaui/interop/src/cpp/ets/etsapi.h | 1545 ++ .../interop/src/cpp/interop-logging.cc | 79 + .../koalaui/interop/src/cpp/interop-logging.h | 51 + .../koalaui/interop/src/cpp/interop-types.h | 145 + .../interop/src/cpp/jni/convertors-jni.cc | 107 + .../interop/src/cpp/jni/convertors-jni.h | 1465 ++ .../interop/src/cpp/jsc/convertors-jsc.cc | 285 + .../interop/src/cpp/jsc/convertors-jsc.h | 722 + .../interop/src/cpp/napi/convertors-napi.cc | 389 + .../interop/src/cpp/napi/convertors-napi.h | 1374 ++ .../interop/src/cpp/napi/win-dynamic-node.cc | 672 + .../koalaui/interop/src/cpp/ohos/hilog/log.h | 286 + .../koalaui/interop/src/cpp/ohos/oh_sk_log.cc | 67 + .../koalaui/interop/src/cpp/ohos/oh_sk_log.h | 57 + .../koalaui/interop/src/cpp/profiler.h | 98 + .../koalaui/interop/src/cpp/tracer.h | 45 + .../interop/src/cpp/types/koala-types.h | 225 + .../interop/src/cpp/types/signatures.cc | 157 + .../interop/src/cpp/types/signatures.h | 25 + .../koalaui/interop/src/cpp/vmloader.cc | 638 + .../interop/src/cpp/wasm/convertors-wasm.h | 778 + .../interop/src/interop/DeserializerBase.ts | 221 + .../interop/src/interop/Finalizable.ts | 109 + .../src/interop/InteropNativeModule.ts | 59 + .../koalaui/interop/src/interop/InteropOps.ts | 88 + .../interop/src/interop/InteropTypes.ts | 31 + .../interop/src/interop/MaterializedBase.ts | 20 + .../interop/src/interop/NativeBuffer.ts | 39 + .../interop/src/interop/NativeString.ts | 30 + .../koalaui/interop/src/interop/Platform.ts | 89 + .../interop/src/interop/SerializerBase.ts | 296 + .../koalaui/interop/src/interop/Wrapper.ts | 45 + .../koalaui/interop/src/interop/arrays.ts | 43 + .../koalaui/interop/src/interop/buffer.ts | 36 + .../koalaui/interop/src/interop/index.ts | 74 + .../src/interop/java/CallbackRecord.java | 25 + .../src/interop/java/CallbackRegistry.java | 69 + .../src/interop/java/CallbackTests.java | 181 + .../src/interop/java/CallbackType.java | 19 + .../interop/src/interop/loadLibraries.ts | 40 + .../koalaui/interop/src/interop/nullable.ts | 25 + .../interop/src/napi/wrappers/Callback.ts | 27 + .../interop/src/napi/wrappers/Wrapper.ts | 46 + .../interop/src/napi/wrappers/arrays.ts | 111 + .../interop/src/wasm/wrappers/Callback.ts | 99 + .../interop/src/wasm/wrappers/Wrapper.ts | 44 + .../interop/src/wasm/wrappers/arrays.ts | 171 + koala-wrapper/native/BUILD.gn | 141 + koala-wrapper/native/include/common.h | 39 + koala-wrapper/native/meson.build | 63 + koala-wrapper/native/meson_options.txt | 23 + koala-wrapper/native/src/bridges.cc | 345 + koala-wrapper/native/src/common.cc | 231 + koala-wrapper/native/src/generated/bridges.cc | 11764 ++++++++++++++++ koala-wrapper/package.json | 81 + koala-wrapper/src/Es2pandaEnums.ts | 184 + koala-wrapper/src/Es2pandaNativeModule.ts | 661 + koala-wrapper/src/InteropNativeModule.ts | 50 + koala-wrapper/src/arkts-api/class-by-peer.ts | 31 + .../src/arkts-api/factory/nodeFactory.ts | 567 + .../src/arkts-api/factory/nodeTests.ts | 89 + koala-wrapper/src/arkts-api/index.ts | 75 + .../src/arkts-api/peers/ArktsObject.ts | 24 + koala-wrapper/src/arkts-api/peers/AstNode.ts | 129 + koala-wrapper/src/arkts-api/peers/Config.ts | 53 + koala-wrapper/src/arkts-api/peers/Context.ts | 56 + .../src/arkts-api/peers/ImportPathManager.ts | 36 + koala-wrapper/src/arkts-api/peers/Program.ts | 55 + .../src/arkts-api/peers/SourcePosition.ts | 38 + koala-wrapper/src/arkts-api/static/global.ts | 73 + .../to-be-generated/MemberExpression.ts | 98 + koala-wrapper/src/arkts-api/types.ts | 1007 ++ .../arkts-api/utilities/nativePtrDecoder.ts | 69 + .../src/arkts-api/utilities/private.ts | 163 + .../src/arkts-api/utilities/public.ts | 159 + koala-wrapper/src/arkts-api/visitor.ts | 338 + koala-wrapper/src/es2panda.ts | 24 + koala-wrapper/src/generated/Es2pandaEnums.ts | 1266 ++ .../src/generated/Es2pandaNativeModule.ts | 3715 +++++ koala-wrapper/src/generated/index.ts | 192 + koala-wrapper/src/generated/node-map.ts | 182 + .../src/generated/peers/AnnotatedAstNode.ts | 40 + .../generated/peers/AnnotatedExpression.ts | 50 + .../src/generated/peers/AnnotatedStatement.ts | 41 + .../generated/peers/AnnotationDeclaration.ts | 114 + .../src/generated/peers/AnnotationUsage.ts | 78 + .../src/generated/peers/ArrayExpression.ts | 80 + .../peers/ArrowFunctionExpression.ts | 71 + .../src/generated/peers/AssertStatement.ts | 58 + .../generated/peers/AssignmentExpression.ts | 80 + .../src/generated/peers/AstDumper.ts | 45 + .../src/generated/peers/AwaitExpression.ts | 54 + .../src/generated/peers/BigIntLiteral.ts | 54 + .../src/generated/peers/BinaryExpression.ts | 96 + .../src/generated/peers/BlockExpression.ts | 65 + .../src/generated/peers/BlockStatement.ts | 64 + .../src/generated/peers/BooleanLiteral.ts | 54 + .../src/generated/peers/BreakStatement.ts | 69 + .../src/generated/peers/CallExpression.ts | 98 + .../src/generated/peers/CatchClause.ts | 59 + .../src/generated/peers/ChainExpression.ts | 54 + .../src/generated/peers/CharLiteral.ts | 51 + .../src/generated/peers/ClassDeclaration.ts | 59 + .../src/generated/peers/ClassDefinition.ts | 222 + .../src/generated/peers/ClassElement.ts | 67 + .../src/generated/peers/ClassExpression.ts | 55 + .../src/generated/peers/ClassProperty.ts | 71 + .../src/generated/peers/ClassStaticBlock.ts | 53 + .../generated/peers/ConditionalExpression.ts | 75 + koala-wrapper/src/generated/peers/Context.ts | 37 + .../src/generated/peers/ContinueStatement.ts | 69 + .../src/generated/peers/DebuggerStatement.ts | 51 + .../src/generated/peers/Decorator.ts | 55 + .../generated/peers/DirectEvalExpression.ts | 53 + .../src/generated/peers/DoWhileStatement.ts | 59 + .../src/generated/peers/ETSClassLiteral.ts | 55 + .../generated/peers/ETSDynamicFunctionType.ts | 41 + .../src/generated/peers/ETSFunctionType.ts | 85 + .../generated/peers/ETSImportDeclaration.ts | 69 + .../generated/peers/ETSLaunchExpression.ts | 55 + .../src/generated/peers/ETSModule.ts | 72 + .../peers/ETSNewArrayInstanceExpression.ts | 63 + .../peers/ETSNewClassInstanceExpression.ts | 73 + .../ETSNewMultiDimArrayInstanceExpression.ts | 64 + .../src/generated/peers/ETSNullType.ts | 51 + .../generated/peers/ETSPackageDeclaration.ts | 52 + .../generated/peers/ETSParameterExpression.ts | 109 + .../src/generated/peers/ETSPrimitiveType.ts | 55 + .../generated/peers/ETSReExportDeclaration.ts | 52 + .../generated/peers/ETSStructDeclaration.ts | 52 + koala-wrapper/src/generated/peers/ETSTuple.ts | 82 + .../src/generated/peers/ETSTypeReference.ts | 56 + .../generated/peers/ETSTypeReferencePart.ts | 68 + .../src/generated/peers/ETSUndefinedType.ts | 51 + .../src/generated/peers/ETSUnionType.ts | 54 + .../src/generated/peers/ETSWildcardType.ts | 56 + .../src/generated/peers/EmptyStatement.ts | 51 + .../generated/peers/ExportAllDeclaration.ts | 59 + .../peers/ExportDefaultDeclaration.ts | 57 + .../generated/peers/ExportNamedDeclaration.ts | 74 + .../src/generated/peers/ExportSpecifier.ts | 58 + .../src/generated/peers/Expression.ts | 61 + .../generated/peers/ExpressionStatement.ts | 60 + .../src/generated/peers/ForInStatement.ts | 62 + .../src/generated/peers/ForOfStatement.ts | 65 + .../src/generated/peers/ForUpdateStatement.ts | 62 + .../src/generated/peers/FunctionDecl.ts | 41 + .../generated/peers/FunctionDeclaration.ts | 73 + .../src/generated/peers/FunctionExpression.ts | 68 + .../src/generated/peers/FunctionSignature.ts | 60 + .../src/generated/peers/Identifier.ts | 158 + .../src/generated/peers/IfStatement.ts | 61 + .../src/generated/peers/ImportDeclaration.ts | 62 + .../generated/peers/ImportDefaultSpecifier.ts | 55 + .../src/generated/peers/ImportExpression.ts | 54 + .../peers/ImportNamespaceSpecifier.ts | 55 + .../src/generated/peers/ImportSource.ts | 50 + .../src/generated/peers/ImportSpecifier.ts | 58 + .../src/generated/peers/InterfaceDecl.ts | 41 + .../src/generated/peers/LabelledStatement.ts | 58 + koala-wrapper/src/generated/peers/Literal.ts | 41 + .../src/generated/peers/LoopStatement.ts | 41 + .../peers/MaybeOptionalExpression.ts | 49 + .../src/generated/peers/MemberExpression.ts | 93 + .../src/generated/peers/MetaProperty.ts | 55 + .../src/generated/peers/MethodDefinition.ts | 98 + .../src/generated/peers/NamedType.ts | 77 + .../src/generated/peers/NewExpression.ts | 57 + .../src/generated/peers/NullLiteral.ts | 51 + .../src/generated/peers/NumberLiteral.ts | 48 + .../src/generated/peers/ObjectExpression.ts | 83 + .../src/generated/peers/OmittedExpression.ts | 51 + .../src/generated/peers/OpaqueTypeNode.ts | 51 + .../peers/PrefixAssertionExpression.ts | 58 + koala-wrapper/src/generated/peers/Property.ts | 80 + .../src/generated/peers/RegExpLiteral.ts | 58 + .../src/generated/peers/ReturnStatement.ts | 66 + .../src/generated/peers/ScriptFunction.ts | 199 + .../src/generated/peers/SequenceExpression.ts | 54 + .../src/generated/peers/SpreadElement.ts | 67 + .../src/generated/peers/SrcDumper.ts | 83 + .../src/generated/peers/Statement.ts | 40 + .../src/generated/peers/StringLiteral.ts | 59 + .../src/generated/peers/SuperExpression.ts | 51 + .../generated/peers/SwitchCaseStatement.ts | 58 + .../src/generated/peers/SwitchStatement.ts | 59 + .../src/generated/peers/TSAnyKeyword.ts | 51 + .../src/generated/peers/TSArrayType.ts | 54 + .../src/generated/peers/TSAsExpression.ts | 77 + .../src/generated/peers/TSBigintKeyword.ts | 51 + .../src/generated/peers/TSBooleanKeyword.ts | 51 + .../src/generated/peers/TSClassImplements.ts | 64 + .../src/generated/peers/TSConditionalType.ts | 64 + .../src/generated/peers/TSConstructorType.ts | 66 + .../src/generated/peers/TSEnumDeclaration.ts | 82 + .../src/generated/peers/TSEnumMember.ts | 67 + .../peers/TSExternalModuleReference.ts | 54 + .../src/generated/peers/TSFunctionType.ts | 68 + .../peers/TSImportEqualsDeclaration.ts | 62 + .../src/generated/peers/TSImportType.ts | 65 + .../src/generated/peers/TSIndexSignature.ts | 63 + .../generated/peers/TSIndexedAccessType.ts | 57 + .../src/generated/peers/TSInferType.ts | 55 + .../src/generated/peers/TSInterfaceBody.ts | 57 + .../generated/peers/TSInterfaceDeclaration.ts | 103 + .../generated/peers/TSInterfaceHeritage.ts | 55 + .../src/generated/peers/TSIntersectionType.ts | 55 + .../src/generated/peers/TSLiteralType.ts | 55 + .../src/generated/peers/TSMappedType.ts | 65 + .../src/generated/peers/TSMethodSignature.ts | 72 + .../src/generated/peers/TSModuleBlock.ts | 54 + .../generated/peers/TSModuleDeclaration.ts | 64 + .../src/generated/peers/TSNamedTupleMember.ts | 61 + .../src/generated/peers/TSNeverKeyword.ts | 51 + .../generated/peers/TSNonNullExpression.ts | 59 + .../src/generated/peers/TSNullKeyword.ts | 51 + .../src/generated/peers/TSNumberKeyword.ts | 51 + .../src/generated/peers/TSObjectKeyword.ts | 51 + .../generated/peers/TSParameterProperty.ts | 67 + .../generated/peers/TSParenthesizedType.ts | 55 + .../generated/peers/TSPropertySignature.ts | 73 + .../src/generated/peers/TSQualifiedName.ts | 58 + .../generated/peers/TSSignatureDeclaration.ts | 68 + .../src/generated/peers/TSStringKeyword.ts | 51 + .../src/generated/peers/TSThisType.ts | 51 + .../src/generated/peers/TSTupleType.ts | 54 + .../generated/peers/TSTypeAliasDeclaration.ts | 92 + .../src/generated/peers/TSTypeAssertion.ts | 64 + .../src/generated/peers/TSTypeLiteral.ts | 54 + .../src/generated/peers/TSTypeOperator.ts | 64 + .../src/generated/peers/TSTypeParameter.ts | 88 + .../peers/TSTypeParameterDeclaration.ts | 63 + .../peers/TSTypeParameterInstantiation.ts | 55 + .../src/generated/peers/TSTypePredicate.ts | 61 + .../src/generated/peers/TSTypeQuery.ts | 55 + .../src/generated/peers/TSTypeReference.ts | 60 + .../src/generated/peers/TSUndefinedKeyword.ts | 51 + .../src/generated/peers/TSUnionType.ts | 54 + .../src/generated/peers/TSUnknownKeyword.ts | 51 + .../src/generated/peers/TSVoidKeyword.ts | 51 + .../peers/TaggedTemplateExpression.ts | 62 + .../src/generated/peers/TemplateElement.ts | 63 + .../src/generated/peers/TemplateLiteral.ts | 58 + .../src/generated/peers/ThisExpression.ts | 51 + .../src/generated/peers/ThrowStatement.ts | 55 + .../src/generated/peers/TryStatement.ts | 67 + koala-wrapper/src/generated/peers/TypeNode.ts | 50 + .../src/generated/peers/TypedAstNode.ts | 40 + .../src/generated/peers/TypedStatement.ts | 41 + .../src/generated/peers/TypeofExpression.ts | 54 + .../src/generated/peers/UnaryExpression.ts | 58 + .../src/generated/peers/UndefinedLiteral.ts | 51 + .../src/generated/peers/UpdateExpression.ts | 61 + .../src/generated/peers/ValidationInfo.ts | 43 + .../generated/peers/VariableDeclaration.ts | 72 + .../src/generated/peers/VariableDeclarator.ts | 73 + .../src/generated/peers/WhileStatement.ts | 59 + .../src/generated/peers/YieldExpression.ts | 57 + koala-wrapper/src/reexport-for-generated.ts | 32 + koala-wrapper/src/utils.ts | 86 + koala-wrapper/tools/issue_gen.mjs | 66 + koala-wrapper/tsconfig.json | 38 + 574 files changed, 86133 insertions(+), 2 deletions(-) create mode 100644 arkui-plugins/.gitignore create mode 100755 arkui-plugins/BUILD.gn create mode 100644 arkui-plugins/babel.config.js create mode 100755 arkui-plugins/build_ui_plugins.py create mode 100644 arkui-plugins/common/abstract-visitor.ts create mode 100644 arkui-plugins/common/arkts-utils.ts create mode 100644 arkui-plugins/common/debug.ts create mode 100644 arkui-plugins/common/etsglobal-remover.ts create mode 100644 arkui-plugins/common/gensym-generator.ts create mode 100644 arkui-plugins/common/plugin-context.ts create mode 100644 arkui-plugins/common/predefines.ts create mode 100644 arkui-plugins/common/print-visitor.ts create mode 100644 arkui-plugins/common/program-visitor.ts create mode 100644 arkui-plugins/custom-import-plugin.js create mode 100644 arkui-plugins/interop-plugins/decl_transformer.ts create mode 100644 arkui-plugins/interop-plugins/emit_transformer.ts create mode 100644 arkui-plugins/interop-plugins/index.ts create mode 100644 arkui-plugins/interop-plugins/interop_plugin.ts create mode 100644 arkui-plugins/interop-plugins/types.ts create mode 100644 arkui-plugins/jest-test.config.ts create mode 100644 arkui-plugins/memo-plugins/function-transformer.ts create mode 100644 arkui-plugins/memo-plugins/import-transformer.ts create mode 100644 arkui-plugins/memo-plugins/index.ts create mode 100644 arkui-plugins/memo-plugins/memo-factory.ts create mode 100644 arkui-plugins/memo-plugins/memo-transformer.ts create mode 100644 arkui-plugins/memo-plugins/parameter-transformer.ts create mode 100644 arkui-plugins/memo-plugins/return-transformer.ts create mode 100644 arkui-plugins/memo-plugins/signature-transformer.ts create mode 100644 arkui-plugins/memo-plugins/utils.ts create mode 100755 arkui-plugins/npm_preinstall.sh create mode 100644 arkui-plugins/package.json create mode 100644 arkui-plugins/path.ts create mode 100644 arkui-plugins/test/arktsconfig_gen.js create mode 100644 arkui-plugins/test/arktsconfig_template.json create mode 100755 arkui-plugins/test/demo/localtest/build_config_template.json create mode 100644 arkui-plugins/test/demo/localtest/build_decl_config_template.json create mode 100644 arkui-plugins/test/demo/localtest/entry/index.ets create mode 100755 arkui-plugins/test/demo/localtest/entry/new.ets create mode 100644 arkui-plugins/test/demo/mock/builder-lambda/instantiate-content.ets create mode 100644 arkui-plugins/test/demo/mock/builder-lambda/instantiate-multi-content.ets create mode 100644 arkui-plugins/test/demo/mock/builder-lambda/instantiate.ets create mode 100644 arkui-plugins/test/demo/mock/entry.ets create mode 100644 arkui-plugins/test/demo/mock/struct-to-class.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.component.column.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.component.common.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.component.customComponent.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.component.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.component.enums.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.component.styledString.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.component.text.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.component.units.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.external.resource.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.stateManagement.common.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.stateManagement.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.stateManagement.runtime.d.ets create mode 100644 arkui-plugins/test/local/@ohos.arkui.stateManagement.storage.d.ets create mode 100644 arkui-plugins/test/localtest_config.js create mode 100644 arkui-plugins/test/localtest_decl_config.js create mode 100644 arkui-plugins/test/package.json create mode 100644 arkui-plugins/test/test.log create mode 100644 arkui-plugins/test/ut/common/annotation.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts create mode 100644 arkui-plugins/test/utils/artkts-config.ts create mode 100644 arkui-plugins/test/utils/compile.ts create mode 100644 arkui-plugins/test/utils/global.ts create mode 100644 arkui-plugins/test/utils/parse-string.ts create mode 100644 arkui-plugins/test/utils/path-config.ts create mode 100644 arkui-plugins/test/utils/plugin-driver.ts create mode 100644 arkui-plugins/test/utils/plugin-tester.ts create mode 100644 arkui-plugins/test/utils/safe-types.ts create mode 100644 arkui-plugins/tsconfig.build.json create mode 100644 arkui-plugins/tsconfig.json create mode 100644 arkui-plugins/ui-plugins/builder-lambda-transformer.ts create mode 100644 arkui-plugins/ui-plugins/component-transformer.ts create mode 100644 arkui-plugins/ui-plugins/entry-translators/entry-transformer.ts create mode 100644 arkui-plugins/ui-plugins/entry-translators/factory.ts create mode 100644 arkui-plugins/ui-plugins/entry-translators/utils.ts create mode 100644 arkui-plugins/ui-plugins/index.ts create mode 100644 arkui-plugins/ui-plugins/preprocessor-transform.ts create mode 100644 arkui-plugins/ui-plugins/printer-transformer.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/base.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/builderParam.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/consume.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/factory.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/index.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/link.ts create mode 100755 arkui-plugins/ui-plugins/property-translators/localstoragelink.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/localstorageprop.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/objectlink.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/prop.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/provide.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/regularProperty.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/state.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/staticProperty.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/storageProp.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/storagelink.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/types.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/utils.ts create mode 100644 arkui-plugins/ui-plugins/property-translators/watch.ts create mode 100644 arkui-plugins/ui-plugins/struct-transformer.ts create mode 100644 arkui-plugins/ui-plugins/ui-factory.ts create mode 100644 arkui-plugins/ui-plugins/utils.ts create mode 100644 koala-wrapper/.gitignore create mode 100644 koala-wrapper/.gitlab-ci.yml create mode 100644 koala-wrapper/.mocharc.json create mode 100644 koala-wrapper/BUILD.gn create mode 100644 koala-wrapper/arktsconfig-memo.json create mode 100644 koala-wrapper/arktsconfig-print-only.json create mode 100644 koala-wrapper/arktsconfig.json create mode 100644 koala-wrapper/babel.config.js create mode 100755 koala-wrapper/build_ts_wrapper.py create mode 100644 koala-wrapper/koalaui-transform.js create mode 100644 koala-wrapper/koalaui/common/dist/bridges/ohos/chai/index.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/bridges/ohos/chai/index.js create mode 100644 koala-wrapper/koalaui/common/dist/bridges/ohos/index.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/bridges/ohos/index.js create mode 100644 koala-wrapper/koalaui/common/dist/bridges/ohos/mocha/index.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/bridges/ohos/mocha/index.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Errors.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Errors.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Finalization.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Finalization.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/KoalaProfiler.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/KoalaProfiler.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/LifecycleEvent.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/LifecycleEvent.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/MarkableQueue.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/MarkableQueue.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Matrix33.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Matrix33.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Matrix44.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Matrix44.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/PerfProbe.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/PerfProbe.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Point.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Point.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Point3.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/Point3.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/index.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/index.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/koalaKey.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/koalaKey.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/math.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/math.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/sha1.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/sha1.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/stringUtils.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/stringUtils.js create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/uniqueId.d.ts create mode 100644 koala-wrapper/koalaui/common/dist/lib/src/uniqueId.js create mode 100644 koala-wrapper/koalaui/common/oh-package.json5 create mode 100644 koala-wrapper/koalaui/common/src/Errors.ts create mode 100644 koala-wrapper/koalaui/common/src/Finalization.ts create mode 100644 koala-wrapper/koalaui/common/src/KoalaProfiler.ts create mode 100644 koala-wrapper/koalaui/common/src/LifecycleEvent.ts create mode 100644 koala-wrapper/koalaui/common/src/MarkableQueue.ts create mode 100644 koala-wrapper/koalaui/common/src/Matrix33.ts create mode 100644 koala-wrapper/koalaui/common/src/Matrix44.ts create mode 100644 koala-wrapper/koalaui/common/src/PerfProbe.ts create mode 100644 koala-wrapper/koalaui/common/src/Point.ts create mode 100644 koala-wrapper/koalaui/common/src/Point3.ts create mode 100644 koala-wrapper/koalaui/common/src/index.ts create mode 100644 koala-wrapper/koalaui/common/src/koalaKey.ts create mode 100644 koala-wrapper/koalaui/common/src/math.ts create mode 100644 koala-wrapper/koalaui/common/src/sha1.ts create mode 100644 koala-wrapper/koalaui/common/src/stringUtils.ts create mode 100644 koala-wrapper/koalaui/common/src/uniqueId.ts create mode 100644 koala-wrapper/koalaui/compat/README.md create mode 100644 koala-wrapper/koalaui/compat/dist/src/index.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/index.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/array.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/array.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/atomic.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/atomic.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/double.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/double.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/finalization.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/finalization.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/index.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/index.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/observable.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/observable.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/performance.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/performance.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/prop-deep-copy.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/prop-deep-copy.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/reflection.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/reflection.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/strings.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/strings.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/ts-reflection.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/ts-reflection.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/types.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/types.js create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/utils.d.ts create mode 100644 koala-wrapper/koalaui/compat/dist/src/typescript/utils.js create mode 100644 koala-wrapper/koalaui/compat/src/arkts/array.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/atomic.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/double.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/finalization.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/index.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/observable.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/performance.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/prop-deep-copy.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/reflection.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/strings.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/ts-reflection.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/types.ts create mode 100644 koala-wrapper/koalaui/compat/src/arkts/utils.ts create mode 100644 koala-wrapper/koalaui/compat/src/index.ts create mode 100644 koala-wrapper/koalaui/compat/src/ohos/index.ts create mode 100644 koala-wrapper/koalaui/compat/src/ohos/performance.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/Types.d.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/array.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/atomic.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/double.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/finalization.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/index.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/observable.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/performance.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/prop-deep-copy.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/reflection.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/strings.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/ts-reflection.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/types.ts create mode 100644 koala-wrapper/koalaui/compat/src/typescript/utils.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/arkts/ResourceManager.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/arkts/ResourceManager.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/DeserializerBase.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/DeserializerBase.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/Finalizable.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/Finalizable.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropNativeModule.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropNativeModule.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropOps.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropOps.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropTypes.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropTypes.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/MaterializedBase.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/MaterializedBase.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeBuffer.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeBuffer.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeString.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeString.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/Platform.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/Platform.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/SerializerBase.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/SerializerBase.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/Wrapper.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/Wrapper.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/arrays.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/arrays.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/buffer.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/buffer.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/index.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/index.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/loadLibraries.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/loadLibraries.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/nullable.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/interop/nullable.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Callback.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Callback.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Wrapper.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Wrapper.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/arrays.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/arrays.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Callback.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Callback.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Wrapper.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Wrapper.js create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/arrays.d.ts create mode 100644 koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/arrays.js create mode 100644 koala-wrapper/koalaui/interop/oh-package.json5 create mode 100644 koala-wrapper/koalaui/interop/src/arkts/DeserializerBase.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/Finalizable.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/InteropNativeModule.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/InteropTypes.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/MaterializedBase.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/NativeBuffer.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/ResourceManager.ts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/SerializerBase.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/buffer.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/callback.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/index.sts create mode 100644 koala-wrapper/koalaui/interop/src/arkts/loadLibraries.sts create mode 100644 koala-wrapper/koalaui/interop/src/cangjie/DeserializerBase.cj create mode 100644 koala-wrapper/koalaui/interop/src/cangjie/Finalizable.cj create mode 100644 koala-wrapper/koalaui/interop/src/cangjie/InteropNativeModule.cj create mode 100644 koala-wrapper/koalaui/interop/src/cangjie/InteropTypes.cj create mode 100644 koala-wrapper/koalaui/interop/src/cangjie/ResourceManager.cj create mode 100644 koala-wrapper/koalaui/interop/src/cangjie/SerializerBase.cj create mode 100644 koala-wrapper/koalaui/interop/src/cangjie/Tag.cj create mode 100644 koala-wrapper/koalaui/interop/src/cangjie/cjpm.toml create mode 100644 koala-wrapper/koalaui/interop/src/cpp/DeserializerBase.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/SerializerBase.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ani/ani.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ani/convertors-ani.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ani/convertors-ani.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/callback-resource.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/callback-resource.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/cangjie/convertors-cj.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/cangjie/convertors-cj.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/common-interop.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/common-interop.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/crashdump.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/dynamic-loader.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ets/convertors-ets.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ets/convertors-ets.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ets/etsapi.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/interop-logging.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/interop-logging.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/interop-types.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/jni/convertors-jni.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/jni/convertors-jni.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/jsc/convertors-jsc.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/jsc/convertors-jsc.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/napi/convertors-napi.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/napi/convertors-napi.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/napi/win-dynamic-node.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ohos/hilog/log.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ohos/oh_sk_log.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/ohos/oh_sk_log.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/profiler.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/tracer.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/types/koala-types.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/types/signatures.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/types/signatures.h create mode 100644 koala-wrapper/koalaui/interop/src/cpp/vmloader.cc create mode 100644 koala-wrapper/koalaui/interop/src/cpp/wasm/convertors-wasm.h create mode 100644 koala-wrapper/koalaui/interop/src/interop/DeserializerBase.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/Finalizable.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/InteropNativeModule.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/InteropOps.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/InteropTypes.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/MaterializedBase.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/NativeBuffer.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/NativeString.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/Platform.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/SerializerBase.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/Wrapper.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/arrays.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/buffer.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/index.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/java/CallbackRecord.java create mode 100644 koala-wrapper/koalaui/interop/src/interop/java/CallbackRegistry.java create mode 100644 koala-wrapper/koalaui/interop/src/interop/java/CallbackTests.java create mode 100644 koala-wrapper/koalaui/interop/src/interop/java/CallbackType.java create mode 100644 koala-wrapper/koalaui/interop/src/interop/loadLibraries.ts create mode 100644 koala-wrapper/koalaui/interop/src/interop/nullable.ts create mode 100644 koala-wrapper/koalaui/interop/src/napi/wrappers/Callback.ts create mode 100644 koala-wrapper/koalaui/interop/src/napi/wrappers/Wrapper.ts create mode 100644 koala-wrapper/koalaui/interop/src/napi/wrappers/arrays.ts create mode 100644 koala-wrapper/koalaui/interop/src/wasm/wrappers/Callback.ts create mode 100644 koala-wrapper/koalaui/interop/src/wasm/wrappers/Wrapper.ts create mode 100644 koala-wrapper/koalaui/interop/src/wasm/wrappers/arrays.ts create mode 100644 koala-wrapper/native/BUILD.gn create mode 100644 koala-wrapper/native/include/common.h create mode 100644 koala-wrapper/native/meson.build create mode 100644 koala-wrapper/native/meson_options.txt create mode 100644 koala-wrapper/native/src/bridges.cc create mode 100644 koala-wrapper/native/src/common.cc create mode 100644 koala-wrapper/native/src/generated/bridges.cc create mode 100644 koala-wrapper/package.json create mode 100644 koala-wrapper/src/Es2pandaEnums.ts create mode 100644 koala-wrapper/src/Es2pandaNativeModule.ts create mode 100644 koala-wrapper/src/InteropNativeModule.ts create mode 100644 koala-wrapper/src/arkts-api/class-by-peer.ts create mode 100644 koala-wrapper/src/arkts-api/factory/nodeFactory.ts create mode 100644 koala-wrapper/src/arkts-api/factory/nodeTests.ts create mode 100644 koala-wrapper/src/arkts-api/index.ts create mode 100644 koala-wrapper/src/arkts-api/peers/ArktsObject.ts create mode 100644 koala-wrapper/src/arkts-api/peers/AstNode.ts create mode 100644 koala-wrapper/src/arkts-api/peers/Config.ts create mode 100644 koala-wrapper/src/arkts-api/peers/Context.ts create mode 100644 koala-wrapper/src/arkts-api/peers/ImportPathManager.ts create mode 100644 koala-wrapper/src/arkts-api/peers/Program.ts create mode 100644 koala-wrapper/src/arkts-api/peers/SourcePosition.ts create mode 100644 koala-wrapper/src/arkts-api/static/global.ts create mode 100644 koala-wrapper/src/arkts-api/to-be-generated/MemberExpression.ts create mode 100644 koala-wrapper/src/arkts-api/types.ts create mode 100644 koala-wrapper/src/arkts-api/utilities/nativePtrDecoder.ts create mode 100644 koala-wrapper/src/arkts-api/utilities/private.ts create mode 100644 koala-wrapper/src/arkts-api/utilities/public.ts create mode 100644 koala-wrapper/src/arkts-api/visitor.ts create mode 100644 koala-wrapper/src/es2panda.ts create mode 100644 koala-wrapper/src/generated/Es2pandaEnums.ts create mode 100644 koala-wrapper/src/generated/Es2pandaNativeModule.ts create mode 100644 koala-wrapper/src/generated/index.ts create mode 100644 koala-wrapper/src/generated/node-map.ts create mode 100644 koala-wrapper/src/generated/peers/AnnotatedAstNode.ts create mode 100644 koala-wrapper/src/generated/peers/AnnotatedExpression.ts create mode 100644 koala-wrapper/src/generated/peers/AnnotatedStatement.ts create mode 100644 koala-wrapper/src/generated/peers/AnnotationDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/AnnotationUsage.ts create mode 100644 koala-wrapper/src/generated/peers/ArrayExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts create mode 100644 koala-wrapper/src/generated/peers/AssertStatement.ts create mode 100644 koala-wrapper/src/generated/peers/AssignmentExpression.ts create mode 100644 koala-wrapper/src/generated/peers/AstDumper.ts create mode 100644 koala-wrapper/src/generated/peers/AwaitExpression.ts create mode 100644 koala-wrapper/src/generated/peers/BigIntLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/BinaryExpression.ts create mode 100644 koala-wrapper/src/generated/peers/BlockExpression.ts create mode 100644 koala-wrapper/src/generated/peers/BlockStatement.ts create mode 100644 koala-wrapper/src/generated/peers/BooleanLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/BreakStatement.ts create mode 100644 koala-wrapper/src/generated/peers/CallExpression.ts create mode 100644 koala-wrapper/src/generated/peers/CatchClause.ts create mode 100644 koala-wrapper/src/generated/peers/ChainExpression.ts create mode 100644 koala-wrapper/src/generated/peers/CharLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/ClassDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ClassDefinition.ts create mode 100644 koala-wrapper/src/generated/peers/ClassElement.ts create mode 100644 koala-wrapper/src/generated/peers/ClassExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ClassProperty.ts create mode 100644 koala-wrapper/src/generated/peers/ClassStaticBlock.ts create mode 100644 koala-wrapper/src/generated/peers/ConditionalExpression.ts create mode 100644 koala-wrapper/src/generated/peers/Context.ts create mode 100644 koala-wrapper/src/generated/peers/ContinueStatement.ts create mode 100644 koala-wrapper/src/generated/peers/DebuggerStatement.ts create mode 100644 koala-wrapper/src/generated/peers/Decorator.ts create mode 100644 koala-wrapper/src/generated/peers/DirectEvalExpression.ts create mode 100644 koala-wrapper/src/generated/peers/DoWhileStatement.ts create mode 100644 koala-wrapper/src/generated/peers/ETSClassLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/ETSDynamicFunctionType.ts create mode 100644 koala-wrapper/src/generated/peers/ETSFunctionType.ts create mode 100644 koala-wrapper/src/generated/peers/ETSImportDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ETSLaunchExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ETSModule.ts create mode 100644 koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ETSNullType.ts create mode 100644 koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ETSParameterExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ETSPrimitiveType.ts create mode 100644 koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ETSStructDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ETSTuple.ts create mode 100644 koala-wrapper/src/generated/peers/ETSTypeReference.ts create mode 100644 koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts create mode 100644 koala-wrapper/src/generated/peers/ETSUndefinedType.ts create mode 100644 koala-wrapper/src/generated/peers/ETSUnionType.ts create mode 100644 koala-wrapper/src/generated/peers/ETSWildcardType.ts create mode 100644 koala-wrapper/src/generated/peers/EmptyStatement.ts create mode 100644 koala-wrapper/src/generated/peers/ExportAllDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ExportSpecifier.ts create mode 100644 koala-wrapper/src/generated/peers/Expression.ts create mode 100644 koala-wrapper/src/generated/peers/ExpressionStatement.ts create mode 100644 koala-wrapper/src/generated/peers/ForInStatement.ts create mode 100644 koala-wrapper/src/generated/peers/ForOfStatement.ts create mode 100644 koala-wrapper/src/generated/peers/ForUpdateStatement.ts create mode 100644 koala-wrapper/src/generated/peers/FunctionDecl.ts create mode 100644 koala-wrapper/src/generated/peers/FunctionDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/FunctionExpression.ts create mode 100644 koala-wrapper/src/generated/peers/FunctionSignature.ts create mode 100644 koala-wrapper/src/generated/peers/Identifier.ts create mode 100644 koala-wrapper/src/generated/peers/IfStatement.ts create mode 100644 koala-wrapper/src/generated/peers/ImportDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts create mode 100644 koala-wrapper/src/generated/peers/ImportExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts create mode 100644 koala-wrapper/src/generated/peers/ImportSource.ts create mode 100644 koala-wrapper/src/generated/peers/ImportSpecifier.ts create mode 100644 koala-wrapper/src/generated/peers/InterfaceDecl.ts create mode 100644 koala-wrapper/src/generated/peers/LabelledStatement.ts create mode 100644 koala-wrapper/src/generated/peers/Literal.ts create mode 100644 koala-wrapper/src/generated/peers/LoopStatement.ts create mode 100644 koala-wrapper/src/generated/peers/MaybeOptionalExpression.ts create mode 100644 koala-wrapper/src/generated/peers/MemberExpression.ts create mode 100644 koala-wrapper/src/generated/peers/MetaProperty.ts create mode 100644 koala-wrapper/src/generated/peers/MethodDefinition.ts create mode 100644 koala-wrapper/src/generated/peers/NamedType.ts create mode 100644 koala-wrapper/src/generated/peers/NewExpression.ts create mode 100644 koala-wrapper/src/generated/peers/NullLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/NumberLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/ObjectExpression.ts create mode 100644 koala-wrapper/src/generated/peers/OmittedExpression.ts create mode 100644 koala-wrapper/src/generated/peers/OpaqueTypeNode.ts create mode 100644 koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts create mode 100644 koala-wrapper/src/generated/peers/Property.ts create mode 100644 koala-wrapper/src/generated/peers/RegExpLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/ReturnStatement.ts create mode 100644 koala-wrapper/src/generated/peers/ScriptFunction.ts create mode 100644 koala-wrapper/src/generated/peers/SequenceExpression.ts create mode 100644 koala-wrapper/src/generated/peers/SpreadElement.ts create mode 100644 koala-wrapper/src/generated/peers/SrcDumper.ts create mode 100644 koala-wrapper/src/generated/peers/Statement.ts create mode 100644 koala-wrapper/src/generated/peers/StringLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/SuperExpression.ts create mode 100644 koala-wrapper/src/generated/peers/SwitchCaseStatement.ts create mode 100644 koala-wrapper/src/generated/peers/SwitchStatement.ts create mode 100644 koala-wrapper/src/generated/peers/TSAnyKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSArrayType.ts create mode 100644 koala-wrapper/src/generated/peers/TSAsExpression.ts create mode 100644 koala-wrapper/src/generated/peers/TSBigintKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSBooleanKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSClassImplements.ts create mode 100644 koala-wrapper/src/generated/peers/TSConditionalType.ts create mode 100644 koala-wrapper/src/generated/peers/TSConstructorType.ts create mode 100644 koala-wrapper/src/generated/peers/TSEnumDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/TSEnumMember.ts create mode 100644 koala-wrapper/src/generated/peers/TSExternalModuleReference.ts create mode 100644 koala-wrapper/src/generated/peers/TSFunctionType.ts create mode 100644 koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/TSImportType.ts create mode 100644 koala-wrapper/src/generated/peers/TSIndexSignature.ts create mode 100644 koala-wrapper/src/generated/peers/TSIndexedAccessType.ts create mode 100644 koala-wrapper/src/generated/peers/TSInferType.ts create mode 100644 koala-wrapper/src/generated/peers/TSInterfaceBody.ts create mode 100644 koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts create mode 100644 koala-wrapper/src/generated/peers/TSIntersectionType.ts create mode 100644 koala-wrapper/src/generated/peers/TSLiteralType.ts create mode 100644 koala-wrapper/src/generated/peers/TSMappedType.ts create mode 100644 koala-wrapper/src/generated/peers/TSMethodSignature.ts create mode 100644 koala-wrapper/src/generated/peers/TSModuleBlock.ts create mode 100644 koala-wrapper/src/generated/peers/TSModuleDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/TSNamedTupleMember.ts create mode 100644 koala-wrapper/src/generated/peers/TSNeverKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSNonNullExpression.ts create mode 100644 koala-wrapper/src/generated/peers/TSNullKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSNumberKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSObjectKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSParameterProperty.ts create mode 100644 koala-wrapper/src/generated/peers/TSParenthesizedType.ts create mode 100644 koala-wrapper/src/generated/peers/TSPropertySignature.ts create mode 100644 koala-wrapper/src/generated/peers/TSQualifiedName.ts create mode 100644 koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/TSStringKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSThisType.ts create mode 100644 koala-wrapper/src/generated/peers/TSTupleType.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeAssertion.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeOperator.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeParameter.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypePredicate.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeQuery.ts create mode 100644 koala-wrapper/src/generated/peers/TSTypeReference.ts create mode 100644 koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSUnionType.ts create mode 100644 koala-wrapper/src/generated/peers/TSUnknownKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TSVoidKeyword.ts create mode 100644 koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts create mode 100644 koala-wrapper/src/generated/peers/TemplateElement.ts create mode 100644 koala-wrapper/src/generated/peers/TemplateLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/ThisExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ThrowStatement.ts create mode 100644 koala-wrapper/src/generated/peers/TryStatement.ts create mode 100644 koala-wrapper/src/generated/peers/TypeNode.ts create mode 100644 koala-wrapper/src/generated/peers/TypedAstNode.ts create mode 100644 koala-wrapper/src/generated/peers/TypedStatement.ts create mode 100644 koala-wrapper/src/generated/peers/TypeofExpression.ts create mode 100644 koala-wrapper/src/generated/peers/UnaryExpression.ts create mode 100644 koala-wrapper/src/generated/peers/UndefinedLiteral.ts create mode 100644 koala-wrapper/src/generated/peers/UpdateExpression.ts create mode 100644 koala-wrapper/src/generated/peers/ValidationInfo.ts create mode 100644 koala-wrapper/src/generated/peers/VariableDeclaration.ts create mode 100644 koala-wrapper/src/generated/peers/VariableDeclarator.ts create mode 100644 koala-wrapper/src/generated/peers/WhileStatement.ts create mode 100644 koala-wrapper/src/generated/peers/YieldExpression.ts create mode 100644 koala-wrapper/src/reexport-for-generated.ts create mode 100644 koala-wrapper/src/utils.ts create mode 100644 koala-wrapper/tools/issue_gen.mjs create mode 100644 koala-wrapper/tsconfig.json diff --git a/arkui-plugins/.gitignore b/arkui-plugins/.gitignore new file mode 100644 index 000000000..7f8e5351e --- /dev/null +++ b/arkui-plugins/.gitignore @@ -0,0 +1,17 @@ +node_modules/ +**/*/node_modules/ + +**/*/dist/ +**/*/build/ +build/ +lib/ + +*.tgz + +package-lock.json +/**/*/package-lock.json + +coverage/ +**/*/generated + +test/demo/localtest/build_config.json diff --git a/arkui-plugins/BUILD.gn b/arkui-plugins/BUILD.gn new file mode 100755 index 000000000..a262ea4c0 --- /dev/null +++ b/arkui-plugins/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +npm_path = "//prebuilts/build-tools/common/nodejs/current/bin/npm" + +action("gen_ui_plugins") { + script = "build_ui_plugins.py" + args = [ + "--source_path", + rebase_path(get_path_info(".", "abspath")), + "--output_path", + rebase_path("$target_gen_dir"), + "--npm", + rebase_path(npm_path), + "--current_os", + "$current_os", + "--root_out_dir", + rebase_path(root_out_dir), + ] + outputs = [ "$target_gen_dir" ] +} + +ohos_copy("ui_plugin") { + deps = [ ":gen_ui_plugins" ] + sources = [ rebase_path("$target_gen_dir") ] + outputs = [ target_out_dir + "/$target_name" ] + module_source_dir = target_out_dir + "/$target_name" + module_install_name = "" + subsystem_name = "developtools" + part_name = "ace_ets2bundle" +} diff --git a/arkui-plugins/babel.config.js b/arkui-plugins/babel.config.js new file mode 100644 index 000000000..fe3d51b87 --- /dev/null +++ b/arkui-plugins/babel.config.js @@ -0,0 +1,42 @@ +/* + * 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. + */ + +module.exports = function(api) { + api.cache(true); + + const presets = ['@babel/typescript']; + const plugins = [ + '@babel/plugin-transform-modules-commonjs', + '@babel/plugin-proposal-class-properties', + [ + '@babel/plugin-transform-arrow-functions', + { + spec: true + } + ], + './custom-import-plugin' + ]; + const ignore = [ + '**/test/**', + '**/node_modules/**', + 'jest-test.config.ts' + ]; + + return { + presets, + plugins, + ignore + }; +}; diff --git a/arkui-plugins/build_ui_plugins.py b/arkui-plugins/build_ui_plugins.py new file mode 100755 index 000000000..0d56133ba --- /dev/null +++ b/arkui-plugins/build_ui_plugins.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import shutil +import subprocess +import sys +import tarfile + + +def copy_files(source_path, dest_path, is_file=False): + try: + if is_file: + os.makedirs(os.path.dirname(dest_path), exist_ok=True) + shutil.copy(source_path, dest_path) + else: + shutil.copytree(source_path, dest_path, dirs_exist_ok=True, + symlinks=True) + except Exception as err: + raise Exception("Copy files failed. Error: " + str(err)) from err + + +def run_cmd(cmd, execution_path=None): + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=execution_path) + stdout, stderr = proc.communicate(timeout=1000) + if proc.returncode != 0: + raise Exception(stderr.decode()) + + +def build(options): + build_cmd = [options.npm, 'run', 'compile:plugins'] + run_cmd(build_cmd, options.source_path) + + +def copy_output(options): + run_cmd(['rm', '-rf', options.output_path]) + copy_files(os.path.join(options.source_path, 'lib'), + os.path.join(options.output_path, 'lib')) + + copy_files(os.path.join(options.source_path, 'package.json'), + os.path.join(options.output_path, 'package.json'), True) + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--npm', help='path to a npm exetuable') + parser.add_argument('--source_path', help='path to build system source') + parser.add_argument('--output_path', help='path to output') + parser.add_argument('--root_out_dir', help='path to root out') + parser.add_argument('--current_os', help='current_os') + + options = parser.parse_args() + return options + + +def main(): + options = parse_args() + + build(options) + copy_output(options) + + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/arkui-plugins/common/abstract-visitor.ts b/arkui-plugins/common/abstract-visitor.ts new file mode 100644 index 000000000..3117118b9 --- /dev/null +++ b/arkui-plugins/common/abstract-visitor.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +export interface VisitorOptions { + isExternal?: boolean, + externalSourceName?: string +} + +export abstract class AbstractVisitor implements VisitorOptions { + public isExternal: boolean; + public externalSourceName?: string; + + constructor(options?: VisitorOptions) { + this.isExternal = options?.isExternal ?? false; + this.externalSourceName = options?.externalSourceName; + } + + indentation = 0 + + withIndentation(exec: () => T) { + this.indentation++ + const result = exec() + this.indentation-- + return result + } + + abstract visitor(node: arkts.AstNode): arkts.AstNode + + reset(): void { + this.indentation = 0; + } + + visitEachChild(node: arkts.AstNode): arkts.AstNode { + return this.withIndentation(() => + arkts.visitEachChild( + node, + it => this.visitor(it) + ) + ) + } +} diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts new file mode 100644 index 000000000..f79340995 --- /dev/null +++ b/arkui-plugins/common/arkts-utils.ts @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +export function annotation(name: string): arkts.AnnotationUsage { + const ident: arkts.Identifier = arkts.factory.createIdentifier(name).setAnnotationUsage(); + const annotation: arkts.AnnotationUsage = arkts.factory.createAnnotationUsage(ident); + + annotation.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ANNOTATION_USAGE; + ident.parent = annotation; + + return annotation; +} + +export function isAnnotation(node: arkts.AnnotationUsage, annoName: string) { + return node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === annoName; +} + +export function removeAnnotationByName( + annotations: readonly arkts.AnnotationUsage[], + annoName: string +): arkts.AnnotationUsage[] { + return annotations.filter((it) => !isAnnotation(it, annoName)); +} + +export function expectName(node: arkts.AstNode | undefined): string { + if (!node) { + throw new Error("Expected an identifier, got empty node"); + } + if (!arkts.isIdentifier(node)) { + throw new Error("Expected an identifier, got: " + arkts.nodeType(node).toString()); + } + return node.name; +} + +export function mangle(value: string): string { + return `__${value}`; +} + +export function backingField(originalName: string): string { + return mangle(`backing_${originalName}`); +} + +export function filterDefined(value: (T | undefined)[]): T[] { + return value.filter((it: T | undefined): it is T => it != undefined); +} + +export function collect(...value: (ReadonlyArray | T | undefined)[]): T[] { + const empty: (T | undefined)[] = [] + return filterDefined(empty.concat(...value)) +} + +export function matchPrefix(prefixCollection: string[], name: string): boolean { + for (const prefix of prefixCollection) { + if (name.startsWith(prefix)) { + return true; + } + } + return false; +} + +export function updateStructMetadata( + structInfo: arkts.StructInfo, + propertyName: string, + properties: string[], + modifiers: arkts.Es2pandaModifierFlags, + hasStateManagementType?: boolean +): arkts.StructInfo { + const metadata: Record = structInfo.metadata ?? {}; + metadata[propertyName] = { name: propertyName, properties, modifiers, hasStateManagementType }; + structInfo.metadata = metadata; + return structInfo; +} \ No newline at end of file diff --git a/arkui-plugins/common/debug.ts b/arkui-plugins/common/debug.ts new file mode 100644 index 000000000..7d13d26c8 --- /dev/null +++ b/arkui-plugins/common/debug.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as fs from 'fs'; +import * as path from 'path'; + +const isDebugLog: boolean = false; +const isDebugDump: boolean = false; + +export function getEnumName(enumType: any, value: number): string | undefined { + return enumType[value]; +} + +function mkDir(filePath: string): void { + const parent = path.join(filePath, '..'); + if (!(fs.existsSync(parent) && !fs.statSync(parent).isFile())) { + mkDir(parent); + } + fs.mkdirSync(filePath); +} + +export function debugDump(content: string, fileName: string, isInit: boolean): void { + if (!isDebugDump) return; + + const currentDirectory = process.cwd(); + const outputDir: string = path.resolve(currentDirectory, 'entry', 'build', 'default', 'generated', 'dist', 'cache'); + const filePath: string = path.resolve(outputDir, fileName); + if (!fs.existsSync(outputDir)) { + mkDir(outputDir); + } + try { + if (!isInit && fs.existsSync(filePath)) { + const existingContent = fs.readFileSync(filePath, 'utf8'); + const newContent = existingContent &&!existingContent.endsWith('\n') + ? existingContent + '\n' + content + : existingContent + content; + fs.writeFileSync(filePath, newContent, 'utf8'); + } else { + fs.writeFileSync(filePath, content, 'utf8'); + } + } catch (error) { + console.error('文件操作失败:', error); + } +} + +export function debugLog(message?: any, ...optionalParams: any[]): void { + if (!isDebugLog) return; + console.log(message, ...optionalParams); +} + +export function getDumpFileName( + state: number, + prefix: string, + index: number | undefined, + suffix: string +): string { + return `${state}_${prefix}_${index ?? ''}_${suffix}.sts`; +} diff --git a/arkui-plugins/common/etsglobal-remover.ts b/arkui-plugins/common/etsglobal-remover.ts new file mode 100644 index 000000000..d2936a10a --- /dev/null +++ b/arkui-plugins/common/etsglobal-remover.ts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { AbstractVisitor } from "./abstract-visitor" + +const ETSGLOBAL = "ETSGLOBAL" + +export class EtsglobalRemover extends AbstractVisitor { + visitor(node: arkts.AstNode): arkts.AstNode { + if (arkts.isEtsScript(node)) { + const keep = node.statements.filter((it) => { + return !(arkts.isClassDeclaration(it) && it.definition?.ident?.name == ETSGLOBAL) + }) + return arkts.factory.updateEtsScript( + node, + keep + ) + } + return node + } +} diff --git a/arkui-plugins/common/gensym-generator.ts b/arkui-plugins/common/gensym-generator.ts new file mode 100644 index 000000000..aa48a70f3 --- /dev/null +++ b/arkui-plugins/common/gensym-generator.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { getCommonPath } from "../path" +const common = require(getCommonPath()) +const UniqueId = common.UniqueId + +export class GenSymGenerator { + // Global for the whole program. + private static callCount: number = 0; + static instance: GenSymGenerator; + + // Set `stable` to true if you want to have more predictable values. + // For example for tests. + // Don't use it in production! + private constructor(public stableForTests: boolean = false) { + if (stableForTests) GenSymGenerator.callCount = 0; + } + + static getInstance(stableForTests: boolean = false): GenSymGenerator { + if (!this.instance) { + this.instance = new GenSymGenerator(stableForTests); + } + + return this.instance; + } + + sha1Id(callName: string): string { + const uniqId = new UniqueId(); + uniqId.addString("gensym uniqid"); + uniqId.addString(callName); + uniqId.addI32(GenSymGenerator.callCount++); + return uniqId.compute().substring(0, 7); + } + + stringId(callName: string): string { + return `${GenSymGenerator.callCount++}_${callName}_id`; + } + + id(callName: string = ""): string { + const positionId = (this.stableForTests) ? + this.stringId(callName) : + this.sha1Id(callName); + + const coreceToStr = parseInt(positionId, 16).toString(); + + // compiler use gensym%%_ but % is illegal before after-check phase + return `gensym___${coreceToStr}`; + } +} \ No newline at end of file diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts new file mode 100644 index 000000000..6c331858c --- /dev/null +++ b/arkui-plugins/common/plugin-context.ts @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +// TODO: move this to arkts-api +export class PluginContext { + private ast: arkts.EtsScript | undefined; + private program: arkts.Program | undefined; + private projectConfig: ProjectConfig | undefined; + + constructor() { + this.ast = undefined; + this.program = undefined; + this.projectConfig = undefined; + } + + public setArkTSAst(ast: arkts.EtsScript): void { + this.ast = ast; + } + + public getArkTSAst(): arkts.EtsScript | undefined { + return this.ast; + } + + public setArkTSProgram(program: arkts.Program): void { + this.program = program; + } + + public getArkTSProgram(): arkts.Program | undefined { + return this.program; + } + + public setProjectConfig(projectConfig: ProjectConfig): void { + throw new Error("do not set projectConfig!"); + } + + public getProjectConfig(): ProjectConfig | undefined { + return this.projectConfig; + } +} + +export interface ProjectConfig { + bundleName: string, + moduleName: string +} + +export type PluginHandlerFunction = () => void; + +export type PluginHandlerObject = { + order: 'pre' | 'post' | undefined + handler: PluginHandlerFunction +}; + +export type PluginHandler = PluginHandlerFunction | PluginHandlerObject; + +export interface Plugins { + name: string; + afterNew?: PluginHandler, + parsed?: PluginHandler, + scopeInited?: PluginHandler, + checked?: PluginHandler, + lowered?: PluginHandler, + asmGenerated?: PluginHandler, + binGenerated?: PluginHandler, + clean?: PluginHandler, +}; + +export type PluginState = keyof Omit; + +export type PluginExecutor = { + name: string + handler: PluginHandlerFunction +}; diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts new file mode 100644 index 000000000..e1c5281f8 --- /dev/null +++ b/arkui-plugins/common/predefines.ts @@ -0,0 +1,64 @@ +/* + * 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. + */ + +export const EXTERNAL_SOURCE_PREFIX_NAMES: string[] = [ + "std", + "escompat" +]; + +export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ + "@ohos.arkui" +]; + +export const IMPORT_SOURCE_MAP: Map> = new Map>([ + ["@ohos.arkui.component", new Set(["$r", "$rawfile", "ArkReusableStructBase", "Reusable"])], + ["@ohos.arkui.external", new Set(["_r", "_rawfile"])], + ["@ohos.arkui.stateManagement", new Set([ + "State", + "Prop", + "Provide", + "Consume", + "StorageLink", + "StorageProp", + "LocalStorageLink", + "LocalStorageProp", + "StateDecoratedVariable", + "MutableState", + "contextLocalStateOf", + "contextLocal", + "observableProxy", + "SyncedProperty", + "propState", + "AppStorageLinkState", + "DecoratedMutableVariable", + "LinkDecoratedVariable", + "PropDecoratedVariable", + "StorageLinkDecoratedVariable", + "StoragePropDecoratedVariable" + ])] +]); + +export const OUTPUT_DEPENDENCY_MAP: Map = new Map([ + ["$r", ["_r"]], + ["$rawfile", ["_rawfile"]], + ["State", ["StateDecoratedVariable"]], + ["Link", ["LinkDecoratedVariable", "DecoratedMutableVariable"]], + ["Prop", ["PropDecoratedVariable"]], + ["Provide", ["MutableState", "contextLocalStateOf", "observableProxy"]], + ["Consume", ["MutableState", "contextLocal", "observableProxy"]], + ["StorageProp", ["StoragePropDecoratedVariable"]], + ["Reusable", ["ArkReusableStructBase"]], + ["StorageLink", ["StorageLinkDecoratedVariable"]] +]); \ No newline at end of file diff --git a/arkui-plugins/common/print-visitor.ts b/arkui-plugins/common/print-visitor.ts new file mode 100644 index 000000000..9a48a2085 --- /dev/null +++ b/arkui-plugins/common/print-visitor.ts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { AbstractVisitor } from "../common/abstract-visitor"; + +export class PrintVisitor extends AbstractVisitor { + private result = "" + + private printNode(node: arkts.AstNode) { + return `${" ".repeat(4 * this.indentation) + node.constructor.name} ${this.nameIfIdentifier(node)}` + } + + private nameIfIdentifier(node: arkts.AstNode): string { + return arkts.isIdentifier(node) ? `'${node.name}'` : "" + } + + visitor(node: arkts.AstNode): arkts.AstNode { + console.log(this.printNode(node)) + return this.visitEachChild(node) + } +} diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts new file mode 100644 index 000000000..56f796690 --- /dev/null +++ b/arkui-plugins/common/program-visitor.ts @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { AbstractVisitor, VisitorOptions } from "./abstract-visitor"; +import { matchPrefix } from "./arkts-utils"; +import { debugDump, getEnumName, getDumpFileName } from "./debug"; + +export interface ProgramVisitorOptions extends VisitorOptions { + pluginName: string; + state: arkts.Es2pandaContextState; + visitors: AbstractVisitor[]; + skipPrefixNames: string[]; +} + +export class ProgramVisitor extends AbstractVisitor { + private readonly pluginName: string; + private readonly state: arkts.Es2pandaContextState; + private readonly visitors: AbstractVisitor[]; + private readonly skipPrefixNames: string[]; + private filenames: Map; + + constructor(options: ProgramVisitorOptions) { + super(options); + this.pluginName = options.pluginName + this.state = options.state; + this.visitors = options.visitors; + this.skipPrefixNames = options.skipPrefixNames ?? []; + this.filenames = new Map(); + } + + reset(): void { + super.reset(); + this.filenames = new Map(); + } + + programVisitor(program: arkts.Program): arkts.Program { + const skipPrefixes: string[] = this.skipPrefixNames; + + const visited = new Set(); + const queue: arkts.Program[] = [program]; + + while (queue.length > 0) { + const currProgram = queue.shift()!; + if (visited.has(currProgram.peer)) { + continue; + } + + if (currProgram.peer !== program.peer) { + const name: string = this.filenames.get(currProgram.peer)!; + debugDump( + currProgram.astNode.dumpSrc(), + getDumpFileName(this.state, "ORI", undefined, name), + true + ); + const script = this.visitor(currProgram.astNode, name); + if (script) { + debugDump( + script.dumpSrc(), + getDumpFileName(this.state, this.pluginName, undefined, name), + true + ); + } + } + + visited.add(currProgram.peer); + + for (const externalSource of currProgram.externalSources) { + // TODO: this is very time-consuming... + if (matchPrefix(skipPrefixes, externalSource.getName())) { + continue; + } + + const nextProgramArr: arkts.Program[] = externalSource.programs ?? []; + for (const nextProgram of nextProgramArr) { + this.filenames.set(nextProgram.peer, externalSource.getName()); + if (!visited.has(nextProgram.peer)) { + queue.push(nextProgram); + } + } + } + } + + let programScript = program.astNode; + programScript = this.visitor(programScript, this.externalSourceName); + + return program; + } + + visitor(node: arkts.AstNode, externalSourceName?: string): arkts.EtsScript { + let script: arkts.EtsScript = node as arkts.EtsScript; + let count: number = 0; + for (const transformer of this.visitors) { + transformer.isExternal = !!externalSourceName; + transformer.externalSourceName = externalSourceName; + script = transformer.visitor(script) as arkts.EtsScript; + transformer.reset(); + arkts.setAllParents(script); + if (!transformer.isExternal) { + debugDump( + script.dumpSrc(), + getDumpFileName(this.state, this.pluginName, count, transformer.constructor.name), + true + ); + count += 1; + } + } + return script; + } +} \ No newline at end of file diff --git a/arkui-plugins/custom-import-plugin.js b/arkui-plugins/custom-import-plugin.js new file mode 100644 index 000000000..84b8a6bd5 --- /dev/null +++ b/arkui-plugins/custom-import-plugin.js @@ -0,0 +1,48 @@ +/* + * 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. + */ + + +const path = require('path'); + +module.exports = function (babel) { + const { types: t } = babel; + + return { + name: 'custom-import-plugin', + visitor: { + ImportDeclaration(pathNode) { + const sourceValue = pathNode.node.source.value; + if (sourceValue === '@koalaui/libarkts' && pathNode.node.specifiers.length === 1 && t.isImportNamespaceSpecifier(pathNode.node.specifiers[0])) { + const currentFileDir = path.dirname(pathNode.hub.file.opts.filename); + const configDir = process.cwd(); + const relativePath = path.relative(currentFileDir, configDir); + const importPath = relativePath ? path.join(relativePath, 'path') : './path'; + + const newImport = t.importDeclaration( + [t.importSpecifier(t.identifier('getArktsPath'), t.identifier('getArktsPath'))], + t.stringLiteral(importPath) + ); + + const requireCall = t.callExpression(t.identifier('require'), [t.callExpression(t.identifier('getArktsPath'), [])]); + const arkts = t.variableDeclaration('const', [ + t.variableDeclarator(t.identifier('arkts'), requireCall) + ]); + + pathNode.replaceWithMultiple([newImport, arkts]); + } + } + } + }; +}; \ No newline at end of file diff --git a/arkui-plugins/interop-plugins/decl_transformer.ts b/arkui-plugins/interop-plugins/decl_transformer.ts new file mode 100644 index 000000000..2aee8e9f5 --- /dev/null +++ b/arkui-plugins/interop-plugins/decl_transformer.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; + +import { AbstractVisitor } from "../common/abstract-visitor"; + +import { debugLog } from '../common/debug'; + +export class DeclTransformer extends AbstractVisitor { + constructor(private options?: interop.DeclTransformerOptions) { + super(); + } + + processComponent(node: arkts.StructDeclaration): arkts.ClassDeclaration { + const className = node.definition?.ident?.name; + if (!className) { + throw "Non Empty className expected for Component"; + } + + let newDec: arkts.ClassDeclaration = arkts.factory.createClassDeclaration(node.definition); + + const newDefinition = arkts.factory.updateClassDefinition( + newDec.definition!, + newDec.definition?.ident, + undefined, + undefined, + newDec.definition?.implements!, + undefined, + undefined, + node.definition?.body, + newDec.definition?.modifiers!, + arkts.classDefinitionFlags(newDec.definition!) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); + + arkts.factory.updateClassDeclaration(newDec, newDefinition); + newDec.modifiers = node.modifiers; + return newDec; + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + let astNode:arkts.AstNode = beforeChildren; + if (arkts.isEtsScript(astNode)) { + astNode = this.transformImportDecl(astNode); + } + + const node = this.visitEachChild(astNode); + if (arkts.isStructDeclaration(node)) { + debugLog(`DeclTransformer:before:flag:${arkts.classDefinitionIsFromStructConst(node.definition!)}`); + arkts.classDefinitionSetFromStructModifier(node.definition!); + let newnode = this.processComponent(node); + debugLog(`DeclTransformer:after:flag:${arkts.classDefinitionIsFromStructConst(newnode.definition!)}`); + return newnode; + } + return node; + } + + transformImportDecl(estNode: arkts.AstNode):arkts.AstNode { + if (!arkts.isEtsScript(estNode)) { + return estNode; + } + + let statements = estNode.statements.filter(node => this.isImportDeclarationNeedFilter(node)) + .map(node => this.updateImportDeclaration(node)); + + return arkts.factory.updateEtsScript(estNode,statements) + } + + isImportDeclarationNeedFilter(astNode: arkts.AstNode):boolean { + return !arkts.isETSImportDeclaration(astNode); + } + + updateImportDeclaration(astNode: arkts.AstNode):arkts.AstNode { + return astNode; + } +} diff --git a/arkui-plugins/interop-plugins/emit_transformer.ts b/arkui-plugins/interop-plugins/emit_transformer.ts new file mode 100644 index 000000000..dc1b6df03 --- /dev/null +++ b/arkui-plugins/interop-plugins/emit_transformer.ts @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; + +import { AbstractVisitor } from "../common/abstract-visitor"; + +import { debugLog } from '../common/debug'; + +export class EmitTransformer extends AbstractVisitor { + constructor(private options?: interop.EmitTransformerOptions) { + super(); + } + + processComponent(node: arkts.ClassDeclaration): arkts.ClassDeclaration { + const className = node.definition?.ident?.name; + if (!className) { + throw "Non Empty className expected for Component"; + } + + const newDefinition = arkts.factory.updateClassDefinition( + node.definition, + node.definition?.ident, + undefined, + undefined, + node.definition?.implements, + undefined, + undefined, + node.definition?.body, + node.definition?.modifiers, + arkts.classDefinitionFlags(node.definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); + + let newDec: arkts.ClassDeclaration = arkts.factory.updateClassDeclaration(node, newDefinition); + + debugLog(`DeclTransformer:checked:struct_ast:${newDefinition.dumpJson()}`); + newDec.modifiers = node.modifiers; + return newDec; + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + const node = this.visitEachChild(beforeChildren); + if (arkts.isClassDeclaration(node) && arkts.classDefinitionIsFromStructConst(node.definition!)) { + return this.processComponent(node); + } + return node; + } +} diff --git a/arkui-plugins/interop-plugins/index.ts b/arkui-plugins/interop-plugins/index.ts new file mode 100644 index 000000000..f2c502e43 --- /dev/null +++ b/arkui-plugins/interop-plugins/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { interopPlugin } from './interop_plugin'; + +export function interopTransform() { + return interopPlugin; +} diff --git a/arkui-plugins/interop-plugins/interop_plugin.ts b/arkui-plugins/interop-plugins/interop_plugin.ts new file mode 100644 index 000000000..b998bac8f --- /dev/null +++ b/arkui-plugins/interop-plugins/interop_plugin.ts @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; + +import { DeclTransformer } from './decl_transformer'; +import { EmitTransformer } from './emit_transformer'; +import { ProgramVisitor } from "../common/program-visitor"; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from "../common/predefines"; + +import { debugLog } from '../common/debug'; + +export const interopPlugin: interop.Plugin = { + name: 'interop-plugin', + parsed(this: interop.PluginContext) { + debugLog("interopTransform:parsed"); + let node = this.getArkTSAst(); + + if (node) { + debugLog("interopTransform:parsed:before:source: ", node.dumpSrc()); + debugLog("interopTransform:parsed:before:ast: ", node.dumpJson()); + + let script: arkts.EtsScript = node as arkts.EtsScript; + + const declTransformer = new DeclTransformer({ + arkui: "@koalaui.arkts-arkui.StructParse" as interop.TransfromerName + }); + + const programVisitor = new ProgramVisitor({ + pluginName: "decl", + state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + visitors: [declTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES + }); + + script = programVisitor.visitor(script); + + debugLog("interopTransform:parsed:after:source: ", script.dumpSrc()); + debugLog("interopTransform:parsed:after:ast: ", script.dumpJson()); + + this.setArkTSAst(script); + return script as interop.EtsScript; + } + }, + checked(this: interop.PluginContext) { + debugLog("interopTransform:checked"); + let node = this.getArkTSAst(); + if (node) { + debugLog("interopTransform:checked:before:source: ", node.dumpSrc()); + debugLog("interopTransform:parsed:before:ast: ", node.dumpJson()); + + let script: arkts.EtsScript = node as arkts.EtsScript; + + const emitTransformer = new EmitTransformer({ + arkui: "@koalaui.arkts-arkui.EmitBase" as interop.TransfromerName + }); + + const programVisitor = new ProgramVisitor({ + pluginName: "emit", + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [emitTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES + }); + + // script = programVisitor.visitor(script); + + debugLog("interopTransform:checked:after:source: ", script.dumpSrc()); + debugLog("interopTransform:checked:after:ast: ", script.dumpJson()); + + this.setArkTSAst(script); + return script as interop.EtsScript; + } + } +} diff --git a/arkui-plugins/interop-plugins/types.ts b/arkui-plugins/interop-plugins/types.ts new file mode 100644 index 000000000..cefbb302d --- /dev/null +++ b/arkui-plugins/interop-plugins/types.ts @@ -0,0 +1,56 @@ +/* + * 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. + */ + +namespace interop { + export type NativePointer = number; + + export interface PluginContext { + setArkTSAst(ast: Node): void; + getArkTSAst(): Node | undefined; + setArkTSProgram(program: Node): void; + getArkTSProgram(): Node | undefined; + setProjectConfig(projectConfig: Node): void; + getProjectConfig(): Node | undefined; + } + + export interface ArktsObject { + readonly peer: NativePointer; + } + + export interface Node extends ArktsObject { + get originalPeer(): NativePointer; + set originalPeer(peer: NativePointer); + dumpJson(): string; + dumpSrc(): string; + } + + export interface EtsScript extends Node {} + + export interface Plugin { + name: string, + parsed?(context: PluginContext): EtsScript | undefined; + checked?(context: PluginContext): EtsScript | undefined; + } + + export type TransfromerName = string & {__TransfromerNameBrand: any }; + + export interface EmitTransformerOptions { + arkui: TransfromerName; + } + + export interface DeclTransformerOptions { + arkui: TransfromerName; + } +} diff --git a/arkui-plugins/jest-test.config.ts b/arkui-plugins/jest-test.config.ts new file mode 100644 index 000000000..4b278d2e6 --- /dev/null +++ b/arkui-plugins/jest-test.config.ts @@ -0,0 +1,33 @@ +/* + * 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. + */ + +export default { + testEnvironment: 'node', + transform: { + '^.+\\.ts$': [ + 'ts-jest', + { isolatedModules: true } + ] + }, + testRegex: './test/ut/.+\\.test\\.ts$', + moduleFileExtensions: ['ts', 'js', 'json', 'node'], + coverageDirectory: './test/report', + collectCoverageFrom: [ + 'common/**', + 'memo-plugins/**', + 'ui-plugins/**', + ], + verbose: true +} \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts new file mode 100644 index 000000000..004b9496f --- /dev/null +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -0,0 +1,443 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { factory } from "./memo-factory" +import { AbstractVisitor, VisitorOptions } from "../common/abstract-visitor" +import { + PositionalIdTracker, + castFunctionExpression, + castParameters, + hasMemoAnnotation, + hasMemoIntrinsicAnnotation, + hasMemoStableAnnotation, + isStandaloneArrowFunction, + isVoidType, + removeMemoAnnotation +} from "./utils" +import { ParameterTransformer } from "./parameter-transformer" +import { ReturnTransformer } from "./return-transformer" +import { SignatureTransformer } from "./signature-transformer" + +function mayAddLastReturn(node: arkts.BlockStatement): boolean { + return node.statements.length > 0 && + !arkts.isReturnStatement(node.statements[node.statements.length - 1]) && + !arkts.isThrowStatement(node.statements[node.statements.length - 1]) +} + +function updateFunctionBody( + node: arkts.BlockStatement, + parameters: arkts.ETSParameterExpression[], + returnTypeAnnotation: arkts.TypeNode | undefined, + stableThis: boolean, + hash: arkts.NumberLiteral | arkts.StringLiteral +): [ + arkts.BlockStatement, + arkts.VariableDeclaration | undefined, + arkts.ReturnStatement | arkts.BlockStatement | undefined, +] { + let returnTypeAnno = (!returnTypeAnnotation ||stableThis) + ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + : returnTypeAnnotation; + const scopeDeclaration = factory.createScopeDeclaration( + returnTypeAnno, + hash, parameters.length + ) + const memoParameters = parameters.map((name, id) => { return factory.createMemoParameterDeclarator(id, name.identifier.name) }) + const memoParametersDeclaration = memoParameters.length + ? [ + arkts.factory.createVariableDeclaration( + 0, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, + memoParameters, + ) + ] + : [] + const syntheticReturnStatement = factory.createSyntheticReturnStatement(stableThis) + const isVoidValue = isVoidType(returnTypeAnno) + const unchangedCheck = factory.createIfStatementWithSyntheticReturnStatement(syntheticReturnStatement, isVoidValue) + if (node) { + return [ + arkts.factory.updateBlock( + node, + [ + scopeDeclaration, + ...memoParametersDeclaration, + unchangedCheck, + ...node.statements, + ...(mayAddLastReturn(node) ? [arkts.factory.createReturnStatement()] : []), + ] + ), + memoParametersDeclaration.length ? memoParametersDeclaration[0] : undefined, + syntheticReturnStatement, + ] + } else { + return [ + node, + memoParametersDeclaration.length ? memoParametersDeclaration[0] : undefined, + syntheticReturnStatement, + ] + } +} + +function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | undefined): boolean { + if (!typeAnnotation) return false; + if (arkts.isETSFunctionType(typeAnnotation)) { + return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation) + } else if (arkts.isETSUnionType(typeAnnotation)) { + return typeAnnotation.types.some((type) => ( + arkts.isETSFunctionType(type) + && (hasMemoAnnotation(type) || hasMemoIntrinsicAnnotation(type)) + )); + } + return false; +} + +function updateMemoTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): arkts.TypeNode | undefined { + if (!typeAnnotation) return undefined; + if (!arkts.isTypeNode(typeAnnotation)) return undefined; + + if (typeAnnotation && arkts.isETSFunctionType(typeAnnotation)) { + return factory.updateFunctionTypeWithMemoParameters(typeAnnotation); + } else if (typeAnnotation && arkts.isETSUnionType(typeAnnotation)) { + return arkts.factory.updateUnionType( + typeAnnotation, + typeAnnotation.types.map((it) => { + if (arkts.isETSFunctionType(it)) { + return factory.updateFunctionTypeWithMemoParameters(it); + } + return it; + }) + ) + } + return typeAnnotation; +} + +type ScopeInfo = { + name?: string, + isMemo: boolean +} + +export interface FunctionTransformerOptions extends VisitorOptions { + positionalIdTracker: PositionalIdTracker; + parameterTransformer: ParameterTransformer; + returnTransformer: ReturnTransformer; + signatureTransformer: SignatureTransformer; +} + +export class FunctionTransformer extends AbstractVisitor { + private readonly positionalIdTracker: PositionalIdTracker; + private readonly parameterTransformer: ParameterTransformer; + private readonly returnTransformer: ReturnTransformer; + private readonly signatureTransformer: SignatureTransformer; + + constructor(options: FunctionTransformerOptions) { + super(options) + this.positionalIdTracker = options.positionalIdTracker + this.parameterTransformer = options.parameterTransformer + this.returnTransformer = options.returnTransformer + this.signatureTransformer = options.signatureTransformer + } + + private scopes: ScopeInfo[] = [] + private stable: number = 0 + + reset() { + super.reset(); + this.scopes = []; + this.stable = 0; + this.parameterTransformer.reset(); + this.returnTransformer.reset(); + this.signatureTransformer.reset(); + } + + enter(node: arkts.AstNode) { + if (arkts.isMethodDefinition(node)) { + const name = node.name.name + const isMemo = hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction) + this.scopes.push({ name , isMemo }) + } + if ( + arkts.isClassProperty(node) + && !!node.key + && arkts.isIdentifier(node.key) + && !!node.value + && arkts.isArrowFunctionExpression(node.value) + ) { + const name = node.key.name; + let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); + isMemo ||= hasMemoAnnotation(node.value) || hasMemoIntrinsicAnnotation(node.value); + isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + this.scopes.push({ name , isMemo }); + } + if (isStandaloneArrowFunction(node)) { + const name = undefined; + const isMemo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + this.scopes.push({ name , isMemo }); + } + if ( + arkts.isTSTypeAliasDeclaration(node) + && !!node.id + && !!node.typeAnnotation + ) { + const name = node.id.name; + let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); + isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + this.scopes.push({ name , isMemo }); + } + if (arkts.isClassDefinition(node)) { + if (hasMemoStableAnnotation(node)) { + this.stable++ + } + } + return this + } + + exit(node: arkts.AstNode) { + if (arkts.isMethodDefinition(node)) { + this.scopes.pop() + } + if (arkts.isClassDefinition(node)) { + if (hasMemoStableAnnotation(node)) { + this.stable-- + } + } + return this + } + + enterAnonymousScope(node: arkts.ScriptFunction) { + const name = undefined + const isMemo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) + this.scopes.push({ name, isMemo }) + return this + } + + exitAnonymousScope() { + this.scopes.pop() + return this + } + + checkMemoCallInMethod(decl: arkts.MethodDefinition) { + if (this.scopes[this.scopes.length - 1].isMemo == false) { + if (this.scopes[this.scopes.length - 1].name) { + console.error(`Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${this.scopes[this.scopes.length - 1].name}`) + throw "Invalid @memo usage" + } else { + console.error(`Attempt to call @memo-method ${decl.name.name} from anonymous non-@memo-method`) + throw "Invalid @memo usage" + } + } + return this + } + + checkMemoCallInFunction() { + if (this.scopes[this.scopes.length - 1]?.isMemo == false) { + console.error(`Attempt to call @memo-function`) + throw "Invalid @memo usage" + } + return this + } + + updateScriptFunction( + scriptFunction: arkts.ScriptFunction, + name: string = "", + ): arkts.ScriptFunction { + const isStableThis = this.stable > 0 && scriptFunction.returnTypeAnnotation !== undefined && arkts.isTSThisType(scriptFunction.returnTypeAnnotation) + const [body, memoParametersDeclaration, syntheticReturnStatement] = updateFunctionBody( + scriptFunction.body as arkts.BlockStatement, + castParameters(scriptFunction.params), + scriptFunction.returnTypeAnnotation, + isStableThis, + this.positionalIdTracker.id(name), + ) + const afterParameterTransformer = this.parameterTransformer + .withParameters(scriptFunction.params as arkts.ETSParameterExpression[]) + .skip(memoParametersDeclaration) + .visitor(body) + const afterReturnTransformer = this.returnTransformer + .skip(syntheticReturnStatement) + .rewriteThis(this.stable > 0) + .visitor(afterParameterTransformer) + const updateScriptFunction = arkts.factory.updateScriptFunction( + scriptFunction, + afterReturnTransformer, + arkts.FunctionSignature.createFunctionSignature( + scriptFunction.typeParams, + [ + ...factory.createHiddenParameters(), + ...scriptFunction.params // we handle function params with signature-transformer + ], + scriptFunction.returnTypeAnnotation, + scriptFunction.hasReceiver + ), + scriptFunction.flags, + scriptFunction.modifiers + ) + return updateScriptFunction; + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + this.enter(beforeChildren) + const node = this.visitEachChild(beforeChildren) + this.exit(beforeChildren) + if (arkts.isMethodDefinition(node)) { + if ( + node.scriptFunction.body + && (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) + ) { + return arkts.factory.updateMethodDefinition( + node, + node.kind, + node.name, + arkts.factory.createFunctionExpression( + this.signatureTransformer.visitor( + removeMemoAnnotation( + this.updateScriptFunction(node.scriptFunction, node.name.name) + ) + + ) + ), + node.modifiers, + false + ); + } + + return arkts.factory.updateMethodDefinition( + node, + node.kind, + node.name, + arkts.factory.createFunctionExpression( + this.signatureTransformer.visitor(node.scriptFunction), + ), + node.modifiers, + false + ); + } + if (arkts.isCallExpression(node)) { + const expr = node.expression + const decl = arkts.getDecl(expr) + if (decl && arkts.isMethodDefinition(decl) && (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction))) { + this.checkMemoCallInMethod(decl) + const updatedArguments = node.arguments.map((it, index) => { + const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type + if (type && arkts.isETSFunctionType(type)) { + if ( + !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) + && !hasMemoIntrinsicAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) + ) { + return it //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) + } + if (arkts.isArrowFunctionExpression(it)) { + this.enterAnonymousScope(it.scriptFunction) + const res = this.updateScriptFunction(it.scriptFunction) + this.exitAnonymousScope() + return arkts.factory.updateArrowFunction(it, res) + } + } + return it + }) + return arkts.factory.updateCallExpression( + node, + node.expression, + undefined, + [...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), ...updatedArguments] + ) + } + if (isStandaloneArrowFunction(node.expression)) { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== node.expression.scriptFunction.id?.name) return node; + this.exitAnonymousScope(); + this.checkMemoCallInFunction(); + + this.enterAnonymousScope(node.expression.scriptFunction); + const res = this.updateScriptFunction(node.expression.scriptFunction, node.expression.scriptFunction.id?.name); + this.exitAnonymousScope(); + + return arkts.factory.updateCallExpression( + node, + arkts.factory.updateArrowFunction(node.expression, res), + node.typeArguments, + [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...node.arguments] + ) + } + } + if( + arkts.isClassProperty(node) + && !!node.key + && arkts.isIdentifier(node.key) + && !!node.value + && arkts.isArrowFunctionExpression(node.value) + ) { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== node.key?.name) return node; + this.exitAnonymousScope(); + + this.enterAnonymousScope(node.value.scriptFunction); + const res = this.updateScriptFunction(node.value.scriptFunction, node.key.name); + this.exitAnonymousScope(); + + let typeAnnotation: arkts.TypeNode | undefined; + if ( + !!node.typeAnnotation + && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation)) + ) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-property ${node.key.name}`); + throw "Invalid @memo usage"; + } + + return arkts.factory.updateClassProperty( + node, + node.key, + arkts.factory.updateArrowFunction(node.value, res), + typeAnnotation, + node.modifiers, + node.isComputed + ); + } + if (arkts.isTSTypeAliasDeclaration(node)) { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== node.id?.name) return node; + this.exitAnonymousScope(); + + let typeAnnotation: arkts.TypeNode | undefined; + if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-type ${node.id!.name}`); + throw "Invalid @memo usage"; + } + + return arkts.factory.updateTSTypeAliasDeclaration( + node, + node.id, + node.typeParams, + typeAnnotation + ); + } + if (isStandaloneArrowFunction(node)) { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== node.scriptFunction.id?.name) return node; + this.exitAnonymousScope(); + + this.enterAnonymousScope(node.scriptFunction); + const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); + this.exitAnonymousScope(); + + return arkts.factory.updateArrowFunction( + node, + res + ); + } + return node + } +} \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/import-transformer.ts b/arkui-plugins/memo-plugins/import-transformer.ts new file mode 100644 index 000000000..aece85ce4 --- /dev/null +++ b/arkui-plugins/memo-plugins/import-transformer.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { AbstractVisitor } from "../common/abstract-visitor" +import { factory } from "./memo-factory" + +export class ImportTransformer extends AbstractVisitor { + visitor(node: arkts.AstNode): arkts.AstNode { + if (node instanceof arkts.EtsScript) { + factory.createContextTypesImportDeclaration(); + return arkts.factory.updateEtsScript( + node, + node.statements + ) + } + return node + } +} diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts new file mode 100644 index 000000000..841b6410a --- /dev/null +++ b/arkui-plugins/memo-plugins/index.ts @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { Plugins, PluginContext } from "../common/plugin-context"; +import { FunctionTransformer } from "./function-transformer"; +import { PositionalIdTracker } from "./utils"; +import { ReturnTransformer } from "./return-transformer"; +import { ParameterTransformer } from "./parameter-transformer"; +import { ProgramVisitor } from "../common/program-visitor"; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from "../common/predefines"; +import { debugDump, debugLog, getDumpFileName } from "../common/debug" +import { SignatureTransformer } from "./signature-transformer"; + +export function unmemoizeTransform(): Plugins { + return { + name: 'memo-plugin', + checked(this: PluginContext) { + console.log("[MEMO PLUGIN] AFTER CHECKED ENTER"); + let program = arkts.arktsGlobal.compilerContext.program; + let script = program.astNode; + if (script) { + debugLog("[BEFORE MEMO SCRIPT] script: ", script.dumpSrc()); + debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 5, "MEMO_AfterCheck_Begin"), true); + + const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); + const parameterTransformer = new ParameterTransformer({ positionalIdTracker }); + const returnTransformer = new ReturnTransformer(); + const signatureTransformer = new SignatureTransformer(); + const functionTransformer = new FunctionTransformer({ + positionalIdTracker, + parameterTransformer, + returnTransformer, + signatureTransformer + }); + + const programVisitor = new ProgramVisitor({ + pluginName: unmemoizeTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [functionTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES + }); + + program = programVisitor.programVisitor(program); + script = program.astNode; + + debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); + debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 6, "MEMO_AfterCheck_End"), true); + + arkts.recheckSubtree(script); + this.setArkTSAst(script); + console.log("[MEMO PLUGIN] AFTER CHECKED EXIT"); + return script; + } + console.log("[MEMO PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM"); + } + } +} \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts new file mode 100644 index 000000000..94bfcc855 --- /dev/null +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { RuntimeNames } from "./utils" + +export class factory { + // Importing + static createContextTypeImportSpecifier(): arkts.ImportSpecifier { + return arkts.factory.createImportSpecifier( + arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE), + arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE), + ) + } + static createIdTypeImportSpecifier(): arkts.ImportSpecifier { + return arkts.factory.createImportSpecifier( + arkts.factory.createIdentifier(RuntimeNames.ID_TYPE), + arkts.factory.createIdentifier(RuntimeNames.ID_TYPE), + ) + } + // TODO: Currently, import declaration can only be inserted at after-parsed stage. + static createContextTypesImportDeclaration(): void { + const source: arkts.StringLiteral = arkts.factory.createStringLiteral(RuntimeNames.CONTEXT_TYPE_DEFAULT_IMPORT); + // const resolvedSource: arkts.StringLiteral = arkts.factory.create1StringLiteral( + // arkts.ImportPathManager.create().resolvePath('', source.str) + // ); + const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + source, + [ + factory.createContextTypeImportSpecifier(), + factory.createIdTypeImportSpecifier() + ], + arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE + ) + // Insert this import at the top of the script's statements. + arkts.importDeclarationInsert(importDecl); + return; + } + + // Parameters + static createContextParameter(): arkts.ETSParameterExpression { + return arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + RuntimeNames.CONTEXT, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE) + ) + ) + ), + undefined + ) + } + static createIdParameter(): arkts.ETSParameterExpression { + return arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier(RuntimeNames.ID, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(RuntimeNames.ID_TYPE) + ) + ) + ), + undefined + ) + } + static createHiddenParameters(): arkts.ETSParameterExpression[] { + return [factory.createContextParameter(), factory.createIdParameter()] + } + static updateFunctionTypeWithMemoParameters(type: arkts.ETSFunctionType): arkts.ETSFunctionType { + return arkts.factory.updateFunctionType( + type, + arkts.factory.createFunctionSignature( + undefined, + [...factory.createHiddenParameters(), ...type.params], + type.returnType, + false, + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + ) + } + + // Arguments + static createContextArgument(): arkts.AstNode { + return arkts.factory.createIdentifier(RuntimeNames.CONTEXT) + } + static createIdArgument(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.AstNode { + return arkts.factory.createBinaryExpression( + arkts.factory.createIdentifier(RuntimeNames.ID), + hash, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS, + ) + } + static createHiddenArguments(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.AstNode[] { + return [factory.createContextArgument(), factory.createIdArgument(hash)] + } + + // Memo parameters + static createMemoParameterIdentifier(name: string): arkts.Identifier { + return arkts.factory.createIdentifier(`${RuntimeNames.PARAMETER}_${name}`) + } + static createMemoParameterDeclarator(id: number, name: string): arkts.VariableDeclarator { + return arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_CONST, + factory.createMemoParameterIdentifier(name), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(RuntimeNames.SCOPE), + arkts.factory.createIdentifier(RuntimeNames.INTERNAL_PARAMETER_STATE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createNumericLiteral(id), + arkts.factory.createIdentifier(name), + ], + ) + ) + } + static createMemoParameterAccess(name: string): arkts.MemberExpression { + return arkts.factory.createMemberExpression( + factory.createMemoParameterIdentifier(name), + arkts.factory.createIdentifier(RuntimeNames.VALUE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_GETTER, + false, + false, + ) + } + static createMemoParameterAccessMemoWithScope(name: string, hash: arkts.NumberLiteral | arkts.StringLiteral, passArgs?: arkts.AstNode[]): arkts.CallExpression { + const updatedArgs = passArgs ? passArgs : [] + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + factory.createMemoParameterIdentifier(name), + arkts.factory.createIdentifier(RuntimeNames.VALUE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_GETTER, + false, + false, + ), + undefined, + [...factory.createHiddenArguments(hash), ...updatedArgs], + ) + } + static createMemoParameterAccessMemoWithoutScope(name: string, hash: arkts.NumberLiteral | arkts.StringLiteral, passArgs?: arkts.AstNode[]): arkts.CallExpression { + const updatedArgs = passArgs ? passArgs : [] + return arkts.factory.createCallExpression( + arkts.factory.createIdentifier(name), + undefined, + [...factory.createHiddenArguments(hash), ...updatedArgs], + ) + } + static createMemoParameterAccessCall(name: string, hash: arkts.NumberLiteral | arkts.StringLiteral, passArgs?: arkts.AstNode[]): arkts.CallExpression { + const updatedArgs = passArgs ? passArgs : [] + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + factory.createMemoParameterIdentifier(name), + arkts.factory.createIdentifier(RuntimeNames.VALUE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_GETTER, + false, + false, + ), + undefined, + [...updatedArgs], + ) + } + + // Recache + static createScopeDeclaration(returnTypeAnnotation: arkts.TypeNode | undefined, hash: arkts.NumberLiteral | arkts.StringLiteral, cnt: number): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + 0, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_CONST, + arkts.factory.createIdentifier(RuntimeNames.SCOPE), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(RuntimeNames.CONTEXT), + arkts.factory.createIdentifier(RuntimeNames.INTERNAL_SCOPE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + returnTypeAnnotation ? [returnTypeAnnotation] : [arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID)], + [ + factory.createIdArgument(hash), + arkts.factory.createNumericLiteral(cnt) + ], + ) + ) + ] + ) + } + static createRecacheCall(arg?: arkts.AstNode): arkts.CallExpression { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(RuntimeNames.SCOPE), + arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE_NEW), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + arg ? [arg] : undefined, + ) + } + static createReturnThis(): arkts.BlockStatement { + return arkts.factory.createBlock([ + arkts.factory.createExpressionStatement( + factory.createRecacheCall() + ), + arkts.factory.createReturnStatement( + arkts.factory.createThisExpression() + ) + ]) + } + static createSyntheticReturnStatement(stableThis: boolean): arkts.ReturnStatement | arkts.BlockStatement { + if (!stableThis) { + return arkts.factory.createReturnStatement( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(RuntimeNames.SCOPE), + arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, + false, + false, + ), + ) + } + return arkts.factory.createBlock([ + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(RuntimeNames.SCOPE), + arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, + false, + false, + ), + arkts.factory.createReturnStatement( + arkts.factory.createThisExpression() + ) + ]) + } + static createIfStatementWithSyntheticReturnStatement( + syntheticReturnStatement: arkts.ReturnStatement | arkts.BlockStatement, + isVoidValue: boolean + ): arkts.IfStatement { + let returnStatement = syntheticReturnStatement; + if (isVoidValue && arkts.isReturnStatement(syntheticReturnStatement)) { + returnStatement = arkts.factory.createBlock([ + arkts.factory.createExpressionStatement( + syntheticReturnStatement.argument! + ), + arkts.factory.createReturnStatement() + ]) + } + return arkts.factory.createIfStatement( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(RuntimeNames.SCOPE), + arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE_OK), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, + false, + false, + ), + returnStatement, + ) + } + + // Compute + static createLambdaWrapper(node: arkts.Expression): arkts.ArrowFunctionExpression { + return arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + arkts.factory.createBlock([ + arkts.factory.createReturnStatement(node) + ]), + arkts.factory.createFunctionSignature( + undefined, + [], + undefined, + false, + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ) + } + static createComputeExpression(hash: arkts.NumberLiteral | arkts.StringLiteral, node: arkts.Expression): arkts.CallExpression { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(RuntimeNames.CONTEXT), + arkts.factory.createIdentifier(RuntimeNames.COMPUTE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [factory.createIdArgument(hash), factory.createLambdaWrapper(node)] + ) + } +} diff --git a/arkui-plugins/memo-plugins/memo-transformer.ts b/arkui-plugins/memo-plugins/memo-transformer.ts new file mode 100644 index 000000000..5fd6fe00a --- /dev/null +++ b/arkui-plugins/memo-plugins/memo-transformer.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { FunctionTransformer } from "./function-transformer" +import { PositionalIdTracker } from "./utils" +import { factory } from "./memo-factory" +import { ReturnTransformer } from "./return-transformer" +import { ParameterTransformer } from "./parameter-transformer" +import { EtsglobalRemover } from "../common/etsglobal-remover" +import { SignatureTransformer } from "./signature-transformer" + +export interface TransformerOptions { + trace?: boolean, + removeEtsglobal?: boolean +} + +export default function memoTransformer( + userPluginOptions?: TransformerOptions +) { + return (node0: arkts.EtsScript) => { + const node = (userPluginOptions?.removeEtsglobal ? new EtsglobalRemover().visitor(node0) : node0) as arkts.EtsScript + const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false) + const parameterTransformer = new ParameterTransformer({ + positionalIdTracker + }) + const returnTransformer = new ReturnTransformer() + const signatureTransformer = new SignatureTransformer() + const functionTransformer = new FunctionTransformer({ positionalIdTracker, parameterTransformer, returnTransformer, signatureTransformer }) + factory.createContextTypesImportDeclaration(); + return functionTransformer.visitor( + arkts.factory.updateEtsScript( + node, + node.statements + ) + ) + } +} + diff --git a/arkui-plugins/memo-plugins/parameter-transformer.ts b/arkui-plugins/memo-plugins/parameter-transformer.ts new file mode 100644 index 000000000..a734ca525 --- /dev/null +++ b/arkui-plugins/memo-plugins/parameter-transformer.ts @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as arkts from "@koalaui/libarkts" + +import { factory } from "./memo-factory" +import { AbstractVisitor, VisitorOptions } from "../common/abstract-visitor" +import { + hasMemoAnnotation, + hasMemoIntrinsicAnnotation, + isMemoParametersDeclaration, + PositionalIdTracker +} from "./utils" + +export interface ParameterTransformerOptions extends VisitorOptions { + positionalIdTracker: PositionalIdTracker +} + +export class ParameterTransformer extends AbstractVisitor { + private rewriteIdentifiers?: Map arkts.MemberExpression | arkts.Identifier> + private rewriteCalls?: Map arkts.CallExpression> + private skipNode?: arkts.VariableDeclaration + private readonly positionalIdTracker: PositionalIdTracker + + constructor(options: ParameterTransformerOptions) { + super(options) + this.positionalIdTracker = options.positionalIdTracker + } + + reset(): void { + super.reset(); + this.rewriteIdentifiers = undefined; + this.rewriteCalls = undefined; + this.skipNode = undefined; + } + + withParameters(parameters: arkts.ETSParameterExpression[]): ParameterTransformer { + this.rewriteCalls = new Map(parameters.filter(it => it.type && (arkts.isETSFunctionType(it.type) || arkts.isETSUnionType(it.type))).map((it) => { + return [it.peer, (passArgs: arkts.AstNode[]) => { + if (hasMemoAnnotation(it) || hasMemoIntrinsicAnnotation(it)) { + if (it.type && arkts.isETSFunctionType(it.type) && !it.optional) { + return factory.createMemoParameterAccessMemoWithScope(it.identifier.name, this.positionalIdTracker?.id(), passArgs) + } else { + return factory.createMemoParameterAccessMemoWithoutScope(it.identifier.name, this.positionalIdTracker?.id(), passArgs) + } + } + return factory.createMemoParameterAccessCall(it.identifier.name, this.positionalIdTracker?.id(), passArgs) + }] + })) + this.rewriteIdentifiers = new Map(parameters.map((it) => { + return [it.peer, () => { + if ((it.type && arkts.isETSFunctionType(it.type)) || it.optional) { + return arkts.factory.createIdentifier(it.identifier.name) + } + return factory.createMemoParameterAccess(it.identifier.name) + }] + })) + return this + } + + skip(memoParametersDeclaration?: arkts.VariableDeclaration): ParameterTransformer { + this.skipNode = memoParametersDeclaration + return this + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + // TODO: temporary checking skip nodes by comparison with expected skip nodes + // Should be fixed when update procedure implemented properly + if (!beforeChildren) { + return beforeChildren; + } + if (/* beforeChildren === this.skipNode */ isMemoParametersDeclaration(beforeChildren)) { + return beforeChildren + } + if (arkts.isCallExpression(beforeChildren)) { + if (arkts.isIdentifier(beforeChildren.expression)) { + const decl = arkts.getDecl(beforeChildren.expression) + if (decl && arkts.isEtsParameterExpression(decl) && this.rewriteCalls?.has(decl.peer)) { + return this.rewriteCalls.get(decl.peer)!( + beforeChildren.arguments.map((it) => this.visitor(it)) + ) + } + } + } + const node = this.visitEachChild(beforeChildren) + if (arkts.isIdentifier(node)) { + const decl = arkts.getDecl(node) + if ((decl && arkts.isEtsParameterExpression(decl)) && this.rewriteIdentifiers?.has(decl.peer)) { + const res = this.rewriteIdentifiers.get(decl.peer)!() + if (arkts.isMemberExpression(res)) { + return res + } + } + } + return node + } +} diff --git a/arkui-plugins/memo-plugins/return-transformer.ts b/arkui-plugins/memo-plugins/return-transformer.ts new file mode 100644 index 000000000..01998194f --- /dev/null +++ b/arkui-plugins/memo-plugins/return-transformer.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { factory } from "./memo-factory" +import { AbstractVisitor } from "../common/abstract-visitor" +import { isSyntheticReturnStatement } from "./utils" + +export class ReturnTransformer extends AbstractVisitor { + private skipNode?: arkts.ReturnStatement | arkts.BlockStatement + private stableThis: boolean = false + + reset() { + super.reset(); + this.skipNode = undefined; + this.stableThis = false; + } + + skip(syntheticReturnStatement?: arkts.ReturnStatement | arkts.BlockStatement): ReturnTransformer { + this.skipNode = syntheticReturnStatement + return this + } + + rewriteThis(stableThis: boolean): ReturnTransformer { + this.stableThis = stableThis + return this + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + // TODO: temporary checking skip nodes by comparison with expected skip nodes + // Should be fixed when update procedure implemented properly + if (/* beforeChildren === this.skipNode */ isSyntheticReturnStatement(beforeChildren)) { + return beforeChildren; + } + if (arkts.isScriptFunction(beforeChildren)) { + return beforeChildren + } + const node = this.visitEachChild(beforeChildren) + if (arkts.isReturnStatement(node)) { + if (this.stableThis && node.argument && arkts.isThisExpression(node.argument)) { + return factory.createReturnThis() + } + return arkts.factory.createBlock([ + arkts.factory.createExpressionStatement( + factory.createRecacheCall(node.argument) + ), + node + ]); + } + return node + } +} \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts new file mode 100644 index 000000000..258f28f11 --- /dev/null +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { factory } from "./memo-factory" +import { hasMemoAnnotation, hasMemoIntrinsicAnnotation } from "./utils" +import { AbstractVisitor } from "../common/abstract-visitor" + +export class SignatureTransformer extends AbstractVisitor { + public modified = false + + reset(): void { + super.reset(); + this.modified = false; + } + + visitor(node: T, applyMemo: boolean = false): T { + if (arkts.isScriptFunction(node)) { + const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo + if (memo) { + this.modified = true + } + return arkts.factory.updateScriptFunction( + node, + node.body, + arkts.factory.createFunctionSignature( + node.typeParams, + [...(memo ? factory.createHiddenParameters() : []), ...node.params.map(it => this.visitor(it))], + node.returnTypeAnnotation + ? this.visitor(node.returnTypeAnnotation) + : memo ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) : undefined, + node.hasReceiver, + ), + node.flags, + node.modifiers + ) as any as T + } + if (arkts.isEtsParameterExpression(node)) { + const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) + if (!node.type) { + if (memo) { + console.error(`@memo parameter ${node.identifier.name} without type annotatation`) + throw "Invalid @memo usage" + } + return node + } + node.type = this.visitor(node.type, memo) + return node as any as T + } + if (arkts.isETSFunctionType(node)) { + const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo + if (memo) { + this.modified = true + } + return arkts.factory.updateFunctionType( + node, + arkts.factory.createFunctionSignature( + undefined, + [...(memo ? factory.createHiddenParameters() : []), ...node.params.map(it => this.visitor(it))], + this.visitor(node.returnType!), + false, + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + ) as any as T + } + if (arkts.isETSUnionType(node)) { + return arkts.factory.updateUnionType( + node, + node.types.map(it => this.visitor(it, applyMemo)) + ) as any as T + } + if (arkts.isETSUndefinedType(node)) { + return node as any as T + } + if (applyMemo) { + throw "Invalid @memo usage" + } + return node + } +} \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts new file mode 100644 index 000000000..91fd89356 --- /dev/null +++ b/arkui-plugins/memo-plugins/utils.ts @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as arkts from "@koalaui/libarkts" +import { getCommonPath } from "../path" +const common = require(getCommonPath()) +const UniqueId = common.UniqueId + +export enum RuntimeNames { + __CONTEXT = "__context", + __ID = "__id", + ANNOTATION = "memo", + ANNOTATION_INTRINSIC = "memo_intrinsic", + ANNOTATION_STABLE = "memo_stable", + COMPUTE = "compute", + CONTEXT = "__memo_context", + CONTEXT_TYPE = "__memo_context_type", + CONTEXT_TYPE_DEFAULT_IMPORT = "@ohos.arkui.StateManagement.runtime", + ID = "__memo_id", + ID_TYPE = "__memo_id_type", + INTERNAL_PARAMETER_STATE = "param", + INTERNAL_SCOPE = "scope", + INTERNAL_VALUE = "cached", + INTERNAL_VALUE_NEW = "recache", + INTERNAL_VALUE_OK = "unchanged", + PARAMETER = "__memo_parameter", + SCOPE = "__memo_scope", + VALUE = "value", +} + +function baseName(path: string): string { + return path.replace(/^.*\/(.*)$/, "$1") +} + +export class PositionalIdTracker { + // Global for the whole program. + static callCount: number = 0 + + // Set `stable` to true if you want to have more predictable values. + // For example for tests. + // Don't use it in production! + constructor(public filename: string, public stableForTests: boolean = false) { + if (stableForTests) PositionalIdTracker.callCount = 0 + } + + sha1Id(callName: string, fileName: string): string { + const uniqId = new UniqueId() + uniqId.addString("memo call uniqid") + uniqId.addString(fileName) + uniqId.addString(callName) + uniqId.addI32(PositionalIdTracker.callCount++) + return uniqId.compute().substring(0, 7) + } + + stringId(callName: string, fileName: string): string { + return `${PositionalIdTracker.callCount++}_${callName}_id_DIRNAME/${fileName}` + } + + id(callName: string = ""): arkts.NumberLiteral | arkts.StringLiteral { + + const fileName = this.stableForTests ? + baseName(this.filename) : + this.filename + + const positionId = (this.stableForTests) ? + this.stringId(callName, fileName) : + this.sha1Id(callName, fileName) + + + return this.stableForTests + ? arkts.factory.createStringLiteral(positionId) + : arkts.factory.createNumericLiteral(parseInt(positionId, 16)) + } +} + +export function isMemoAnnotation(node: arkts.AnnotationUsage, memoName: RuntimeNames) { + return node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === memoName +} + +export type MemoAstNode = arkts.ScriptFunction + | arkts.ETSParameterExpression + | arkts.ClassProperty + | arkts.TSTypeAliasDeclaration + | arkts.ETSFunctionType + | arkts.ArrowFunctionExpression; + +export function hasMemoAnnotation(node: T): boolean { + return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION)) +} + +export function hasMemoIntrinsicAnnotation(node: T): boolean { + return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC)) +} + +export function hasMemoStableAnnotation(node: arkts.ClassDefinition) { + return node.annotations.some((it) => + it.expr !== undefined && arkts.isIdentifier(it.expr) && it.expr.name === RuntimeNames.ANNOTATION_STABLE + ) +} + +export function removeMemoAnnotation(node: T): T { + const newAnnotations: arkts.AnnotationUsage[] = node.annotations.filter( + (it) => ( + !isMemoAnnotation(it, RuntimeNames.ANNOTATION) + && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC) + && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) + ) + ); + if (arkts.isEtsParameterExpression(node)) { + node.annotations = newAnnotations; + return node; + } + return node.setAnnotations(newAnnotations) as T; +} + +/** + * TODO: + * @deprecated + */ +export function isSyntheticReturnStatement(node: arkts.AstNode) { + return ( + arkts.isReturnStatement(node) && + node.argument && arkts.isMemberExpression(node.argument) && + arkts.isIdentifier(node.argument.object) && + node.argument.object.name === RuntimeNames.SCOPE && + arkts.isIdentifier(node.argument.property) && + node.argument.property.name === RuntimeNames.INTERNAL_VALUE + ) || arkts.isBlockStatement(node) +} + +/** + * TODO: + * @deprecated + */ +export function isMemoParametersDeclaration(node: arkts.AstNode) { + return arkts.isVariableDeclaration(node) && + node.declarators.every((it) => it.name.name.startsWith(RuntimeNames.PARAMETER)) +} + +/** + * TODO: change this to TypeNodeGetType to check void type + */ +export function isVoidType(typeNode: arkts.TypeNode | undefined) { + return typeNode?.dumpSrc() === "void" +} + +/** + * es2panda API is weird here + * + * @deprecated + */ +export function castParameters(params: readonly arkts.Expression[]): arkts.ETSParameterExpression[] { + return params as arkts.ETSParameterExpression[] +} + +/** + * es2panda API is weird here + * + * @deprecated + */ +export function castFunctionExpression(value: arkts.Expression | undefined): arkts.FunctionExpression { + return value as unknown as arkts.FunctionExpression +} + +export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.ArrowFunctionExpression { + if (!arkts.isArrowFunctionExpression(node)) return false; + + // handling anonymous arrow function call + if (arkts.isCallExpression(node.parent) && node.parent.expression.peer === node.peer) return true; + + return ( + !arkts.isClassProperty(node.parent) + && !(arkts.isCallExpression(node.parent) && node.parent.expression) + ) +} \ No newline at end of file diff --git a/arkui-plugins/npm_preinstall.sh b/arkui-plugins/npm_preinstall.sh new file mode 100755 index 000000000..478471ab0 --- /dev/null +++ b/arkui-plugins/npm_preinstall.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# coding: utf-8 +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if [ "$1" == "--init" ]; then + cd ../koala-wrapper + npm install + npm run compile + npm link + + cd ../ts_wrapper + npm install + npm run compile + npm link + + cd ../arkui-plugins + mkdir node_modules + npm link @koalaui/libarkts +fi \ No newline at end of file diff --git a/arkui-plugins/package.json b/arkui-plugins/package.json new file mode 100644 index 000000000..20078aeb0 --- /dev/null +++ b/arkui-plugins/package.json @@ -0,0 +1,33 @@ +{ + "name": "arkui-plugin", + "version": "1.0.0", + "description": "", + "private": true, + "workspaces": [ + "./test" + ], + "scripts": { + "local:install": "chmod 777 ./npm_preinstall.sh && ./npm_preinstall.sh --init", + "compile:plugins": "./node_modules/.bin/babel . --out-dir lib --extensions .ts", + "compile:clean": "rm -rf lib", + "test": "jest --config ./jest-test.config.ts", + "compile": "npm run compile:clean && npm run compile:plugins && cp -rf ./lib $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/" + }, + "devDependencies": { + "@babel/cli": "7.20.7", + "@babel/core": "7.20.12", + "@babel/plugin-proposal-class-properties": "7.18.6", + "@babel/preset-env": "7.20.2", + "@babel/preset-typescript": "7.18.6", + "@babel/runtime": "7.20.13", + "@types/jest": "^29.5.14", + "@types/node": "^22.13.9", + "jest": "^29.7.0", + "ts-jest": "^29.2.0", + "ts-node": "^10.9.0", + "typescript": "^5.0.0" + }, + "dependencies": { + "@koalaui/libarkts": "../koala-wrapper" + } +} diff --git a/arkui-plugins/path.ts b/arkui-plugins/path.ts new file mode 100644 index 000000000..6b8a714e8 --- /dev/null +++ b/arkui-plugins/path.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { error } from 'console'; +import * as path from 'path'; + +const UI_PLUGINS = 'ui-plugins'; +const ARKUI_PLUGINS = 'arkui-plugins'; + +function findMatchingFile(currentPath: string, targetFileName1: string, targetFileName2: string): string | null { + let current = currentPath; + while (true) { + // 获取当前路径的文件名 + const baseName = path.basename(current); + if (baseName === targetFileName1 || baseName === targetFileName2) { + return path.dirname(current); + } + + const parentPath = path.dirname(current); + if (parentPath === current) { + break; + } + current = parentPath; + } + throw new Error("ui-plugins not found.") +} + +function findRootDir() { + const plugins = findMatchingFile(__dirname, UI_PLUGINS, ARKUI_PLUGINS); + if (plugins === null) { + throw ("error") + } + return plugins +} + +export function getArktsPath() { + return path.join(findRootDir(), 'koala-wrapper','./build/lib/arkts-api/index.js') +} + +export function getInteropPath() { + return path.join(findRootDir(), 'koala-wrapper/koalaui/interop', "./dist/lib/src/interop/index.js") +} + +export function getCommonPath() { + return path.join(findRootDir(), 'koala-wrapper/koalaui/common', "./dist/lib/src/index.js") +} + +export function getCompatPath() { + return path.join(findRootDir(), 'koala-wrapper/koalaui/compat', "./dist/src/index.js") +} diff --git a/arkui-plugins/test/arktsconfig_gen.js b/arkui-plugins/test/arktsconfig_gen.js new file mode 100644 index 000000000..bd8b94608 --- /dev/null +++ b/arkui-plugins/test/arktsconfig_gen.js @@ -0,0 +1,57 @@ +/* + * 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. + */ + +const fs = require('fs'); +const path = require('path'); + +// 获取当前目录 +const currentDirectory = process.cwd(); +let workSpace = currentDirectory; +for (let i = 0; i < 4; i++) { + workSpace = path.dirname(workSpace); +} +// JSON 文件路径 +const jsonFilePath = path.join(__dirname, 'arktsconfig_template.json'); +const outJsonFilePath = path.join(__dirname, 'dist/cache/arktsconfig.json'); + +try { + // 读取 JSON 文件内容 + const data = fs.readFileSync(jsonFilePath, 'utf8'); + const jsonData = JSON.parse(data); + + // 处理 baseUrl 字段 + if (jsonData.compilerOptions.baseUrl) { + jsonData.compilerOptions.baseUrl = jsonData.compilerOptions.baseUrl.replace(/workspace/g, workSpace); + } + + // 处理 Paths 字段 + if (jsonData.compilerOptions.paths) { + for (const key in jsonData.compilerOptions.paths) { + const values = jsonData.compilerOptions.paths[key]; + for (let i = 0; i < values.length; i++) { + if (key.startsWith('@ohos.arkui.')) { + values[i] = currentDirectory + "/dist/cache/" + key; + } else { + values[i] = values[i].replace(/workspace/g, workSpace); + } + } + } + } + + // 将修改后的内容写回 JSON 文件 + fs.writeFileSync(outJsonFilePath, JSON.stringify(jsonData, null, 2), 'utf8'); +} catch (error) { + console.error('处理 JSON 文件时出错:', error); +} \ No newline at end of file diff --git a/arkui-plugins/test/arktsconfig_template.json b/arkui-plugins/test/arktsconfig_template.json new file mode 100644 index 000000000..1353fee74 --- /dev/null +++ b/arkui-plugins/test/arktsconfig_template.json @@ -0,0 +1,2797 @@ +{ + "compilerOptions": { + "package": "entry", + "baseUrl": "workspace/developtools/ace_ets2bundle/arkui-plugins/test/dist/cache/", + "include": [ + "./0_SRC_Memo_2_FunctionTransformer.ets" + ], + "paths": { + "std": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib/stdlib/std" + ], + "escompat": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib/stdlib/escompat" + ], + "@ohos.InputMethodExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.InputMethodExtensionAbility" + ], + "@ohos.InputMethodExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.InputMethodExtensionContext" + ], + "@ohos.InputMethodSubtype": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.InputMethodSubtype" + ], + "@ohos.PiPWindow": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.PiPWindow" + ], + "@ohos.UiTest": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.UiTest" + ], + "@ohos.WallpaperExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.WallpaperExtensionAbility" + ], + "@ohos.WorkSchedulerExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.WorkSchedulerExtensionAbility" + ], + "@ohos.ability.ability": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ability.ability" + ], + "@ohos.ability.dataUriUtils": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ability.dataUriUtils" + ], + "@ohos.ability.errorCode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ability.errorCode" + ], + "@ohos.ability.featureAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ability.featureAbility" + ], + "@ohos.ability.particleAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ability.particleAbility" + ], + "@ohos.ability.screenLockFileManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ability.screenLockFileManager" + ], + "@ohos.ability.wantConstant": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ability.wantConstant" + ], + "@ohos.abilityAccessCtrl": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.abilityAccessCtrl" + ], + "@ohos.accessibility.GesturePath": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.accessibility.GesturePath" + ], + "@ohos.accessibility.GesturePoint": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.accessibility.GesturePoint" + ], + "@ohos.accessibility.config": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.accessibility.config" + ], + "@ohos.accessibility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.accessibility" + ], + "@ohos.account.appAccount": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.account.appAccount" + ], + "@ohos.account.distributedAccount": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.account.distributedAccount" + ], + "@ohos.account.osAccount": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.account.osAccount" + ], + "@ohos.advertising.AdComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.advertising.AdComponent" + ], + "@ohos.advertising.AdsServiceExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.advertising.AdsServiceExtensionAbility" + ], + "@ohos.advertising.AutoAdComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.advertising.AutoAdComponent" + ], + "@ohos.advertising": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.advertising" + ], + "@ohos.ai.intelligentVoice": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ai.intelligentVoice" + ], + "@ohos.ai.mindSporeLite": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.ai.mindSporeLite" + ], + "@ohos.animation.windowAnimationManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.animation.windowAnimationManager" + ], + "@ohos.animator": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.animator" + ], + "@ohos.app.ability.Ability": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.Ability" + ], + "@ohos.app.ability.AbilityConstant": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.AbilityConstant" + ], + "@ohos.app.ability.AbilityLifecycleCallback": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.AbilityLifecycleCallback" + ], + "@ohos.app.ability.AbilityStage": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.AbilityStage" + ], + "@ohos.app.ability.ActionExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ActionExtensionAbility" + ], + "@ohos.app.ability.ApplicationStateChangeCallback": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ApplicationStateChangeCallback" + ], + "@ohos.app.ability.AtomicServiceOptions": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.AtomicServiceOptions" + ], + "@ohos.app.ability.AutoFillExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.AutoFillExtensionAbility" + ], + "@ohos.app.ability.ChildProcess": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ChildProcess" + ], + "@ohos.app.ability.ChildProcessArgs": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ChildProcessArgs" + ], + "@ohos.app.ability.ChildProcessOptions": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ChildProcessOptions" + ], + "@ohos.app.ability.Configuration": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.Configuration" + ], + "@ohos.app.ability.ConfigurationConstant": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ConfigurationConstant" + ], + "@ohos.app.ability.DriverExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.DriverExtensionAbility" + ], + "@ohos.app.ability.EmbeddableUIAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.EmbeddableUIAbility" + ], + "@ohos.app.ability.EmbeddedUIExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.EmbeddedUIExtensionAbility" + ], + "@ohos.app.ability.EnvironmentCallback": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.EnvironmentCallback" + ], + "@ohos.app.ability.ExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ExtensionAbility" + ], + "@ohos.app.ability.FenceExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.FenceExtensionAbility" + ], + "@ohos.app.ability.FenceExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.FenceExtensionContext" + ], + "@ohos.app.ability.InsightIntentContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.InsightIntentContext" + ], + "@ohos.app.ability.InsightIntentExecutor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.InsightIntentExecutor" + ], + "@ohos.app.ability.MediaControlExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.MediaControlExtensionAbility" + ], + "@ohos.app.ability.OpenLinkOptions": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.OpenLinkOptions" + ], + "@ohos.app.ability.PhotoEditorExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.PhotoEditorExtensionAbility" + ], + "@ohos.app.ability.PrintExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.PrintExtensionAbility" + ], + "@ohos.app.ability.ServiceExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ServiceExtensionAbility" + ], + "@ohos.app.ability.ShareExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.ShareExtensionAbility" + ], + "@ohos.app.ability.StartOptions": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.StartOptions" + ], + "@ohos.app.ability.UIAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.UIAbility" + ], + "@ohos.app.ability.UIExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.UIExtensionAbility" + ], + "@ohos.app.ability.UIExtensionContentSession": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.UIExtensionContentSession" + ], + "@ohos.app.ability.UIServiceExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.UIServiceExtensionAbility" + ], + "@ohos.app.ability.UserAuthExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.UserAuthExtensionAbility" + ], + "@ohos.app.ability.VpnExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.VpnExtensionAbility" + ], + "@ohos.app.ability.Want": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.Want" + ], + "@ohos.app.ability.abilityDelegatorRegistry": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.abilityDelegatorRegistry" + ], + "@ohos.app.ability.abilityManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.abilityManager" + ], + "@ohos.app.ability.appManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.appManager" + ], + "@ohos.app.ability.appRecovery": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.appRecovery" + ], + "@ohos.app.ability.application": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.application" + ], + "@ohos.app.ability.autoFillManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.autoFillManager" + ], + "@ohos.app.ability.autoStartupManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.autoStartupManager" + ], + "@ohos.app.ability.childProcessManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.childProcessManager" + ], + "@ohos.app.ability.common": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.common" + ], + "@ohos.app.ability.contextConstant": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.contextConstant" + ], + "@ohos.app.ability.dataUriUtils": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.dataUriUtils" + ], + "@ohos.app.ability.dialogRequest": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.dialogRequest" + ], + "@ohos.app.ability.dialogSession": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.dialogSession" + ], + "@ohos.app.ability.errorManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.errorManager" + ], + "@ohos.app.ability.insightIntent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.insightIntent" + ], + "@ohos.app.ability.insightIntentDriver": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.insightIntentDriver" + ], + "@ohos.app.ability.missionManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.missionManager" + ], + "@ohos.app.ability.quickFixManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.quickFixManager" + ], + "@ohos.app.ability.sendableContextManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.sendableContextManager" + ], + "@ohos.app.ability.wantAgent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.wantAgent" + ], + "@ohos.app.ability.wantConstant": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.ability.wantConstant" + ], + "@ohos.app.appstartup.StartupConfig": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.appstartup.StartupConfig" + ], + "@ohos.app.appstartup.StartupConfigEntry": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.appstartup.StartupConfigEntry" + ], + "@ohos.app.appstartup.StartupListener": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.appstartup.StartupListener" + ], + "@ohos.app.appstartup.StartupTask": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.appstartup.StartupTask" + ], + "@ohos.app.appstartup.startupManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.appstartup.startupManager" + ], + "@ohos.app.businessAbilityRouter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.businessAbilityRouter" + ], + "@ohos.app.form.FormExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.form.FormExtensionAbility" + ], + "@ohos.app.form.formAgent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.form.formAgent" + ], + "@ohos.app.form.formBindingData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.form.formBindingData" + ], + "@ohos.app.form.formHost": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.form.formHost" + ], + "@ohos.app.form.formInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.form.formInfo" + ], + "@ohos.app.form.formObserver": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.form.formObserver" + ], + "@ohos.app.form.formProvider": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.app.form.formProvider" + ], + "@ohos.application.AccessibilityExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.AccessibilityExtensionAbility" + ], + "@ohos.application.BackupExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.BackupExtensionAbility" + ], + "@ohos.application.Configuration": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.Configuration" + ], + "@ohos.application.ConfigurationConstant": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.ConfigurationConstant" + ], + "@ohos.application.DataShareExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.DataShareExtensionAbility" + ], + "@ohos.application.StaticSubscriberExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.StaticSubscriberExtensionAbility" + ], + "@ohos.application.StaticSubscriberExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.StaticSubscriberExtensionContext" + ], + "@ohos.application.Want": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.Want" + ], + "@ohos.application.WindowExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.WindowExtensionAbility" + ], + "@ohos.application.abilityDelegatorRegistry": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.abilityDelegatorRegistry" + ], + "@ohos.application.abilityManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.abilityManager" + ], + "@ohos.application.appManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.appManager" + ], + "@ohos.application.formBindingData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.formBindingData" + ], + "@ohos.application.formError": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.formError" + ], + "@ohos.application.formHost": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.formHost" + ], + "@ohos.application.formInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.formInfo" + ], + "@ohos.application.formProvider": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.formProvider" + ], + "@ohos.application.missionManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.missionManager" + ], + "@ohos.application.testRunner": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.testRunner" + ], + "@ohos.application.uriPermissionManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.application.uriPermissionManager" + ], + "@ohos.arkui.Prefetcher": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.Prefetcher" + ], + "@ohos.arkui.StateManagement": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.StateManagement" + ], + "@ohos.arkui.StateManagement.runtime": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.StateManagement.runtime" + ], + "@ohos.arkui.UIContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.UIContext" + ], + "@ohos.arkui.advanced.Chip": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.Chip" + ], + "@ohos.arkui.advanced.ChipGroup": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.ChipGroup" + ], + "@ohos.arkui.advanced.ComposeListItem": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.ComposeListItem" + ], + "@ohos.arkui.advanced.ComposeTitleBar": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.ComposeTitleBar" + ], + "@ohos.arkui.advanced.Counter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.Counter" + ], + "@ohos.arkui.advanced.Dialog": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.Dialog" + ], + "@ohos.arkui.advanced.DownloadFileButton": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.DownloadFileButton" + ], + "@ohos.arkui.advanced.EditableTitleBar": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.EditableTitleBar" + ], + "@ohos.arkui.advanced.ExceptionPrompt": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.ExceptionPrompt" + ], + "@ohos.arkui.advanced.Filter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.Filter" + ], + "@ohos.arkui.advanced.FoldSplitContainer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.FoldSplitContainer" + ], + "@ohos.arkui.advanced.FormMenu": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.FormMenu" + ], + "@ohos.arkui.advanced.FullScreenLaunchComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.FullScreenLaunchComponent" + ], + "@ohos.arkui.advanced.GridObjectSortComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.GridObjectSortComponent" + ], + "@ohos.arkui.advanced.InnerFullScreenLaunchComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.InnerFullScreenLaunchComponent" + ], + "@ohos.arkui.advanced.Popup": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.Popup" + ], + "@ohos.arkui.advanced.ProgressButton": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.ProgressButton" + ], + "@ohos.arkui.advanced.SegmentButton": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.SegmentButton" + ], + "@ohos.arkui.advanced.SelectTitleBar": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.SelectTitleBar" + ], + "@ohos.arkui.advanced.SelectionMenu": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.SelectionMenu" + ], + "@ohos.arkui.advanced.SplitLayout": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.SplitLayout" + ], + "@ohos.arkui.advanced.SubHeader": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.SubHeader" + ], + "@ohos.arkui.advanced.SwipeRefresher": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.SwipeRefresher" + ], + "@ohos.arkui.advanced.TabTitleBar": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.TabTitleBar" + ], + "@ohos.arkui.advanced.ToolBar": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.ToolBar" + ], + "@ohos.arkui.advanced.TreeView": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.advanced.TreeView" + ], + "@ohos.arkui.component.AbilityComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.AbilityComponent" + ], + "@ohos.arkui.component.ActionSheet": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ActionSheet" + ], + "@ohos.arkui.component.AlertDialog": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.AlertDialog" + ], + "@ohos.arkui.component.AlphabetIndexer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.AlphabetIndexer" + ], + "@ohos.arkui.component.Animator": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Animator" + ], + "@ohos.arkui.component.Badge": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Badge" + ], + "@ohos.arkui.component.Blank": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Blank" + ], + "@ohos.arkui.component.Button": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Button" + ], + "@ohos.arkui.component.Calendar": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Calendar" + ], + "@ohos.arkui.component.CalendarPicker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.CalendarPicker" + ], + "@ohos.arkui.component.Canvas": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Canvas" + ], + "@ohos.arkui.component.Checkbox": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Checkbox" + ], + "@ohos.arkui.component.CheckboxGroup": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.CheckboxGroup" + ], + "@ohos.arkui.component.Circle": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Circle" + ], + "@ohos.arkui.component.Column": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Column" + ], + "@ohos.arkui.component.ColumnSplit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ColumnSplit" + ], + "@ohos.arkui.component.Common": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Common" + ], + "@ohos.arkui.component.CommonTsEtsApi": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.CommonTsEtsApi" + ], + "@ohos.arkui.component.Component3d": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Component3d" + ], + "@ohos.arkui.component.ContainerSpan": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ContainerSpan" + ], + "@ohos.arkui.component.ContentSlot": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ContentSlot" + ], + "@ohos.arkui.component.ContextMenu": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ContextMenu" + ], + "@ohos.arkui.component.Counter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Counter" + ], + "@ohos.arkui.component.CustomDialogController": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.CustomDialogController" + ], + "@ohos.arkui.component.DataPanel": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.DataPanel" + ], + "@ohos.arkui.component.DatePicker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.DatePicker" + ], + "@ohos.arkui.component.Divider": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Divider" + ], + "@ohos.arkui.component.EffectComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.EffectComponent" + ], + "@ohos.arkui.component.Ellipse": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Ellipse" + ], + "@ohos.arkui.component.EmbeddedComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.EmbeddedComponent" + ], + "@ohos.arkui.component.Enums": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Enums" + ], + "@ohos.arkui.component.Flex": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Flex" + ], + "@ohos.arkui.component.FlowItem": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.FlowItem" + ], + "@ohos.arkui.component.Focus": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Focus" + ], + "@ohos.arkui.component.FolderStack": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.FolderStack" + ], + "@ohos.arkui.component.ForEach": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ForEach" + ], + "@ohos.arkui.component.FormComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.FormComponent" + ], + "@ohos.arkui.component.FormLink": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.FormLink" + ], + "@ohos.arkui.component.Gauge": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Gauge" + ], + "@ohos.arkui.component.Gesture": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Gesture" + ], + "@ohos.arkui.component.Grid": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Grid" + ], + "@ohos.arkui.component.GridCol": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.GridCol" + ], + "@ohos.arkui.component.GridContainer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.GridContainer" + ], + "@ohos.arkui.component.GridItem": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.GridItem" + ], + "@ohos.arkui.component.GridRow": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.GridRow" + ], + "@ohos.arkui.component.Hyperlink": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Hyperlink" + ], + "@ohos.arkui.component.Image": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Image" + ], + "@ohos.arkui.component.ImageAnimator": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ImageAnimator" + ], + "@ohos.arkui.component.ImageCommon": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ImageCommon" + ], + "@ohos.arkui.component.ImageSpan": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ImageSpan" + ], + "@ohos.arkui.component.IndicatorComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.IndicatorComponent" + ], + "@ohos.arkui.component.Inspector": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Inspector" + ], + "@ohos.arkui.component.IsolatedComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.IsolatedComponent" + ], + "@ohos.arkui.component.LazyForEach": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.LazyForEach" + ], + "@ohos.arkui.component.Line": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Line" + ], + "@ohos.arkui.component.Linearindicator": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Linearindicator" + ], + "@ohos.arkui.component.List": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.List" + ], + "@ohos.arkui.component.ListItem": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ListItem" + ], + "@ohos.arkui.component.ListItemGroup": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ListItemGroup" + ], + "@ohos.arkui.component.LoadingProgress": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.LoadingProgress" + ], + "@ohos.arkui.component.Marquee": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Marquee" + ], + "@ohos.arkui.component.Matrix2d": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Matrix2d" + ], + "@ohos.arkui.component.MediaCachedImage": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.MediaCachedImage" + ], + "@ohos.arkui.component.Menu": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Menu" + ], + "@ohos.arkui.component.MenuItem": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.MenuItem" + ], + "@ohos.arkui.component.MenuItemGroup": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.MenuItemGroup" + ], + "@ohos.arkui.component.NavDestination": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.NavDestination" + ], + "@ohos.arkui.component.NavRouter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.NavRouter" + ], + "@ohos.arkui.component.Navigation": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Navigation" + ], + "@ohos.arkui.component.Navigator": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Navigator" + ], + "@ohos.arkui.component.NodeContainer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.NodeContainer" + ], + "@ohos.arkui.component.PageTransition": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.PageTransition" + ], + "@ohos.arkui.component.Panel": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Panel" + ], + "@ohos.arkui.component.Particle": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Particle" + ], + "@ohos.arkui.component.Path": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Path" + ], + "@ohos.arkui.component.PatternLock": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.PatternLock" + ], + "@ohos.arkui.component.Polygon": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Polygon" + ], + "@ohos.arkui.component.Polyline": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Polyline" + ], + "@ohos.arkui.component.Progress": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Progress" + ], + "@ohos.arkui.component.QRCode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.QRCode" + ], + "@ohos.arkui.component.Radio": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Radio" + ], + "@ohos.arkui.component.Rating": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Rating" + ], + "@ohos.arkui.component.Rect": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Rect" + ], + "@ohos.arkui.component.Refresh": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Refresh" + ], + "@ohos.arkui.component.RelativeContainer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.RelativeContainer" + ], + "@ohos.arkui.component.RichEditor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.RichEditor" + ], + "@ohos.arkui.component.RichText": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.RichText" + ], + "@ohos.arkui.component.Row": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Row" + ], + "@ohos.arkui.component.RowSplit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.RowSplit" + ], + "@ohos.arkui.component.Scroll": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Scroll" + ], + "@ohos.arkui.component.ScrollBar": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.ScrollBar" + ], + "@ohos.arkui.component.Search": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Search" + ], + "@ohos.arkui.component.Select": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Select" + ], + "@ohos.arkui.component.Shape": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Shape" + ], + "@ohos.arkui.component.Sidebar": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Sidebar" + ], + "@ohos.arkui.component.Slider": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Slider" + ], + "@ohos.arkui.component.Span": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Span" + ], + "@ohos.arkui.component.Stack": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Stack" + ], + "@ohos.arkui.component.StateManagement": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.StateManagement" + ], + "@ohos.arkui.component.StepperItem": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.StepperItem" + ], + "@ohos.arkui.component.StyledString": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.StyledString" + ], + "@ohos.arkui.component.Swiper": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Swiper" + ], + "@ohos.arkui.component.SymbolGlyph": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.SymbolGlyph" + ], + "@ohos.arkui.component.SymbolSpan": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.SymbolSpan" + ], + "@ohos.arkui.component.TabContent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.TabContent" + ], + "@ohos.arkui.component.Tabs": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Tabs" + ], + "@ohos.arkui.component.Text": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Text" + ], + "@ohos.arkui.component.TextArea": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.TextArea" + ], + "@ohos.arkui.component.TextClock": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.TextClock" + ], + "@ohos.arkui.component.TextCommon": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.TextCommon" + ], + "@ohos.arkui.component.TextInput": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.TextInput" + ], + "@ohos.arkui.component.TextPicker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.TextPicker" + ], + "@ohos.arkui.component.TextTimer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.TextTimer" + ], + "@ohos.arkui.component.TimePicker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.TimePicker" + ], + "@ohos.arkui.component.Toggle": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Toggle" + ], + "@ohos.arkui.component.Units": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Units" + ], + "@ohos.arkui.component.Video": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.Video" + ], + "@ohos.arkui.component.WaterFlow": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.WaterFlow" + ], + "@ohos.arkui.component.WithTheme": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.WithTheme" + ], + "@ohos.arkui.component.XComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component.XComponent" + ], + "@ohos.arkui.component": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.component" + ], + "@ohos.arkui.componentSnapshot": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.componentSnapshot" + ], + "@ohos.arkui.componentUtils": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.componentUtils" + ], + "@ohos.arkui.dragController": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.dragController" + ], + "@ohos.arkui.drawableDescriptor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.drawableDescriptor" + ], + "@ohos.arkui.inspector": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.inspector" + ], + "@ohos.arkui.modifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.modifier" + ], + "@ohos.arkui.node": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.node" + ], + "@ohos.arkui.observer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.observer" + ], + "@ohos.arkui.performanceMonitor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.performanceMonitor" + ], + "@ohos.arkui.shape": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.shape" + ], + "@ohos.arkui.stateManagement": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.stateManagement" + ], + "@ohos.arkui.theme": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.theme" + ], + "@ohos.arkui.uiExtension": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.arkui.uiExtension" + ], + "@ohos.atomicservice.AtomicServiceNavigation": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.atomicservice.AtomicServiceNavigation" + ], + "@ohos.atomicservice.AtomicServiceTabs": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.atomicservice.AtomicServiceTabs" + ], + "@ohos.atomicservice.AtomicServiceWeb": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.atomicservice.AtomicServiceWeb" + ], + "@ohos.atomicservice.InterstitialDialogAction": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.atomicservice.InterstitialDialogAction" + ], + "@ohos.atomicservice.NavPushPathHelper": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.atomicservice.NavPushPathHelper" + ], + "@ohos.backgroundTaskManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.backgroundTaskManager" + ], + "@ohos.base": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.base" + ], + "@ohos.batteryInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.batteryInfo" + ], + "@ohos.batteryStatistics": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.batteryStatistics" + ], + "@ohos.bluetooth.a2dp": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.a2dp" + ], + "@ohos.bluetooth.access": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.access" + ], + "@ohos.bluetooth.baseProfile": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.baseProfile" + ], + "@ohos.bluetooth.ble": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.ble" + ], + "@ohos.bluetooth.connection": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.connection" + ], + "@ohos.bluetooth.constant": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.constant" + ], + "@ohos.bluetooth": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth" + ], + "@ohos.bluetooth.hfp": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.hfp" + ], + "@ohos.bluetooth.hid": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.hid" + ], + "@ohos.bluetooth.map": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.map" + ], + "@ohos.bluetooth.pan": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.pan" + ], + "@ohos.bluetooth.pbap": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.pbap" + ], + "@ohos.bluetooth.socket": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.socket" + ], + "@ohos.bluetooth.wearDetection": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetooth.wearDetection" + ], + "@ohos.bluetoothManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bluetoothManager" + ], + "@ohos.brightness": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.brightness" + ], + "@ohos.buffer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.buffer" + ], + "@ohos.bundle.appControl": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.appControl" + ], + "@ohos.bundle.appDomainVerify": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.appDomainVerify" + ], + "@ohos.bundle.bundleManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.bundleManager" + ], + "@ohos.bundle.bundleMonitor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.bundleMonitor" + ], + "@ohos.bundle.bundleResourceManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.bundleResourceManager" + ], + "@ohos.bundle": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle" + ], + "@ohos.bundle.defaultAppManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.defaultAppManager" + ], + "@ohos.bundle.distributedBundleManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.distributedBundleManager" + ], + "@ohos.bundle.freeInstall": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.freeInstall" + ], + "@ohos.bundle.innerBundleManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.innerBundleManager" + ], + "@ohos.bundle.installer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.installer" + ], + "@ohos.bundle.launcherBundleManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.launcherBundleManager" + ], + "@ohos.bundle.overlay": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.overlay" + ], + "@ohos.bundle.shortcutManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundle.shortcutManager" + ], + "@ohos.bundleState": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bundleState" + ], + "@ohos.bytrace": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.bytrace" + ], + "@ohos.calendarManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.calendarManager" + ], + "@ohos.charger": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.charger" + ], + "@ohos.commonEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.commonEvent" + ], + "@ohos.commonEventManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.commonEventManager" + ], + "@ohos.configPolicy": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.configPolicy" + ], + "@ohos.connectedTag": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.connectedTag" + ], + "@ohos.contact": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.contact" + ], + "@ohos.continuation.continuationManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.continuation.continuationManager" + ], + "@ohos.cooperate": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.cooperate" + ], + "@ohos.curves": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.curves" + ], + "@ohos.customization.customConfig": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.customization.customConfig" + ], + "@ohos.data.DataShareResultSet": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.DataShareResultSet" + ], + "@ohos.data.ValuesBucket": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.ValuesBucket" + ], + "@ohos.data.cloudData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.cloudData" + ], + "@ohos.data.cloudExtension": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.cloudExtension" + ], + "@ohos.data.commonType": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.commonType" + ], + "@ohos.data.dataAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.dataAbility" + ], + "@ohos.data.dataShare": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.dataShare" + ], + "@ohos.data.dataSharePredicates": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.dataSharePredicates" + ], + "@ohos.data.distributedData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.distributedData" + ], + "@ohos.data.distributedDataObject": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.distributedDataObject" + ], + "@ohos.data.distributedKVStore": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.distributedKVStore" + ], + "@ohos.data.preferences": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.preferences" + ], + "@ohos.data.rdb": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.rdb" + ], + "@ohos.data.relationalStore": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.relationalStore" + ], + "@ohos.data.sendablePreferences": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.sendablePreferences" + ], + "@ohos.data.sendableRelationalStore": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.sendableRelationalStore" + ], + "@ohos.data.storage": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.storage" + ], + "@ohos.data.unifiedDataChannel": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.unifiedDataChannel" + ], + "@ohos.data.uniformDataStruct": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.uniformDataStruct" + ], + "@ohos.data.uniformTypeDescriptor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.data.uniformTypeDescriptor" + ], + "@ohos.deviceAttest": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.deviceAttest" + ], + "@ohos.deviceInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.deviceInfo" + ], + "@ohos.deviceStatus.dragInteraction": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.deviceStatus.dragInteraction" + ], + "@ohos.display": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.display" + ], + "@ohos.distributedBundle": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.distributedBundle" + ], + "@ohos.distributedDeviceManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.distributedDeviceManager" + ], + "@ohos.distributedHardware.deviceManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.distributedHardware.deviceManager" + ], + "@ohos.distributedHardware.hardwareManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.distributedHardware.hardwareManager" + ], + "@ohos.distributedMissionManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.distributedMissionManager" + ], + "@ohos.dlpPermission": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.dlpPermission" + ], + "@ohos.document": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.document" + ], + "@ohos.driver.deviceManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.driver.deviceManager" + ], + "@ohos.effectKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.effectKit" + ], + "@ohos.enterprise.EnterpriseAdminExtensionAbility": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.EnterpriseAdminExtensionAbility" + ], + "@ohos.enterprise.accountManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.accountManager" + ], + "@ohos.enterprise.adminManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.adminManager" + ], + "@ohos.enterprise.applicationManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.applicationManager" + ], + "@ohos.enterprise.bluetoothManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.bluetoothManager" + ], + "@ohos.enterprise.browser": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.browser" + ], + "@ohos.enterprise.bundleManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.bundleManager" + ], + "@ohos.enterprise.dateTimeManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.dateTimeManager" + ], + "@ohos.enterprise.deviceControl": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.deviceControl" + ], + "@ohos.enterprise.deviceInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.deviceInfo" + ], + "@ohos.enterprise.deviceSettings": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.deviceSettings" + ], + "@ohos.enterprise.locationManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.locationManager" + ], + "@ohos.enterprise.networkManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.networkManager" + ], + "@ohos.enterprise.restrictions": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.restrictions" + ], + "@ohos.enterprise.securityManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.securityManager" + ], + "@ohos.enterprise.systemManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.systemManager" + ], + "@ohos.enterprise.usbManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.usbManager" + ], + "@ohos.enterprise.wifiManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.enterprise.wifiManager" + ], + "@ohos.events.emitter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.events.emitter" + ], + "@ohos.faultLogger": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.faultLogger" + ], + "@ohos.file.AlbumPickerComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.AlbumPickerComponent" + ], + "@ohos.file.BackupExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.BackupExtensionContext" + ], + "@ohos.file.PhotoPickerComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.PhotoPickerComponent" + ], + "@ohos.file.RecentPhotoComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.RecentPhotoComponent" + ], + "@ohos.file.backup": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.backup" + ], + "@ohos.file.cloudSync": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.cloudSync" + ], + "@ohos.file.cloudSyncManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.cloudSyncManager" + ], + "@ohos.file.environment": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.environment" + ], + "@ohos.file.fileAccess": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.fileAccess" + ], + "@ohos.file.fileExtensionInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.fileExtensionInfo" + ], + "@ohos.file.fileuri": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.fileuri" + ], + "@ohos.file.fs": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.fs" + ], + "@ohos.file.hash": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.hash" + ], + "@ohos.file.photoAccessHelper": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.photoAccessHelper" + ], + "@ohos.file.picker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.picker" + ], + "@ohos.file.recent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.recent" + ], + "@ohos.file.securityLabel": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.securityLabel" + ], + "@ohos.file.sendablePhotoAccessHelper": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.sendablePhotoAccessHelper" + ], + "@ohos.file.statvfs": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.statvfs" + ], + "@ohos.file.storageStatistics": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.storageStatistics" + ], + "@ohos.file.trash": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.trash" + ], + "@ohos.file.volumeManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.file.volumeManager" + ], + "@ohos.fileio": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.fileio" + ], + "@ohos.filemanagement.userFileManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.filemanagement.userFileManager" + ], + "@ohos.fileshare": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.fileshare" + ], + "@ohos.font": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.font" + ], + "@ohos.geoLocationManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.geoLocationManager" + ], + "@ohos.geolocation": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.geolocation" + ], + "@ohos.graphics.colorSpaceManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.colorSpaceManager" + ], + "@ohos.graphics.common2D": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.common2D" + ], + "@ohos.graphics.displaySync": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.displaySync" + ], + "@ohos.graphics.drawing": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.drawing" + ], + "@ohos.graphics.hdrCapability": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.hdrCapability" + ], + "@ohos.graphics.scene": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.scene" + ], + "@ohos.graphics.sendableColorSpaceManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.sendableColorSpaceManager" + ], + "@ohos.graphics.text": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.text" + ], + "@ohos.graphics.uiEffect": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.graphics.uiEffect" + ], + "@ohos.hiAppEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hiAppEvent" + ], + "@ohos.hiSysEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hiSysEvent" + ], + "@ohos.hiTraceChain": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hiTraceChain" + ], + "@ohos.hiTraceMeter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hiTraceMeter" + ], + "@ohos.hichecker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hichecker" + ], + "@ohos.hidebug": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hidebug" + ], + "@ohos.hilog": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hilog" + ], + "@ohos.hiviewdfx.hiAppEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hiviewdfx.hiAppEvent" + ], + "@ohos.hiviewdfx.jsLeakWatcher": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.hiviewdfx.jsLeakWatcher" + ], + "@ohos.i18n": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.i18n" + ], + "@ohos.identifier.oaid": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.identifier.oaid" + ], + "@ohos.inputMethod.Panel": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.inputMethod.Panel" + ], + "@ohos.inputMethod": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.inputMethod" + ], + "@ohos.inputMethodEngine": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.inputMethodEngine" + ], + "@ohos.inputMethodList": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.inputMethodList" + ], + "@ohos.intl": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.intl" + ], + "@ohos.logLibrary": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.logLibrary" + ], + "@ohos.matrix4": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.matrix4" + ], + "@ohos.measure": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.measure" + ], + "@ohos.mediaquery": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.mediaquery" + ], + "@ohos.multimedia.audio": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.audio" + ], + "@ohos.multimedia.audioHaptic": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.audioHaptic" + ], + "@ohos.multimedia.avCastPicker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.avCastPicker" + ], + "@ohos.multimedia.avCastPickerParam": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.avCastPickerParam" + ], + "@ohos.multimedia.avVolumePanel": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.avVolumePanel" + ], + "@ohos.multimedia.avsession": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.avsession" + ], + "@ohos.multimedia.camera": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.camera" + ], + "@ohos.multimedia.cameraPicker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.cameraPicker" + ], + "@ohos.multimedia.drm": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.drm" + ], + "@ohos.multimedia.image": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.image" + ], + "@ohos.multimedia.media": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.media" + ], + "@ohos.multimedia.movingphotoview": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.movingphotoview" + ], + "@ohos.multimedia.sendableImage": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.sendableImage" + ], + "@ohos.multimedia.systemSoundManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimedia.systemSoundManager" + ], + "@ohos.multimodalInput.gestureEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.gestureEvent" + ], + "@ohos.multimodalInput.infraredEmitter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.infraredEmitter" + ], + "@ohos.multimodalInput.inputConsumer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.inputConsumer" + ], + "@ohos.multimodalInput.inputDevice": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.inputDevice" + ], + "@ohos.multimodalInput.inputDeviceCooperate": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.inputDeviceCooperate" + ], + "@ohos.multimodalInput.inputEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.inputEvent" + ], + "@ohos.multimodalInput.inputEventClient": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.inputEventClient" + ], + "@ohos.multimodalInput.inputMonitor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.inputMonitor" + ], + "@ohos.multimodalInput.intentionCode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.intentionCode" + ], + "@ohos.multimodalInput.keyCode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.keyCode" + ], + "@ohos.multimodalInput.keyEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.keyEvent" + ], + "@ohos.multimodalInput.mouseEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.mouseEvent" + ], + "@ohos.multimodalInput.pointer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.pointer" + ], + "@ohos.multimodalInput.shortKey": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.shortKey" + ], + "@ohos.multimodalInput.touchEvent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.multimodalInput.touchEvent" + ], + "@ohos.net.connection": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.connection" + ], + "@ohos.net.ethernet": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.ethernet" + ], + "@ohos.net.http": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.http" + ], + "@ohos.net.mdns": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.mdns" + ], + "@ohos.net.netFirewall": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.netFirewall" + ], + "@ohos.net.networkSecurity": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.networkSecurity" + ], + "@ohos.net.policy": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.policy" + ], + "@ohos.net.sharing": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.sharing" + ], + "@ohos.net.socket": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.socket" + ], + "@ohos.net.statistics": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.statistics" + ], + "@ohos.net.vpn": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.vpn" + ], + "@ohos.net.vpnExtension": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.vpnExtension" + ], + "@ohos.net.webSocket": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.net.webSocket" + ], + "@ohos.nfc.cardEmulation": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.nfc.cardEmulation" + ], + "@ohos.nfc.controller": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.nfc.controller" + ], + "@ohos.nfc.tag": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.nfc.tag" + ], + "@ohos.notification": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.notification" + ], + "@ohos.notificationManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.notificationManager" + ], + "@ohos.notificationSubscribe": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.notificationSubscribe" + ], + "@ohos.pasteboard": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.pasteboard" + ], + "@ohos.pluginComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.pluginComponent" + ], + "@ohos.power": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.power" + ], + "@ohos.print": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.print" + ], + "@ohos.privacyManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.privacyManager" + ], + "@ohos.prompt": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.prompt" + ], + "@ohos.promptAction": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.promptAction" + ], + "@ohos.reminderAgent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.reminderAgent" + ], + "@ohos.reminderAgentManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.reminderAgentManager" + ], + "@ohos.request": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.request" + ], + "@ohos.resourceManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.resourceManager" + ], + "@ohos.resourceschedule.backgroundTaskManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.resourceschedule.backgroundTaskManager" + ], + "@ohos.resourceschedule.deviceStandby": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.resourceschedule.deviceStandby" + ], + "@ohos.resourceschedule.systemload": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.resourceschedule.systemload" + ], + "@ohos.resourceschedule.usageStatistics": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.resourceschedule.usageStatistics" + ], + "@ohos.resourceschedule.workScheduler": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.resourceschedule.workScheduler" + ], + "@ohos.router": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.router" + ], + "@ohos.rpc": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.rpc" + ], + "@ohos.runningLock": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.runningLock" + ], + "@ohos.screen": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.screen" + ], + "@ohos.screenLock": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.screenLock" + ], + "@ohos.screenshot": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.screenshot" + ], + "@ohos.secureElement": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.secureElement" + ], + "@ohos.security.asset": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.security.asset" + ], + "@ohos.security.cert": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.security.cert" + ], + "@ohos.security.certManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.security.certManager" + ], + "@ohos.security.certManagerDialog": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.security.certManagerDialog" + ], + "@ohos.security.cryptoFramework": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.security.cryptoFramework" + ], + "@ohos.security.huks": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.security.huks" + ], + "@ohos.security.securityGuard": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.security.securityGuard" + ], + "@ohos.sendableResourceManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.sendableResourceManager" + ], + "@ohos.sensor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.sensor" + ], + "@ohos.settings": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.settings" + ], + "@ohos.statfs": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.statfs" + ], + "@ohos.stationary": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.stationary" + ], + "@ohos.systemCapability": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.systemCapability" + ], + "@ohos.systemDateTime": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.systemDateTime" + ], + "@ohos.systemParameterEnhance": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.systemParameterEnhance" + ], + "@ohos.systemTime": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.systemTime" + ], + "@ohos.systemTimer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.systemTimer" + ], + "@ohos.systemparameter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.systemparameter" + ], + "@ohos.telephony.call": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.telephony.call" + ], + "@ohos.telephony.data": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.telephony.data" + ], + "@ohos.telephony.observer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.telephony.observer" + ], + "@ohos.telephony.radio": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.telephony.radio" + ], + "@ohos.telephony.sim": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.telephony.sim" + ], + "@ohos.telephony.sms": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.telephony.sms" + ], + "@ohos.telephony.vcard": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.telephony.vcard" + ], + "@ohos.thermal": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.thermal" + ], + "@ohos.uiAppearance": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.uiAppearance" + ], + "@ohos.uiExtensionHost": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.uiExtensionHost" + ], + "@ohos.update": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.update" + ], + "@ohos.uri": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.uri" + ], + "@ohos.url": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.url" + ], + "@ohos.usb": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.usb" + ], + "@ohos.usbManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.usbManager" + ], + "@ohos.userIAM.faceAuth": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.userIAM.faceAuth" + ], + "@ohos.userIAM.userAuth": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.userIAM.userAuth" + ], + "@ohos.userIAM.userAuthIcon": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.userIAM.userAuthIcon" + ], + "@ohos.util.ArrayList": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.ArrayList" + ], + "@ohos.util.Deque": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.Deque" + ], + "@ohos.util.HashMap": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.HashMap" + ], + "@ohos.util.HashSet": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.HashSet" + ], + "@ohos.util.LightWeightMap": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.LightWeightMap" + ], + "@ohos.util.LightWeightSet": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.LightWeightSet" + ], + "@ohos.util.LinkedList": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.LinkedList" + ], + "@ohos.util.List": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.List" + ], + "@ohos.util.PlainArray": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.PlainArray" + ], + "@ohos.util.Queue": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.Queue" + ], + "@ohos.util.Stack": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.Stack" + ], + "@ohos.util.TreeMap": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.TreeMap" + ], + "@ohos.util.TreeSet": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.TreeSet" + ], + "@ohos.util": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util" + ], + "@ohos.util.json": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.json" + ], + "@ohos.util.stream": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.util.stream" + ], + "@ohos.vibrator": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.vibrator" + ], + "@ohos.wallpaper": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.wallpaper" + ], + "@ohos.wantAgent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.wantAgent" + ], + "@ohos.web.netErrorList": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.web.netErrorList" + ], + "@ohos.web.webview": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.web.webview" + ], + "@ohos.wifi": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.wifi" + ], + "@ohos.wifiManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.wifiManager" + ], + "@ohos.wifiManagerExt": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.wifiManagerExt" + ], + "@ohos.wifiext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.wifiext" + ], + "@ohos.window": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.window" + ], + "@ohos.worker": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.worker" + ], + "@ohos.zlib": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@ohos.zlib" + ], + "@ohos.@system.app": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.app" + ], + "@ohos.@system.battery": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.battery" + ], + "@ohos.@system.bluetooth": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.bluetooth" + ], + "@ohos.@system.brightness": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.brightness" + ], + "@ohos.@system.cipher": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.cipher" + ], + "@ohos.@system.configuration": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.configuration" + ], + "@ohos.@system.device": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.device" + ], + "@ohos.@system.fetch": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.fetch" + ], + "@ohos.@system.file": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.file" + ], + "@ohos.@system.geolocation": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.geolocation" + ], + "@ohos.@system.mediaquery": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.mediaquery" + ], + "@ohos.@system.network": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.network" + ], + "@ohos.@system.notification": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.notification" + ], + "@ohos.@system.package": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.package" + ], + "@ohos.@system.prompt": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.prompt" + ], + "@ohos.@system.request": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.request" + ], + "@ohos.@system.router": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.router" + ], + "@ohos.@system.sensor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.sensor" + ], + "@ohos.@system.storage": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.storage" + ], + "@ohos.@system.vibrator": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/@system.vibrator" + ], + "@ohos.ability.abilityResult": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/ability/abilityResult" + ], + "@ohos.ability.connectOptions": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/ability/connectOptions" + ], + "@ohos.ability.dataAbilityHelper": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/ability/dataAbilityHelper" + ], + "@ohos.ability.dataAbilityOperation": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/ability/dataAbilityOperation" + ], + "@ohos.ability.dataAbilityResult": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/ability/dataAbilityResult" + ], + "@ohos.ability.startAbilityParameter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/ability/startAbilityParameter" + ], + "@ohos.ability.want": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/ability/want" + ], + "@ohos.advertising.advertisement": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/advertising/advertisement" + ], + "@ohos.app.appVersionInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/app/appVersionInfo" + ], + "@ohos.app.context": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/app/context" + ], + "@ohos.app.processInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/app/processInfo" + ], + "@ohos.application.AbilityDelegator": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityDelegator" + ], + "@ohos.application.AbilityFirstFrameStateData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityFirstFrameStateData" + ], + "@ohos.application.AbilityFirstFrameStateObserver": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityFirstFrameStateObserver" + ], + "@ohos.application.AbilityForegroundStateObserver": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityForegroundStateObserver" + ], + "@ohos.application.AbilityMonitor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityMonitor" + ], + "@ohos.application.AbilityRunningInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityRunningInfo" + ], + "@ohos.application.AbilityStageContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityStageContext" + ], + "@ohos.application.AbilityStageMonitor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityStageMonitor" + ], + "@ohos.application.AbilityStartCallback": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityStartCallback" + ], + "@ohos.application.AbilityStateData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AbilityStateData" + ], + "@ohos.application.AccessibilityExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AccessibilityExtensionContext" + ], + "@ohos.application.AppForegroundStateObserver": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AppForegroundStateObserver" + ], + "@ohos.application.AppStateData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AppStateData" + ], + "@ohos.application.ApplicationContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ApplicationContext" + ], + "@ohos.application.ApplicationStateObserver": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ApplicationStateObserver" + ], + "@ohos.application.AutoFillExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AutoFillExtensionContext" + ], + "@ohos.application.AutoFillPopupConfig": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AutoFillPopupConfig" + ], + "@ohos.application.AutoFillRect": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AutoFillRect" + ], + "@ohos.application.AutoFillRequest": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AutoFillRequest" + ], + "@ohos.application.AutoFillType": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AutoFillType" + ], + "@ohos.application.AutoStartupCallback": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AutoStartupCallback" + ], + "@ohos.application.AutoStartupInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/AutoStartupInfo" + ], + "@ohos.application.BaseContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/BaseContext" + ], + "@ohos.application.BusinessAbilityInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/BusinessAbilityInfo" + ], + "@ohos.application.Context": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/Context" + ], + "@ohos.application.ContinuableInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ContinuableInfo" + ], + "@ohos.application.ContinueCallback": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ContinueCallback" + ], + "@ohos.application.ContinueDeviceInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ContinueDeviceInfo" + ], + "@ohos.application.ContinueMissionInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ContinueMissionInfo" + ], + "@ohos.application.CustomData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/CustomData" + ], + "@ohos.application.DriverExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/DriverExtensionContext" + ], + "@ohos.application.EmbeddableUIAbilityContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/EmbeddableUIAbilityContext" + ], + "@ohos.application.ErrorObserver": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ErrorObserver" + ], + "@ohos.application.EventHub": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/EventHub" + ], + "@ohos.application.ExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ExtensionContext" + ], + "@ohos.application.ExtensionRunningInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ExtensionRunningInfo" + ], + "@ohos.application.FormExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/FormExtensionContext" + ], + "@ohos.application.LoopObserver": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/LoopObserver" + ], + "@ohos.application.MediaControlExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/MediaControlExtensionContext" + ], + "@ohos.application.MissionCallbacks": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/MissionCallbacks" + ], + "@ohos.application.MissionDeviceInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/MissionDeviceInfo" + ], + "@ohos.application.MissionInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/MissionInfo" + ], + "@ohos.application.MissionListener": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/MissionListener" + ], + "@ohos.application.MissionParameter": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/MissionParameter" + ], + "@ohos.application.MissionSnapshot": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/MissionSnapshot" + ], + "@ohos.application.MultiAppMode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/MultiAppMode" + ], + "@ohos.application.PageNodeInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/PageNodeInfo" + ], + "@ohos.application.PhotoEditorExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/PhotoEditorExtensionContext" + ], + "@ohos.application.ProcessData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ProcessData" + ], + "@ohos.application.ProcessInformation": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ProcessInformation" + ], + "@ohos.application.ProcessRunningInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ProcessRunningInfo" + ], + "@ohos.application.RunningAppClone": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/RunningAppClone" + ], + "@ohos.application.RunningMultiAppInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/RunningMultiAppInfo" + ], + "@ohos.application.RunningMultiInstanceInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/RunningMultiInstanceInfo" + ], + "@ohos.application.SendableContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/SendableContext" + ], + "@ohos.application.ServiceExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ServiceExtensionContext" + ], + "@ohos.application.UIAbilityContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/UIAbilityContext" + ], + "@ohos.application.UIExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/UIExtensionContext" + ], + "@ohos.application.UIServiceExtensionConnectCallback": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/UIServiceExtensionConnectCallback" + ], + "@ohos.application.UIServiceExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/UIServiceExtensionContext" + ], + "@ohos.application.UIServiceHostProxy": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/UIServiceHostProxy" + ], + "@ohos.application.UIServiceProxy": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/UIServiceProxy" + ], + "@ohos.application.ViewData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/ViewData" + ], + "@ohos.application.VpnExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/VpnExtensionContext" + ], + "@ohos.application.WindowExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/WindowExtensionContext" + ], + "@ohos.application.WorkSchedulerExtensionContext": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/WorkSchedulerExtensionContext" + ], + "@ohos.application.abilityDelegatorArgs": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/abilityDelegatorArgs" + ], + "@ohos.application.shellCmdResult": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/application/shellCmdResult" + ], + "@ohos.arkui.AlphabetIndexerModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/AlphabetIndexerModifier" + ], + "@ohos.arkui.AttributeUpdater": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/AttributeUpdater" + ], + "@ohos.arkui.BlankModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/BlankModifier" + ], + "@ohos.arkui.BuilderNode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/BuilderNode" + ], + "@ohos.arkui.ButtonModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ButtonModifier" + ], + "@ohos.arkui.CalendarPickerModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/CalendarPickerModifier" + ], + "@ohos.arkui.CheckboxGroupModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/CheckboxGroupModifier" + ], + "@ohos.arkui.CheckboxModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/CheckboxModifier" + ], + "@ohos.arkui.ColumnModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ColumnModifier" + ], + "@ohos.arkui.ColumnSplitModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ColumnSplitModifier" + ], + "@ohos.arkui.CommonModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/CommonModifier" + ], + "@ohos.arkui.ComponentContent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ComponentContent" + ], + "@ohos.arkui.ContainerSpanModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ContainerSpanModifier" + ], + "@ohos.arkui.Content": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/Content" + ], + "@ohos.arkui.CounterModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/CounterModifier" + ], + "@ohos.arkui.DataPanelModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/DataPanelModifier" + ], + "@ohos.arkui.DatePickerModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/DatePickerModifier" + ], + "@ohos.arkui.DividerModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/DividerModifier" + ], + "@ohos.arkui.FormComponentModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/FormComponentModifier" + ], + "@ohos.arkui.FrameNode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/FrameNode" + ], + "@ohos.arkui.GaugeModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/GaugeModifier" + ], + "@ohos.arkui.Graphics": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/Graphics" + ], + "@ohos.arkui.GridColModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/GridColModifier" + ], + "@ohos.arkui.GridItemModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/GridItemModifier" + ], + "@ohos.arkui.GridModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/GridModifier" + ], + "@ohos.arkui.GridRowModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/GridRowModifier" + ], + "@ohos.arkui.HyperlinkModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/HyperlinkModifier" + ], + "@ohos.arkui.ImageAnimatorModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ImageAnimatorModifier" + ], + "@ohos.arkui.ImageModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ImageModifier" + ], + "@ohos.arkui.ImageSpanModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ImageSpanModifier" + ], + "@ohos.arkui.LineModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/LineModifier" + ], + "@ohos.arkui.ListItemGroupModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ListItemGroupModifier" + ], + "@ohos.arkui.ListItemModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ListItemModifier" + ], + "@ohos.arkui.ListModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ListModifier" + ], + "@ohos.arkui.LoadingProgressModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/LoadingProgressModifier" + ], + "@ohos.arkui.MarqueeModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/MarqueeModifier" + ], + "@ohos.arkui.MenuItemModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/MenuItemModifier" + ], + "@ohos.arkui.MenuModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/MenuModifier" + ], + "@ohos.arkui.NavDestinationModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/NavDestinationModifier" + ], + "@ohos.arkui.NavRouterModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/NavRouterModifier" + ], + "@ohos.arkui.NavigationModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/NavigationModifier" + ], + "@ohos.arkui.NavigatorModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/NavigatorModifier" + ], + "@ohos.arkui.NodeContent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/NodeContent" + ], + "@ohos.arkui.NodeController": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/NodeController" + ], + "@ohos.arkui.PanelModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/PanelModifier" + ], + "@ohos.arkui.ParticleModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ParticleModifier" + ], + "@ohos.arkui.PathModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/PathModifier" + ], + "@ohos.arkui.PatternLockModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/PatternLockModifier" + ], + "@ohos.arkui.PolygonModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/PolygonModifier" + ], + "@ohos.arkui.PolylineModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/PolylineModifier" + ], + "@ohos.arkui.ProgressModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ProgressModifier" + ], + "@ohos.arkui.QRCodeModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/QRCodeModifier" + ], + "@ohos.arkui.RadioModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/RadioModifier" + ], + "@ohos.arkui.RatingModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/RatingModifier" + ], + "@ohos.arkui.RectModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/RectModifier" + ], + "@ohos.arkui.RefreshModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/RefreshModifier" + ], + "@ohos.arkui.RenderNode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/RenderNode" + ], + "@ohos.arkui.RichEditorModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/RichEditorModifier" + ], + "@ohos.arkui.RowModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/RowModifier" + ], + "@ohos.arkui.RowSplitModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/RowSplitModifier" + ], + "@ohos.arkui.ScrollModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ScrollModifier" + ], + "@ohos.arkui.SearchModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/SearchModifier" + ], + "@ohos.arkui.SelectModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/SelectModifier" + ], + "@ohos.arkui.ShapeModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ShapeModifier" + ], + "@ohos.arkui.SideBarContainerModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/SideBarContainerModifier" + ], + "@ohos.arkui.SliderModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/SliderModifier" + ], + "@ohos.arkui.SpanModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/SpanModifier" + ], + "@ohos.arkui.StackModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/StackModifier" + ], + "@ohos.arkui.StepperItemModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/StepperItemModifier" + ], + "@ohos.arkui.SwiperModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/SwiperModifier" + ], + "@ohos.arkui.SymbolGlyphModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/SymbolGlyphModifier" + ], + "@ohos.arkui.SymbolSpanModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/SymbolSpanModifier" + ], + "@ohos.arkui.TabsModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/TabsModifier" + ], + "@ohos.arkui.TextAreaModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/TextAreaModifier" + ], + "@ohos.arkui.TextClockModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/TextClockModifier" + ], + "@ohos.arkui.TextInputModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/TextInputModifier" + ], + "@ohos.arkui.TextModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/TextModifier" + ], + "@ohos.arkui.TextPickerModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/TextPickerModifier" + ], + "@ohos.arkui.TextTimerModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/TextTimerModifier" + ], + "@ohos.arkui.TimePickerModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/TimePickerModifier" + ], + "@ohos.arkui.ToggleModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/ToggleModifier" + ], + "@ohos.arkui.VideoModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/VideoModifier" + ], + "@ohos.arkui.WaterFlowModifier": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/WaterFlowModifier" + ], + "@ohos.arkui.XComponentNode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/XComponentNode" + ], + "@ohos.arkui.component.column": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/component/column" + ], + "@ohos.arkui.component.common": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/component/common" + ], + "@ohos.arkui.component.customComponent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/component/customComponent" + ], + "@ohos.arkui.component.enums": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/component/enums" + ], + "@ohos.arkui.component.styledString": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/component/styledString" + ], + "@ohos.arkui.component.text": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/component/text" + ], + "@ohos.arkui.component.units": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/component/units" + ], + "@ohos.arkui.external.resource": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/external/resource" + ], + "@koalaui.arkts-arkui.Button": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.arkts-arkui.Button" + ], + "@koalaui.arkts-arkui.Column": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.arkts-arkui.Column" + ], + "@koalaui.arkts-arkui.Common": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.arkts-arkui.Common" + ], + "@koalaui.arkts-arkui.StructBase": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.arkts-arkui.StructBase" + ], + "@koalaui.arkts-arkui.Text": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.arkts-arkui.Text" + ], + "@koalaui.arkts-arkui.UserView": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.arkts-arkui.UserView" + ], + "@koalaui.runtime.annotations": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.annotations" + ], + "@koalaui.runtime.common": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.common" + ], + "@koalaui.runtime.internals": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.internals" + ], + "@koalaui.runtime.memo.bind": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.memo.bind" + ], + "@koalaui.runtime.memo.changeListener": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.memo.changeListener" + ], + "@koalaui.runtime.memo.contextLocal": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.memo.contextLocal" + ], + "@koalaui.runtime.memo.entry": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.memo.entry" + ], + "@koalaui.runtime.memo.node": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.memo.node" + ], + "@koalaui.runtime.memo.remember": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.memo.remember" + ], + "@koalaui.runtime.memo.repeat": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.memo.repeat" + ], + "@koalaui.runtime.memo.testing": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.memo.testing" + ], + "@koalaui.runtime.states.Disposable": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.states.Disposable" + ], + "@koalaui.runtime.states.GlobalStateManager": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.states.GlobalStateManager" + ], + "@koalaui.runtime.states.State": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.states.State" + ], + "@koalaui.runtime.tree.IncrementalNode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.tree.IncrementalNode" + ], + "@koalaui.runtime.tree.PrimeNumbers": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.tree.PrimeNumbers" + ], + "@koalaui.runtime.tree.ReadonlyTreeNode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.tree.ReadonlyTreeNode" + ], + "@koalaui.runtime.tree.TreeNode": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.tree.TreeNode" + ], + "@koalaui.runtime.tree.TreePath": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/runtime-api/@koalaui.runtime.tree.TreePath" + ], + "@ohos.arkui.stateManagement.common": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/stateManagement/common" + ], + "@ohos.arkui.stateManagement.runtime": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/stateManagement/runtime" + ], + "@ohos.arkui.stateManagement.storage": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/arkui/stateManagement/storage" + ], + "@ohos.bundle.PermissionDef": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/PermissionDef" + ], + "@ohos.bundle.abilityInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/abilityInfo" + ], + "@ohos.bundle.applicationInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/applicationInfo" + ], + "@ohos.bundle.bundleInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/bundleInfo" + ], + "@ohos.bundle.bundleInstaller": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/bundleInstaller" + ], + "@ohos.bundle.bundleStatusCallback": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/bundleStatusCallback" + ], + "@ohos.bundle.customizeData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/customizeData" + ], + "@ohos.bundle.elementName": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/elementName" + ], + "@ohos.bundle.hapModuleInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/hapModuleInfo" + ], + "@ohos.bundle.launcherAbilityInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/launcherAbilityInfo" + ], + "@ohos.bundle.moduleInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/moduleInfo" + ], + "@ohos.bundle.remoteAbilityInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/remoteAbilityInfo" + ], + "@ohos.bundle.shortcutInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundle/shortcutInfo" + ], + "@ohos.bundleManager.AbilityInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/AbilityInfo" + ], + "@ohos.bundleManager.AppProvisionInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/AppProvisionInfo" + ], + "@ohos.bundleManager.ApplicationInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/ApplicationInfo" + ], + "@ohos.bundleManager.BundleInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/BundleInfo" + ], + "@ohos.bundleManager.BundlePackInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/BundlePackInfo" + ], + "@ohos.bundleManager.BundleResourceInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/BundleResourceInfo" + ], + "@ohos.bundleManager.DispatchInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/DispatchInfo" + ], + "@ohos.bundleManager.ElementName": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/ElementName" + ], + "@ohos.bundleManager.ExtensionAbilityInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/ExtensionAbilityInfo" + ], + "@ohos.bundleManager.HapModuleInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/HapModuleInfo" + ], + "@ohos.bundleManager.LauncherAbilityInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/LauncherAbilityInfo" + ], + "@ohos.bundleManager.LauncherAbilityResourceInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/LauncherAbilityResourceInfo" + ], + "@ohos.bundleManager.Metadata": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/Metadata" + ], + "@ohos.bundleManager.OverlayModuleInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/OverlayModuleInfo" + ], + "@ohos.bundleManager.PermissionDef": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/PermissionDef" + ], + "@ohos.bundleManager.RecoverableApplicationInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/RecoverableApplicationInfo" + ], + "@ohos.bundleManager.RemoteAbilityInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/RemoteAbilityInfo" + ], + "@ohos.bundleManager.SharedBundleInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/SharedBundleInfo" + ], + "@ohos.bundleManager.ShortcutInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/ShortcutInfo" + ], + "@ohos.bundleManager.Skill": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/bundleManager/Skill" + ], + "@ohos.commonEvent.commonEventData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/commonEvent/commonEventData" + ], + "@ohos.commonEvent.commonEventPublishData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/commonEvent/commonEventPublishData" + ], + "@ohos.commonEvent.commonEventSubscribeInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/commonEvent/commonEventSubscribeInfo" + ], + "@ohos.commonEvent.commonEventSubscriber": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/commonEvent/commonEventSubscriber" + ], + "@ohos.continuation.continuationExtraParams": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/continuation/continuationExtraParams" + ], + "@ohos.continuation.continuationResult": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/continuation/continuationResult" + ], + "@ohos.data.rdb.resultSet": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/data/rdb/resultSet" + ], + "@ohos.device-define.default.json": [ + "" + ], + "@ohos.device-define.liteWearable.json": [ + "" + ], + "@ohos.device-define.tablet.json": [ + "" + ], + "@ohos.device-define.wearable.json": [ + "" + ], + "@ohos.global.rawFileDescriptor": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/global/rawFileDescriptor" + ], + "@ohos.global.resource": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/global/resource" + ], + "@ohos.global.sendableResource": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/global/sendableResource" + ], + "@ohos.graphics3d.Scene": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/graphics3d/Scene" + ], + "@ohos.graphics3d.SceneNodes": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/graphics3d/SceneNodes" + ], + "@ohos.graphics3d.ScenePostProcessSettings": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/graphics3d/ScenePostProcessSettings" + ], + "@ohos.graphics3d.SceneResources": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/graphics3d/SceneResources" + ], + "@ohos.graphics3d.SceneTypes": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/graphics3d/SceneTypes" + ], + "@ohos.multimedia.ringtonePlayer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/multimedia/ringtonePlayer" + ], + "@ohos.multimedia.soundPool": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/multimedia/soundPool" + ], + "@ohos.multimedia.systemTonePlayer": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/multimedia/systemTonePlayer" + ], + "@ohos.notification.NotificationCommonDef": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/NotificationCommonDef" + ], + "@ohos.notification.notificationActionButton": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationActionButton" + ], + "@ohos.notification.notificationContent": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationContent" + ], + "@ohos.notification.notificationFlags": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationFlags" + ], + "@ohos.notification.notificationRequest": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationRequest" + ], + "@ohos.notification.notificationSlot": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationSlot" + ], + "@ohos.notification.notificationSorting": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationSorting" + ], + "@ohos.notification.notificationSortingMap": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationSortingMap" + ], + "@ohos.notification.notificationSubscribeInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationSubscribeInfo" + ], + "@ohos.notification.notificationSubscriber": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationSubscriber" + ], + "@ohos.notification.notificationTemplate": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationTemplate" + ], + "@ohos.notification.notificationUserInput": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/notification/notificationUserInput" + ], + "@ohos.permissions": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/permissions" + ], + "@ohos.security.PermissionRequestResult": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/security/PermissionRequestResult" + ], + "@ohos.tag.nfctech": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/tag/nfctech" + ], + "@ohos.tag.tagSession": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/tag/tagSession" + ], + "@ohos.wantAgent.triggerInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/wantAgent/triggerInfo" + ], + "@ohos.wantAgent.wantAgentInfo": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/api/wantAgent/wantAgentInfo" + ], + "@ohos.@arkts.collections": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/arkts/@arkts.collections" + ], + "@ohos.@arkts.lang": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/arkts/@arkts.lang" + ], + "@ohos.@arkts.math.Decimal": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/arkts/@arkts.math.Decimal" + ], + "@ohos.@arkts.utils": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/arkts/@arkts.utils" + ], + "@ohos.@kit.AVSessionKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.AVSessionKit" + ], + "@ohos.@kit.AbilityKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.AbilityKit" + ], + "@ohos.@kit.AccessibilityKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.AccessibilityKit" + ], + "@ohos.@kit.AdsKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.AdsKit" + ], + "@ohos.@kit.ArkData": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ArkData" + ], + "@ohos.@kit.ArkGraphics2D": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ArkGraphics2D" + ], + "@ohos.@kit.ArkGraphics3D": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ArkGraphics3D" + ], + "@ohos.@kit.ArkTS": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ArkTS" + ], + "@ohos.@kit.ArkUI": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ArkUI" + ], + "@ohos.@kit.ArkWeb": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ArkWeb" + ], + "@ohos.@kit.AssetStoreKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.AssetStoreKit" + ], + "@ohos.@kit.AudioKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.AudioKit" + ], + "@ohos.@kit.BackgroundTasksKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.BackgroundTasksKit" + ], + "@ohos.@kit.BasicServicesKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.BasicServicesKit" + ], + "@ohos.@kit.CalendarKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.CalendarKit" + ], + "@ohos.@kit.CameraKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.CameraKit" + ], + "@ohos.@kit.ConnectivityKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ConnectivityKit" + ], + "@ohos.@kit.ContactsKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ContactsKit" + ], + "@ohos.@kit.CoreFileKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.CoreFileKit" + ], + "@ohos.@kit.CryptoArchitectureKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.CryptoArchitectureKit" + ], + "@ohos.@kit.DataLossPreventionKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.DataLossPreventionKit" + ], + "@ohos.@kit.DataProtectionKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.DataProtectionKit" + ], + "@ohos.@kit.DeviceCertificateKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.DeviceCertificateKit" + ], + "@ohos.@kit.DistributedServiceKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.DistributedServiceKit" + ], + "@ohos.@kit.DriverDevelopmentKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.DriverDevelopmentKit" + ], + "@ohos.@kit.DrmKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.DrmKit" + ], + "@ohos.@kit.FormKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.FormKit" + ], + "@ohos.@kit.IMEKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.IMEKit" + ], + "@ohos.@kit.IPCKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.IPCKit" + ], + "@ohos.@kit.ImageKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.ImageKit" + ], + "@ohos.@kit.InputKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.InputKit" + ], + "@ohos.@kit.LocalizationKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.LocalizationKit" + ], + "@ohos.@kit.LocationKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.LocationKit" + ], + "@ohos.@kit.MDMKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.MDMKit" + ], + "@ohos.@kit.MediaKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.MediaKit" + ], + "@ohos.@kit.MediaLibraryKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.MediaLibraryKit" + ], + "@ohos.@kit.MindSporeLiteKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.MindSporeLiteKit" + ], + "@ohos.@kit.MultimodalAwarenessKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.MultimodalAwarenessKit" + ], + "@ohos.@kit.NetworkKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.NetworkKit" + ], + "@ohos.@kit.NotificationKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.NotificationKit" + ], + "@ohos.@kit.PerformanceAnalysisKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.PerformanceAnalysisKit" + ], + "@ohos.@kit.SecurityGuardKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.SecurityGuardKit" + ], + "@ohos.@kit.SensorServiceKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.SensorServiceKit" + ], + "@ohos.@kit.TelephonyKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.TelephonyKit" + ], + "@ohos.@kit.TestKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.TestKit" + ], + "@ohos.@kit.UniversalKeystoreKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.UniversalKeystoreKit" + ], + "@ohos.@kit.UserAuthenticationKit": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.UserAuthenticationKit" + ], + "@ohos.@kit.network": [ + "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/kits/@kit.network" + ] + }, + "entry": "", + "dynamicPaths": {} + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/localtest/build_config_template.json b/arkui-plugins/test/demo/localtest/build_config_template.json new file mode 100755 index 000000000..aa3de2c82 --- /dev/null +++ b/arkui-plugins/test/demo/localtest/build_config_template.json @@ -0,0 +1,24 @@ +{ + "plugins": { + "ui_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/ui-plugins/index", + "memo_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/memo-plugins/index" + }, + + "compileFiles": [ + "./demo/localtest/entry/new.ets" + ], + + "packageName" : "entry", + + "buildType": "build", + "buildMode": "Debug", + "moduleRootPath": "./demo/localtest/entry/", + "sourceRoots": ["./"], + + "loaderOutPath": "./dist", + "cachePath": "./dist/cache", + + "buildSdkPath": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/", + + "dependentModuleList": [] +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/localtest/build_decl_config_template.json b/arkui-plugins/test/demo/localtest/build_decl_config_template.json new file mode 100644 index 000000000..fc58a0e00 --- /dev/null +++ b/arkui-plugins/test/demo/localtest/build_decl_config_template.json @@ -0,0 +1,29 @@ +{ + "plugins": { + "interop_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/interop-plugins/index" + }, + + "compileFiles": [ + "./demo/localtest/entry/new.ets" + ], + + "packageName" : "entry", + + "buildType": "build", + "buildMode": "Debug", + "moduleRootPath": "./demo/localtest/entry/", + "sourceRoots": ["./"], + + "loaderOutPath": "./dist", + "cachePath": "./dist/cache", + + "buildSdkPath": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/", + + "dependentModuleList": [], + + "isIDE": "false", + "enableDeclgenEts2Ts": true, + + "declgenV1OutPath": "workspace/developtools/ace_ets2bundle/arkui-plugins/test/demo/hello_world/declgenV1OutPath", + "declgenBridgeCodePath": "workspace/developtools/ace_ets2bundle/arkui-plugins/test/demo/hello_world/declgenBridgeCodePath" +} diff --git a/arkui-plugins/test/demo/localtest/entry/index.ets b/arkui-plugins/test/demo/localtest/entry/index.ets new file mode 100644 index 000000000..c54a0d153 --- /dev/null +++ b/arkui-plugins/test/demo/localtest/entry/index.ets @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement"; +import { Text, Column, Component, Button, ClickEvent } from "@ohos.arkui.component"; + +import hilog from '@ohos.hilog'; + +@Component +export struct MyStateSample { + message: string = "Click"; + + build() { + Column(undefined) { + Text("Hello World") + .fontSize(20) + Button(this.message) + .backgroundColor("#FFFF00FF") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + }) + Child() + } + } +} + +@Component +export struct Child { + stateVar: string = "Child"; + + build() { + Text(this.stateVar) + .fontSize(50) + } +} diff --git a/arkui-plugins/test/demo/localtest/entry/new.ets b/arkui-plugins/test/demo/localtest/entry/new.ets new file mode 100755 index 000000000..551759239 --- /dev/null +++ b/arkui-plugins/test/demo/localtest/entry/new.ets @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickEvent, UserView } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins +import { State, Link, StateDecoratedVariable, LinkDecoratedVariable,MutableState, stateOf, observableProxy, DecoratedMutableVariable } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import hilog from '@ohos.hilog' + +@Component +struct MyStateSample { + @State stateVar: string = "Parent"; + message: string = "var"; + changeValue() { + this.stateVar+="~"; + } + build() { + Column(undefined) { + Button("ParentChange").backgroundColor("#FFFF00FF") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + this.changeValue(); + }) + Text(this.stateVar).fontSize(20) + ChildLink({stateVar: this.stateVar, stateVar1: this.stateVar, stateVar2: ""} as __Options_ChildLink) + } + } +} + + +@Component +struct ChildLink { + @Link stateVar: string = "Child"; + @State stateVar1: string = "Child"; + @Link stateVar2: string = "Child"; + changeValue() { + this.stateVar+="~"; + } + build() { + Button("ChildChange").backgroundColor("#FFFF00FF") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + this.changeValue(); + }) + Text(this.stateVar).fontSize(50) + } +} + +export class ComExampleTrivialApplication extends UserView { + getBuilder() { + hilog.info(0x0000, 'testTag', 'getBuilder'); + let wrapper = @memo () => { + hilog.info(0x0000, 'testTag', 'MyStateSample'); + MyStateSample(undefined); + } + return wrapper; + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/builder-lambda/instantiate-content.ets b/arkui-plugins/test/demo/mock/builder-lambda/instantiate-content.ets new file mode 100644 index 000000000..f63cefd67 --- /dev/null +++ b/arkui-plugins/test/demo/mock/builder-lambda/instantiate-content.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@koalaui.arkts-arkui.Common" +import { Column } from "@koalaui.arkts-arkui.Column" +import { Text } from "@koalaui.arkts-arkui.Text" + +@Component +struct MyStateSample { + build() { + Column() { + Text("Hello!") + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/builder-lambda/instantiate-multi-content.ets b/arkui-plugins/test/demo/mock/builder-lambda/instantiate-multi-content.ets new file mode 100644 index 000000000..c5712c859 --- /dev/null +++ b/arkui-plugins/test/demo/mock/builder-lambda/instantiate-multi-content.ets @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@koalaui.arkts-arkui.Common" +import { Column } from "@koalaui.arkts-arkui.Column" +import { Text } from "@koalaui.arkts-arkui.Text" +import { Button } from "@koalaui.arkts-arkui.Button" + +@Component +struct MyStateSample { + build() { + Column() { + Text("Hello!") + Button("click me") + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/builder-lambda/instantiate.ets b/arkui-plugins/test/demo/mock/builder-lambda/instantiate.ets new file mode 100644 index 000000000..1b05c1e8a --- /dev/null +++ b/arkui-plugins/test/demo/mock/builder-lambda/instantiate.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@koalaui.arkts-arkui.Common" +import { Column } from "@koalaui.arkts-arkui.Column" + +@Component +struct MyStateSample { + build() { + Column() {} + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/entry.ets b/arkui-plugins/test/demo/mock/entry.ets new file mode 100644 index 000000000..1a0b18983 --- /dev/null +++ b/arkui-plugins/test/demo/mock/entry.ets @@ -0,0 +1,16 @@ +/* + * 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. + */ + +class A {} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/struct-to-class.ets b/arkui-plugins/test/demo/mock/struct-to-class.ets new file mode 100644 index 000000000..85f67b07f --- /dev/null +++ b/arkui-plugins/test/demo/mock/struct-to-class.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import { Component } from "@koalaui.arkts-arkui.Common" + +@Component +struct MyStateSample { + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.component.column.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.column.d.ets new file mode 100644 index 000000000..915dc5ceb --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.component.column.d.ets @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo } from '../stateManagement/runtime'; +import { ComponentBuilder, CommonMethod, PointLightStyle } from './common'; +import { HorizontalAlign, FlexAlign } from './enums'; + +export declare interface ColumnOptions { + space?: string | number; +} + +export declare interface ColumnAttribute extends CommonMethod { + @memo + alignItems(value: HorizontalAlign): this; + @memo + justifyContent(value: FlexAlign): this; + @memo + pointLight(value: PointLightStyle): this; + @memo + reverse(isReversed?: boolean): this; +} + +@memo +@ComponentBuilder +export declare function Column ( + options?: ColumnOptions, + @memo + content?: () => void +): ColumnAttribute; \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.component.common.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.common.d.ets new file mode 100644 index 000000000..2ff6ea60a --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.component.common.d.ets @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Dimension, Length, ResourceColor } from "@ohos.arkui.component.units"; +import { IlluminatedType } from "@ohos.arkui.component.enums"; +import { memo } from '@ohos.arkui.stateManagement.runtime'; + +@Retention({policy: "SOURCE"}) +export @interface BuilderLambda { + value: string +} + +@Retention({policy: "SOURCE"}) +export declare @interface ComponentBuilder {}; + +@Retention({policy: "SOURCE"}) +export declare @interface BuilderParam {}; + +@Retention({policy: "SOURCE"}) +export declare @interface Builder {}; + +export declare interface LightSource { + positionX: Dimension; + positionY: Dimension; + positionZ: Dimension; + intensity: number; + color?: ResourceColor; +} + +export declare interface PointLightStyle { + lightSource?: LightSource; + illuminated?: IlluminatedType; + bloom?: number; +} + +export declare interface CommonMethod { + @memo + width(w: Length): this; + @memo + height(h: Length): this; + @memo + backgroundColor(color: ResourceColor): this; +} \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.component.customComponent.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.customComponent.d.ets new file mode 100644 index 000000000..728c949e7 --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.component.customComponent.d.ets @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo } from "@ohos.arkui.stateManagement.runtime"; +import { ComponentBuilder, CommonMethod } from "@ohos.arkui.component.common"; +import { Length, ResourceColor } from "@ohos.arkui.component.units"; + +@Retention({policy: "SOURCE"}) +export declare @interface Component {}; + +@Retention({policy: "SOURCE"}) +export declare @interface Entry { routeName: string }; + +@Retention({policy: "SOURCE"}) +export declare @interface Reusable {}; + +export declare abstract class CustomComponent, T_Options> implements + CommonMethod { + + @memo + @ComponentBuilder + static $_instantiate, S_Options>( + factory: () => S, + initializers?: S_Options, + @memo + content?: () => void + ): S; + + // Life cycle for custom component + aboutToAppear(): void; + aboutToDisappear(): void; + aboutToReuse(): void; + aboutToRecycle(): void; + + @memo + build(): void; + + // Implementation of common method + @memo + width(w: Length): this; + @memo + height(h: Length): this; + @memo + backgroundColor(color: ResourceColor): this; +} \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.component.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.d.ets new file mode 100644 index 000000000..0f74a9db4 --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.component.d.ets @@ -0,0 +1,22 @@ +/* + * 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. + */ + +export * from "@ohos.arkui.component.customComponent"; +export * from "@ohos.arkui.component.common"; +export * from "@ohos.arkui.component.column"; +export * from "@ohos.arkui.component.text"; +export * from "@ohos.arkui.component.styledString"; +export * from "@ohos.arkui.component.enums"; +export * from "@ohos.arkui.component.units"; \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.component.enums.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.enums.d.ets new file mode 100644 index 000000000..e72c21ace --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.component.enums.d.ets @@ -0,0 +1,53 @@ +/* + * 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. + */ + +export declare enum FlexAlign { + Start = 0, + Center = 1, + End = 2, + SpaceBetween = 3, + SpaceAround = 4, + SpaceEvenly = 5 +} + +export declare enum HorizontalAlign { + Start = 0, + Center = 1, + End = 2 +} + +export declare enum IlluminatedType { + NONE = 0, + BORDER = 1, + CONTENT = 2, + BORDER_CONTENT = 3, + BLOOM_BORDER = 4, + BLOOM_BORDER_CONTENT = 5 +} + +export declare enum Color { + White = 0, + Black = 1, + Blue = 2, + Brown = 3, + Gray = 4, + Green = 5, + Grey = 6, + Orange = 7, + Pink = 8, + Red = 9, + Yellow = 10, + Transparent = 11 +} \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.component.styledString.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.styledString.d.ets new file mode 100644 index 000000000..4a0e94d6f --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.component.styledString.d.ets @@ -0,0 +1,32 @@ +/* + * 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. + */ + +export declare class StyledString { + constructor(value: string /*| ImageAttachment | CustomSpan, styles?: Array*/); + + readonly length: number; + + getString(): string; + // getStyles(start: number, length: number, styledKey?: StyledStringKey): Array; + equals(other: StyledString): boolean; + subStyledString(start: number, length?: number): StyledString; + + static fromHtml(html: string): Promise; + static toHtml(styledString: StyledString): string; + // static marshalling(styledString: StyledString, callback: StyledStringMarshallCallback): ArrayBuffer; + // static unmarshalling(buffer: ArrayBuffer, callback: StyledStringUnmarshallCallback): Promise; + // static marshalling(styledString: StyledString): ArrayBuffer; + // static unmarshalling(buffer: ArrayBuffer): Promise; +} \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.component.text.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.text.d.ets new file mode 100644 index 000000000..5ba7ef754 --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.component.text.d.ets @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Resource } from "@ohos.arkui.external.resource"; +import { StyledString } from "@ohos.arkui.component.styledString"; +import { ComponentBuilder, CommonMethod } from "@ohos.arkui.component.common"; +import { ResourceColor, Length } from "@ohos.arkui.component.units"; +import { memo } from '@ohos.arkui.stateManagement.runtime'; + +export declare class TextController { + closeSelectionMenu(): void; + setStyledString(value: StyledString): void; + + // getLayoutManager(): LayoutManager; +} + +export declare interface TextOptions { + controller: TextController; +} + +export declare interface TextAttribute extends CommonMethod { + // @memo + // font(value: Font, options?: FontSettingOptions): this; + @memo + fontColor(value: ResourceColor): this; + @memo + fontSize(value: number | string | Resource): this; + @memo + minFontSize(value: number | string | Resource): this; + @memo + maxFontSize(value: number | string | Resource): this; + @memo + minFontScale(scale: number | Resource): this; + @memo + maxFontScale(scale: number | Resource): this; + // @memo + // fontStyle(value: FontStyle): this; + // @memo + // fontWeight(value: number | FontWeight | string): this; + // @memo + // fontWeight(weight: number | FontWeight | string, options?: FontSettingOptions): this; + // @memo + // lineSpacing(value: LengthMetrics): this; + // @memo + // textAlign(value: TextAlign): this; + @memo + lineHeight(value: number | string | Resource): this; + // @memo + // textOverflow(options: TextOverflowOptions): this; + @memo + fontFamily(value: string | Resource): this; + @memo + maxLines(value: number): this; + // @memo + // decoration(value: DecorationStyleInterface): this; + @memo + letterSpacing(value: number | string): this; + // @memo + // textCase(value: TextCase): this; + @memo + baselineOffset(value: number | string): this; + // @memo + // copyOption(value: CopyOptions): this; + @memo + draggable(value: boolean): this; + // @memo + // textShadow(value: ShadowOptions | Array): this; + // @memo + // heightAdaptivePolicy(value: TextHeightAdaptivePolicy): this; + @memo + textIndent(value: Length): this; + // @memo + // wordBreak(value: WordBreak): this; + // @memo + // lineBreakStrategy(strategy: LineBreakStrategy): this; + @memo + onCopy(callback: (value: string) => void): this; + @memo + selection(selectionStart: number, selectionEnd: number): this; + @memo + caretColor(color: ResourceColor): this; + @memo + selectedBackgroundColor(color: ResourceColor): this; + // @memo + // ellipsisMode(value: EllipsisMode): this; + @memo + enableDataDetector(enable: boolean): this; + // @memo + // dataDetectorConfig(config: TextDataDetectorConfig): this; + // @memo + // bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType, + // options?: SelectionMenuOptions): this; + @memo + onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void): this; + @memo + fontFeature(value: string): this; + // @memo + // marqueeOptions(options: Optional): this; + // @memo + // onMarqueeStateChange(callback: Callback): this; + @memo + privacySensitive(supported: boolean): this; + // @memo + // textSelectable(mode: TextSelectableMode): this; + // @memo + // editMenuOptions(editMenu: EditMenuOptions): this; + @memo + halfLeading(halfLeading: boolean): this; + @memo + enableHapticFeedback(isEnabled: boolean): this; +} + +@memo +@ComponentBuilder +export declare function Text ( + value?: string | Resource, + options?: TextOptions, + @memo + content?: () => void +): TextAttribute; diff --git a/arkui-plugins/test/local/@ohos.arkui.component.units.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.units.d.ets new file mode 100644 index 000000000..c6a98e628 --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.component.units.d.ets @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Resource } from "@ohos.arkui.external.resource" +import { Color } from "@ohos.arkui.component.enums"; + +export type PX = string; +export type VP = string | number; +export type FP = string; +export type LPX = string; +export type Percentage = string; + +export type Dimension = PX | VP | FP | LPX | Percentage | Resource; + +export type Length = string | number | Resource; + +export type ResourceColor = Color | number | string | Resource; \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.external.resource.d.ets b/arkui-plugins/test/local/@ohos.arkui.external.resource.d.ets new file mode 100644 index 000000000..9cc3b09e0 --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.external.resource.d.ets @@ -0,0 +1,16 @@ +/* + * 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. + */ + +export type Resource = boolean; \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.stateManagement.common.d.ets b/arkui-plugins/test/local/@ohos.arkui.stateManagement.common.d.ets new file mode 100644 index 000000000..274947957 --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.stateManagement.common.d.ets @@ -0,0 +1,61 @@ +/* + * 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. + */ + +@Retention({policy: "SOURCE"}) +export declare @interface State {}; + +@Retention({policy: "SOURCE"}) +export declare @interface Prop {}; + +@Retention({policy: "SOURCE"}) +export declare @interface Link {}; + +@Retention({policy: "SOURCE"}) +export declare @interface Observed {}; + +@Retention({policy: "SOURCE"}) +export declare @interface Track {}; + +@Retention({policy: "SOURCE"}) +export declare @interface ObjectLink {}; + +@Retention({policy: "SOURCE"}) +export declare @interface StorageProp { value: string }; + +@Retention({policy: "SOURCE"}) +export declare @interface StorageLink { value: string }; + +@Retention({policy: "SOURCE"}) +export declare @interface LocalStorageProp { value: string }; + +@Retention({policy: "SOURCE"}) +export declare @interface LocalStorageLink { value: string }; + +@Retention({policy: "SOURCE"}) +export declare @interface Provide { value: string }; + +@Retention({policy: "SOURCE"}) +export declare @interface Consume { value: string }; + +@Retention({policy: "SOURCE"}) +export declare @interface Watch { value: string }; + +@Retention({policy: "SOURCE"}) +export declare @interface Require {}; + +export declare class UIUtils { + static getTarget(source: T): T; + static makeObserved(source: T): T; +} \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.stateManagement.d.ets b/arkui-plugins/test/local/@ohos.arkui.stateManagement.d.ets new file mode 100644 index 000000000..9cb01ec59 --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.stateManagement.d.ets @@ -0,0 +1,18 @@ +/* + * 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. + */ + +export * from "@ohos.arkui.stateManagement.common"; +export * from "@ohos.arkui.stateManagement.runtime"; +export * from "@ohos.arkui.stateManagement.storage"; diff --git a/arkui-plugins/test/local/@ohos.arkui.stateManagement.runtime.d.ets b/arkui-plugins/test/local/@ohos.arkui.stateManagement.runtime.d.ets new file mode 100644 index 000000000..f70c0cb7f --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.stateManagement.runtime.d.ets @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { LocalStorage } from "@ohos.arkui.stateManagement.storage" + +// From incremental engine +@Retention({policy: "SOURCE"}) +export declare @interface memo {}; + +export type __memo_context_type = StateContext; +export type __memo_id_type = MemoCallSiteKey; + +export type MemoCallSiteKey = int; + +export declare interface Disposable { + readonly disposed: boolean; + dispose(): void; +} + +export declare interface State { + readonly modified: boolean; + readonly value: T; +} + +export declare interface MutableState extends Disposable, State { + value: T; +} + +export type Equivalent = (oldV: T, newV: T) => boolean; + +export declare interface InternalScope { + readonly unchanged: boolean; + readonly cached: Value; + recache(newValue?: Value): Value; + param(index: int, value: T, equivalent?: Equivalent, name?: string, contextLocal?: boolean): State; +} + +export declare interface StateContext { + scope(id: MemoCallSiteKey, paramCount?: int): InternalScope; +} + +// From Arkoala +export declare function propState(value?: T): MutableState; +export declare function objectLinkState(value?: T): MutableState; +export declare function stateOf(value: T): MutableState; +export declare function contextLocalStateOf(value: T, key: () => T): MutableState; +export declare function contextLocal(value: T): MutableState; +export declare function observableProxy(value: T): T; +export declare function StorageLinkState(storage: LocalStorage, name: string, value: T): MutableState +export declare function AppStorageLinkState(name: string, value: T): MutableState; \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.stateManagement.storage.d.ets b/arkui-plugins/test/local/@ohos.arkui.stateManagement.storage.d.ets new file mode 100644 index 000000000..a7257c839 --- /dev/null +++ b/arkui-plugins/test/local/@ohos.arkui.stateManagement.storage.d.ets @@ -0,0 +1,119 @@ +/* + * 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. + */ + +export declare interface StorageProperty { + key: string; + defaultValue: number | string | boolean | Object; +} + +export type PersistPropsOptions = StorageProperty; + +export declare interface AbstractProperty { + info(): string; + get(): T; + set(newValue: T): void; +} + +export declare interface SubscribedAbstractProperty extends AbstractProperty { + aboutToBeDeleted(): void; +} + +export declare class LocalStorage { + static getShared(): LocalStorage | undefined; + + constructor(initializingProperties?: StorageProperty[]); + + has(propName: string): boolean; + + keys(): IterableIterator; + + size(): int; + + get(propName: string): T | undefined; + + set(propName: string, newValue: T): boolean; + + setOrCreate(propName: string, newValue?: T): boolean; + + ref(propName: string): AbstractProperty | undefined; + + setAndRef(propName: string, defaultValue: T): AbstractProperty; + + link(propName: string): SubscribedAbstractProperty | undefined; + + setAndLink(propName: string, defaultValue: T): SubscribedAbstractProperty; + + prop(propName: string): SubscribedAbstractProperty | undefined; + + setAndProp(propName: string, defaultValue: T): SubscribedAbstractProperty; + + delete(propName: string): boolean; + + clear(): boolean; +} + +export declare class AppStorage { + static has(propName: string): boolean; + + static keys(): IterableIterator; + + static size(): int; + + static get(propName: string): T | undefined; + + static set(propName: string, newValue: T): boolean; + + static setOrCreate(propName: string, newValue?: T): boolean; + + static ref(propName: string): AbstractProperty | undefined; + + static setAndRef(propName: string, defaultValue: T): AbstractProperty; + + static link(propName: string): SubscribedAbstractProperty | undefined; + + static setAndLink(propName: string, defaultValue: T): SubscribedAbstractProperty; + + static prop(propName: string): SubscribedAbstractProperty | undefined; + + static setAndProp(propName: string, defaultValue: T): SubscribedAbstractProperty; + + static delete(propName: string): boolean; + + static clear(): boolean; +} + +export declare class PersistentStorage { + + static persistProp(key: string, defaultValue: T): void; + + static deleteProp(key: string): void; + + static persistProps(props: PersistPropsOptions[]): void; + + static keys(): Array; +} + +export declare interface EnvPropsOptions { + key: string; + defaultValue: number | string | boolean; +} + +export declare class Environment { + static envProp(key: string, value: S): boolean; + + static envProps(props: EnvPropsOptions[]): void; + + static keys(): Array; +} \ No newline at end of file diff --git a/arkui-plugins/test/localtest_config.js b/arkui-plugins/test/localtest_config.js new file mode 100644 index 000000000..87fd2e7ee --- /dev/null +++ b/arkui-plugins/test/localtest_config.js @@ -0,0 +1,51 @@ +/* + * 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. + */ + +const fs = require('fs'); +const path = require('path'); + +// 获取当前目录 +const currentDirectory = process.cwd(); +let workSpace = currentDirectory; +for (let i = 0; i < 4; i++) { + workSpace = path.dirname(workSpace); +} +// JSON 文件路径 +const jsonFilePath = path.join(__dirname, 'demo/localtest/build_config_template.json'); +const outJsonFilePath = path.join(__dirname, 'demo/localtest/build_config.json'); + +try { + // 读取 JSON 文件内容 + const data = fs.readFileSync(jsonFilePath, 'utf8'); + const jsonData = JSON.parse(data); + console.log(jsonData) + // 处理 baseUrl 字段 + if (jsonData.buildSdkPath) { + jsonData.buildSdkPath = jsonData.buildSdkPath.replace(/workspace/g, workSpace); + } + + // 处理 plugins 字段 + if (jsonData.plugins.ui_plugin) { + jsonData.plugins.ui_plugin = jsonData.plugins.ui_plugin.replace(/workspace/g, workSpace); + } + if (jsonData.plugins.memo_plugin) { + jsonData.plugins.memo_plugin = jsonData.plugins.memo_plugin.replace(/workspace/g, workSpace); + } + + // 将修改后的内容写回 JSON 文件 + fs.writeFileSync(outJsonFilePath, JSON.stringify(jsonData, null, 2), 'utf8'); +} catch (error) { + console.error('处理 JSON 文件时出错:', error); +} \ No newline at end of file diff --git a/arkui-plugins/test/localtest_decl_config.js b/arkui-plugins/test/localtest_decl_config.js new file mode 100644 index 000000000..999494cff --- /dev/null +++ b/arkui-plugins/test/localtest_decl_config.js @@ -0,0 +1,51 @@ +/* + * 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. + */ + +const fs = require('fs'); +const path = require('path'); + +const currentDirectory = process.cwd(); +let workSpace = currentDirectory; +for (let i = 0; i < 4; i++) { + workSpace = path.dirname(workSpace); +} + +const jsonFilePath = path.join(__dirname, 'demo/localtest/build_decl_config_template.json'); +const outJsonFilePath = path.join(__dirname, 'demo/localtest/build_decl_config.json'); + +try { + const data = fs.readFileSync(jsonFilePath, 'utf8'); + const jsonData = JSON.parse(data); + + if (jsonData.buildSdkPath) { + jsonData.buildSdkPath = jsonData.buildSdkPath.replace(/workspace/g, workSpace); + } + + if (jsonData.plugins.interop_plugin) { + jsonData.plugins.interop_plugin = jsonData.plugins.interop_plugin.replace(/workspace/g, workSpace); + } + + if (jsonData.declgenV1OutPath) { + jsonData.declgenV1OutPath = jsonData.declgenV1OutPath.replace(/workspace/g, workSpace); + } + + if (jsonData.declgenBridgeCodePath) { + jsonData.declgenBridgeCodePath = jsonData.declgenBridgeCodePath.replace(/workspace/g, workSpace); + } + + fs.writeFileSync(outJsonFilePath, JSON.stringify(jsonData, null, 2), 'utf8'); +} catch (error) { + console.error('writeFile error:', error); +} diff --git a/arkui-plugins/test/package.json b/arkui-plugins/test/package.json new file mode 100644 index 000000000..51154bd39 --- /dev/null +++ b/arkui-plugins/test/package.json @@ -0,0 +1,17 @@ +{ + "name": "arkui-plugins-test", + "version": "1.0.0", + "description": "", + "private": true, + "scripts": { + "compile:ohos": "node $INIT_CWD/../../../../arkcompiler/ets_frontend/ets2panda/driver/build-system/dist/entry.js ./demo/hello_world/build_config.json", + "compile:gdb": "gdb --args node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/hello_world/build_config.json", + "compile:plugins": "npm run compile --prefix .. ", + "localtest": "rm -rf dist && node localtest_config.js && npm run compile:plugins && LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_config.json", + "localtest_gdb": "LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib gdb --args node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_config.json", + "localtest_decl": "rm -rf dist && node localtest_decl_config.js && npm run compile:plugins && LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_decl_config.json", + "localtest_all": "npm run localtest_decl && npm run localtest", + "es2panda:compile": "node ./arktsconfig_gen.js && $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/bin/es2panda --arktsconfig=./dist/cache/arktsconfig.json", + "es2panda:test": "$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/bin/es2panda ./demo/localtest/entry/test.ets --output=test.abc" + } +} diff --git a/arkui-plugins/test/test.log b/arkui-plugins/test/test.log new file mode 100644 index 000000000..984a29adf --- /dev/null +++ b/arkui-plugins/test/test.log @@ -0,0 +1,372 @@ + +> build_system_test@1.0.0 compile:ohos_sdk +> node /home/wuhaibin/newcode/oh/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/hello_world/build_config.json + +[ + '/home/wuhaibin/.nvm/versions/node/v23.8.0/bin/node', + '/home/wuhaibin/newcode/oh/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js', + './demo/hello_world/build_config.json' +] +Updated PATH: /home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/test/node_modules/.bin:/home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/node_modules/.bin:/home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/node_modules/.bin:/home/wuhaibin/newcode/oh/developtools/node_modules/.bin:/home/wuhaibin/newcode/oh/node_modules/.bin:/home/wuhaibin/newcode/node_modules/.bin:/home/wuhaibin/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/home/wuhaibin/.nvm/versions/node/v23.8.0/lib/node_modules/npm/node_modules/@npmcli/run-script/lib/node-gyp-bin:/home/wuhaibin/.local/bin:/home/wuhaibin/bin:/home/wuhaibin/.nvm/versions/node/v23.8.0/bin:/home/wuhaibin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/wsl/lib:/mnt/c/WINDOWS/system32:/mnt/c/WINDOWS:/mnt/c/WINDOWS/System32/Wbem:/mnt/c/WINDOWS/System32/WindowsPowerShell/v1.0/:/mnt/c/WINDOWS/System32/OpenSSH/:/mnt/c/Users/wuhaibin/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/wuhaibin/AppData/Local/Programs/Microsoft VS Code/bin:/snap/bin:/home/wuhaibin/newcode/oh/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib +Loaded plugin: ui-plugin { uiTransform: [Function: uiTransform] } [Function: uiTransform] +Loaded plugin: memo-plugin { unmemoizeTransform: [Function: unmemoizeTransform] } [Function: unmemoizeTransform] +ets2pandaCmd: _ --extension ets --arktsconfig /home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/test/dist/cache/entry/arktsconfig.json --output /home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/test/dist/cache/entry/a.abc --debug-info ./demo/hello_world/entry/a.ets +[TS WRAPPER] CREATE CONFIG +InitModule: es2panda + +[TS WRAPPER] PROCEED TO STATE: 1 +es2panda proceedToState parsed +[TS WRAPPER] GET AST FROM CONTEXT +executing plugin: ui-plugin +[UI PLUGIN] AFTER PARSED ENTER +[AFTER PARSED SCRIPT]: +import { StructBase } from "@koalaui.arkts-arkui.StructBase"; + +import { Text as Text } from "@koalaui.arkts-arkui.Text"; + +import { Column as Column } from "@koalaui.arkts-arkui.Column"; + +import { Button as Button } from "@koalaui.arkts-arkui.Button"; + +import { Component as Component, StorageLink as StorageLink, State as State } from "@koalaui.arkts-arkui.Common"; + +import { UserView as UserView, UserViewBuilder as UserViewBuilder } from "@koalaui.arkts-arkui.UserView"; + +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.StateManagement.runtime"; + +import { memo as memo } from "@ohos.arkui.StateManagement.runtime"; + +function isTrue(): string { + return "aa"; +} + +final class MyStateSample extends StructBase { + public aaa: string = isTrue(); + + public build() { + Column(){ + Text("Hello World!"); + Text((this).aaa); + Button("change"); + }; + } + + public constructor() {} + +} + +class ComExampleTrivialApplication extends UserView { + public getBuilder(): UserViewBuilder { + let wrapper = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { + MyStateSample.instantiateImpl(undefined, ((): MyStateSample => new MyStateSample()), ({} as __Options_MyStateSample), undefined); + }); + return wrapper; + } + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + + +[UI PLUGIN] AFTER PARSED EXIT +plugin parsed finished +[TS WRAPPER] GET AST FROM CONTEXT +[TS WRAPPER] DESTROY AND RECREATE +[TS WRAPPER] PROCEED TO STATE: 4 +es2panda proceedToState checked +[TS WRAPPER] GET AST FROM CONTEXT +executing plugin: ui-plugin +[UI PLUGIN] AFTER CHECKED ENTER +[AFTER STRUCT SCRIPT] script: +import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; + +import { Text as Text } from "@koalaui.arkts-arkui.Text"; + +import { Column as Column } from "@koalaui.arkts-arkui.Column"; + +import { Button as Button } from "@koalaui.arkts-arkui.Button"; + +import { Component as Component, StorageLink as StorageLink, State as State } from "@koalaui.arkts-arkui.Common"; + +import { UserView as UserView, UserViewBuilder as UserViewBuilder } from "@koalaui.arkts-arkui.UserView"; + +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.StateManagement.runtime"; + +import { memo as memo } from "@ohos.arkui.StateManagement.runtime"; + +abstract class ETSGLOBAL { + public static main() {} + + public static _$init$_() {} + + public static isTrue(): string { + return "aa"; + } + + +} + +class MyStateSample extends StructBase { + @memo()public __initializeStruct(initializers?: __Options_MyStateSample, @memo()content?: (()=> void)): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + public aaa: string = ETSGLOBAL.isTrue(); + + @memo()protected _build(@memo()style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo()content: (()=> void) | undefined, initializers?: __Options_MyStateSample): void { + Column.instantiateImpl(((instance: Column): Column => { + return instance; + }), ((): Column => { + return new Column(); + }), (() => { + Text.instantiateImpl(((instance: Text): Text => { + return instance; + }), ((): Text => { + return new Text(); + }), "Hello World!") + Text.instantiateImpl(((instance: Text): Text => { + return instance; + }), ((): Text => { + return new Text(); + }), (this).aaa) + Button.instantiateImpl(((instance: Button): Button => { + return instance; + }), ((): Button => { + return new Button(); + }), "change") + })); + } + + public constructor() {} + +} + +class ComExampleTrivialApplication extends UserView { + public getBuilder(): UserViewBuilder { + let wrapper = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { + MyStateSample.instantiateImpl(undefined, ((): MyStateSample => { + return new MyStateSample(); + }), ({} as __Options_MyStateSample), undefined); + }); + return wrapper; + } + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + + +[UI PLUGIN] AFTER CHECKED EXIT +executing plugin: memo-plugin +[MEMO PLUGIN] AFTER CHECKED ENTER +[BEFORE MEMO SCRIPT] script: +import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; + +import { Text as Text } from "@koalaui.arkts-arkui.Text"; + +import { Column as Column } from "@koalaui.arkts-arkui.Column"; + +import { Button as Button } from "@koalaui.arkts-arkui.Button"; + +import { Component as Component, StorageLink as StorageLink, State as State } from "@koalaui.arkts-arkui.Common"; + +import { UserView as UserView, UserViewBuilder as UserViewBuilder } from "@koalaui.arkts-arkui.UserView"; + +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.StateManagement.runtime"; + +import { memo as memo } from "@ohos.arkui.StateManagement.runtime"; + +abstract class ETSGLOBAL { + public static main() {} + + public static _$init$_() {} + + public static isTrue(): string { + return "aa"; + } + + +} + +class MyStateSample extends StructBase { + @memo()public __initializeStruct(initializers?: __Options_MyStateSample, @memo()content?: (()=> void)): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + public aaa: string = ETSGLOBAL.isTrue(); + + @memo()protected _build(@memo()style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo()content: (()=> void) | undefined, initializers?: __Options_MyStateSample): void { + Column.instantiateImpl(((instance: Column): Column => { + return instance; + }), ((): Column => { + return new Column(); + }), (() => { + Text.instantiateImpl(((instance: Text): Text => { + return instance; + }), ((): Text => { + return new Text(); + }), "Hello World!") + Text.instantiateImpl(((instance: Text): Text => { + return instance; + }), ((): Text => { + return new Text(); + }), (this).aaa) + Button.instantiateImpl(((instance: Button): Button => { + return instance; + }), ((): Button => { + return new Button(); + }), "change") + })); + } + + public constructor() {} + +} + +class ComExampleTrivialApplication extends UserView { + public getBuilder(): UserViewBuilder { + let wrapper = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { + MyStateSample.instantiateImpl(undefined, ((): MyStateSample => { + return new MyStateSample(); + }), ({} as __Options_MyStateSample), undefined); + }); + return wrapper; + } + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + + +[AFTER MEMO SCRIPT] script: +import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; + +import { Text as Text } from "@koalaui.arkts-arkui.Text"; + +import { Column as Column } from "@koalaui.arkts-arkui.Column"; + +import { Button as Button } from "@koalaui.arkts-arkui.Button"; + +import { Component as Component, StorageLink as StorageLink, State as State } from "@koalaui.arkts-arkui.Common"; + +import { UserView as UserView, UserViewBuilder as UserViewBuilder } from "@koalaui.arkts-arkui.UserView"; + +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.StateManagement.runtime"; + +import { memo as memo } from "@ohos.arkui.StateManagement.runtime"; + +abstract class ETSGLOBAL { + public static main() {} + + public static _$init$_() {} + + public static isTrue(): string { + return "aa"; + } + + +} + +class MyStateSample extends StructBase { + public __initializeStruct(__memo_context: __memo_context_type, __memo_id: __memo_id_type, initializers?: __Options_MyStateSample, content?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + (168924120)), 2); + const __memo_parameter_initializers = __memo_scope.param(0, initializers), __memo_parameter_content = __memo_scope.param(1, content); + if (__memo_scope.unchanged) { + __memo_scope.recache(__memo_scope.cached) + return; + } + { + __memo_scope.recache() + return; + } + } + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + public aaa: string = ETSGLOBAL.isTrue(); + + protected _build(__memo_context: __memo_context_type, __memo_id: __memo_id_type, style: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: MyStateSample)=> MyStateSample) | undefined, content: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined, initializers?: __Options_MyStateSample): void { + const __memo_scope = __memo_context.scope(((__memo_id) + (168198604)), 3); + const __memo_parameter_style = __memo_scope.param(0, style), __memo_parameter_content = __memo_scope.param(1, content), __memo_parameter_initializers = __memo_scope.param(2, initializers); + if (__memo_scope.unchanged) { + __memo_scope.recache(__memo_scope.cached) + return; + } + Column.instantiateImpl(__memo_context, ((__memo_id) + (229216764)), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: Column): Column => { + return instance; + }), ((): Column => { + return new Column(); + }), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { + const __memo_scope = __memo_context.scope(((__memo_id) + (131080140)), 0); + if (__memo_scope.unchanged) { + __memo_scope.recache(__memo_scope.cached) + return; + } + Text.instantiateImpl(__memo_context, ((__memo_id) + (122349231)), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: Text): Text => { + return instance; + }), ((): Text => { + return new Text(); + }), "Hello World!") + Text.instantiateImpl(__memo_context, ((__memo_id) + (259830593)), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: Text): Text => { + return instance; + }), ((): Text => { + return new Text(); + }), (this).aaa) + Button.instantiateImpl(__memo_context, ((__memo_id) + (23671947)), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: Button): Button => { + return instance; + }), ((): Button => { + return new Button(); + }), "change") + { + __memo_scope.recache() + return; + } + })); + { + __memo_scope.recache() + return; + } + } + + public constructor() {} + +} + +class ComExampleTrivialApplication extends UserView { + public getBuilder(): UserViewBuilder { + let wrapper = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { + MyStateSample.instantiateImpl(__memo_context, ((__memo_id) + (44218244)), undefined, ((): MyStateSample => { + return new MyStateSample(); + }), ({} as __Options_MyStateSample), undefined); + }); + return wrapper; + } + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + + +[MEMO PLUGIN] AFTER CHECKED EXIT +plugin checked finished +[TS WRAPPER] GET AST FROM CONTEXT +[TS WRAPPER] DESTROY AND RECREATE +[TS WRAPPER] PROCEED TO STATE: 7 +es2panda bin generated +"/home/wuhaibin/newcode/oh/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/bin/ark_link" --output "/home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/test/dist/modules_static.abc" -- @"dist/cache/fileInfo.txt" diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts new file mode 100644 index 000000000..55babf966 --- /dev/null +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { PluginTestContext, PluginTester } from "../../utils/plugin-tester"; +import { annotation } from "../../../common/arkts-utils"; + +const pluginTester = new PluginTester("test arkts-utils"); + +function testAnnotation(this: PluginTestContext): void { + const anno: arkts.AnnotationUsage = annotation("State"); + expect(arkts.isAnnotationUsage(anno)).toBeTruthy(); + expect(anno.dumpSrc()).toBe("@State()"); +} + +pluginTester.run( + "annotation", + [], + { + parsed: [testAnnotation], + checked: [testAnnotation] + }, + { + stopAfter: "checked" + }, + { + beforeEach: [() => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }], + afterEach: [() => { + jest.spyOn(console, 'warn').mockRestore(); + }] + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts new file mode 100644 index 000000000..16ddbc7f3 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from "path"; +import * as arkts from "@koalaui/libarkts"; +import { PluginTestContext, PluginTester } from "../../../utils/plugin-tester"; +import { mockBuildConfig } from "../../../utils/artkts-config"; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; +import { parseDumpSrc } from "../../../utils/parse-string"; +import { PluginContext, Plugins } from "../../../../common/plugin-context"; +import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; +import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-transformer"; + +const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda"); + +const instantiateTransform: Plugins = { + name: 'instantiate', + parsed(this: PluginContext) { + let program = this.getArkTSProgram(); + if (program) { + let script: arkts.EtsScript = program.astNode; + + const componentTransformer = new ComponentTransformer( + { arkui: "@koalaui.arkts-arkui.StructBase" } + ); + script = componentTransformer.visitor(script) as arkts.EtsScript; + arkts.setAllParents(script); + return script; + } + }, + checked(this: PluginContext) { + let program = this.getArkTSProgram(); + if (program) { + let script: arkts.EtsScript = program.astNode; + + const builderLambdaTransformer = new BuilderLambdaTransformer(); + script = builderLambdaTransformer.visitor(script) as arkts.EtsScript; + arkts.setAllParents(script); + return script; + } + } +}; + +const pluginTester = new PluginTester("test build-lambda transformer"); + +// Test single-content instantiateImpl transformation +function testSingleContent(this: PluginTestContext): void { + const script: arkts.EtsScript = this.script as arkts.EtsScript; + const expectedScript: string = ` +import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; + +import { Component as Component } from "@koalaui.arkts-arkui.Common"; + +import { Column as Column } from "@koalaui.arkts-arkui.Column"; + +import { Text as Text } from "@koalaui.arkts-arkui.Text"; + +abstract class ETSGLOBAL { + public static main() {} + + public static _$init$_() {} + + +} + +final class MyStateSample extends StructBase { + public build() { + Column.instantiateImpl(((instance: Column): Column => { + return instance; + }), ((): Column => { + return new Column(); + }), (() => { + Text.instantiateImpl(((instance: Text): Text => { + return instance; + }), ((): Text => { + return new Text(); + }), "Hello!"); + })); + } + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); +}; + +pluginTester.run( + "transform $_instantiate for single component content", + [instantiateTransform], + { + 'checked:instantiate': [testSingleContent], + }, + { + stopAfter: "checked", + buildConfig: { + ...mockBuildConfig(), + compileFiles: [ + path.resolve( + getRootPath(), + MOCK_ENTRY_DIR_PATH, + "builder-lambda", + "instantiate-content.ets" + ) + ], + moduleRootPath + } + }, + { + beforeEach: [() => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }], + afterEach: [() => { + jest.spyOn(console, 'warn').mockRestore(); + }] + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts new file mode 100644 index 000000000..5170256d9 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from "path"; +import * as arkts from "@koalaui/libarkts"; +import { PluginTestContext, PluginTester } from "../../../utils/plugin-tester"; +import { mockBuildConfig } from "../../../utils/artkts-config"; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; +import { parseDumpSrc } from "../../../utils/parse-string"; +import { PluginContext, Plugins } from "../../../../common/plugin-context"; +import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; +import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-transformer"; + +const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda"); + +const instantiateTransform: Plugins = { + name: 'instantiate', + parsed(this: PluginContext) { + let program = this.getArkTSProgram(); + if (program) { + let script: arkts.EtsScript = program.astNode; + + const componentTransformer = new ComponentTransformer( + { arkui: "@koalaui.arkts-arkui.StructBase" } + ); + script = componentTransformer.visitor(script) as arkts.EtsScript; + arkts.setAllParents(script); + return script; + } + }, + checked(this: PluginContext) { + let program = this.getArkTSProgram(); + if (program) { + let script: arkts.EtsScript = program.astNode; + + const builderLambdaTransformer = new BuilderLambdaTransformer(); + script = builderLambdaTransformer.visitor(script) as arkts.EtsScript; + arkts.setAllParents(script); + return script; + } + } +}; + +const pluginTester = new PluginTester("test build-lambda transformer"); + +// Test multi-content instantiateImpl transformation +function testMultiContent(this: PluginTestContext): void { + const script: arkts.EtsScript = this.script as arkts.EtsScript; + const expectedScript: string = ` +import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; + +import { Component as Component } from "@koalaui.arkts-arkui.Common"; + +import { Column as Column } from "@koalaui.arkts-arkui.Column"; + +import { Text as Text } from "@koalaui.arkts-arkui.Text"; + +import { Button as Button } from "@koalaui.arkts-arkui.Button"; + +abstract class ETSGLOBAL { + public static main() {} + + public static _$init$_() {} + + +} + +final class MyStateSample extends StructBase { + public build() { + Column.instantiateImpl(((instance: Column): Column => { + return instance; + }), ((): Column => { + return new Column(); + }), (() => { + Text.instantiateImpl(((instance: Text): Text => { + return instance; + }), ((): Text => { + return new Text(); + }), "Hello!"); + Button.instantiateImpl(((instance: Button): Button => { + return instance; + }), ((): Button => { + return new Button(); + }), "click me"); + })); + } + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); +}; + +pluginTester.run( + "transform $_instantiate for multiple component contents", + [instantiateTransform], + { + 'checked:instantiate': [testMultiContent], + }, + { + stopAfter: "checked", + buildConfig: { + ...mockBuildConfig(), + compileFiles: [ + path.resolve( + getRootPath(), + MOCK_ENTRY_DIR_PATH, + "builder-lambda", + "instantiate-multi-content.ets" + ) + ], + moduleRootPath + } + }, + { + beforeEach: [() => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }], + afterEach: [() => { + jest.spyOn(console, 'warn').mockRestore(); + }] + } +); + diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts new file mode 100644 index 000000000..f7a104376 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from "path"; +import * as arkts from "@koalaui/libarkts"; +import { PluginTestContext, PluginTester } from "../../../utils/plugin-tester"; +import { BuildConfig, mockBuildConfig } from "../../../utils/artkts-config"; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; +import { parseDumpSrc } from "../../../utils/parse-string"; +import { PluginContext, Plugins } from "../../../../common/plugin-context"; +import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; +import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-transformer"; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda", "instantiate.ets") +]; +buildConfig.moduleRootPath = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda"); + +const instantiateTransform: Plugins = { + name: 'instantiate', + parsed(this: PluginContext) { + let program = this.getArkTSProgram(); + if (program) { + let script: arkts.EtsScript = program.astNode; + + const componentTransformer = new ComponentTransformer( + { arkui: "@koalaui.arkts-arkui.StructBase" } + ); + script = componentTransformer.visitor(script) as arkts.EtsScript; + arkts.setAllParents(script); + return script; + } + }, + checked(this: PluginContext) { + let program = this.getArkTSProgram(); + if (program) { + let script: arkts.EtsScript = program.astNode; + + const builderLambdaTransformer = new BuilderLambdaTransformer(); + script = builderLambdaTransformer.visitor(script) as arkts.EtsScript; + + arkts.setAllParents(script); + return script; + } + } +}; + +const pluginTester = new PluginTester("test build-lambda transformer", buildConfig); + +function testInstantiateImpl(this: PluginTestContext): void { + const script: arkts.EtsScript = this.script as arkts.EtsScript; + const expectedScript: string = ` +import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; + +import { Component as Component } from "@koalaui.arkts-arkui.Common"; + +import { Column as Column } from "@koalaui.arkts-arkui.Column"; + +abstract class ETSGLOBAL { + public static main() {} + + public static _$init$_() {} + + +} + +final class MyStateSample extends StructBase { + public build() { + Column.instantiateImpl(((instance: Column): Column => { + return instance; + }), ((): Column => { + return new Column(); + }), (() => {})); + } + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + "transform $_instantiate for a single component", + [instantiateTransform], + { + 'checked:instantiate': [testInstantiateImpl], + }, + { + stopAfter: "checked" + }, + { + beforeEach: [() => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }], + afterEach: [() => { + jest.spyOn(console, 'warn').mockRestore(); + }] + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts b/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts new file mode 100644 index 000000000..8074a2c50 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from "path"; +import * as arkts from "@koalaui/libarkts"; +import { PluginTestContext, PluginTester } from "../../utils/plugin-tester"; +import { BuildConfig, mockBuildConfig } from "../../utils/artkts-config"; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../utils/path-config"; +import { parseDumpSrc } from "../../utils/parse-string"; +import { PluginContext, Plugins } from "../../../common/plugin-context"; +import { ComponentTransformer } from "../../../ui-plugins/component-transformer"; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "struct-to-class.ets") +]; + +const componentTransform: Plugins = { + name: 'component', + parsed(this: PluginContext) { + let program = this.getArkTSProgram(); + if (program) { + let script: arkts.EtsScript = program.astNode; + + const componentTransformer = new ComponentTransformer( + { arkui: "@koalaui.arkts-arkui.StructBase" } + ); + script = componentTransformer.visitor(script) as arkts.EtsScript; + arkts.setAllParents(script); + return script; + } + } +} + +const pluginTester = new PluginTester("test component transformer", buildConfig); + +function testComponentTransformer(this: PluginTestContext): void { + const script: arkts.EtsScript = this.script as arkts.EtsScript; + const expectedScript: string = ` +import { StructBase } from \"@koalaui.arkts-arkui.StructBase\"; + +import { Component as Component } from \"@koalaui.arkts-arkui.Common\"; + +final class MyStateSample extends StructBase { + + public build() {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); +}; + +pluginTester.run( + "transform struct to class", + [componentTransform], + { + 'parsed:component': [testComponentTransformer], + }, + { + stopAfter: "parsed" + }, + { + beforeEach: [() => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }], + afterEach: [() => { + jest.spyOn(console, 'warn').mockRestore(); + }] + } +); diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts new file mode 100644 index 000000000..66f346cfb --- /dev/null +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -0,0 +1,334 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from "fs"; +import * as path from "path"; +import { + ABC_SUFFIX, + ARKTS_CONFIG_FILE_PATH, + changeFileExtension, + ensurePathExists, + getFileName, + getPandaSDKPath, + getRootPath, + MOCK_ENTRY_DIR_PATH, + MOCK_ENTRY_FILE_NAME, + MOCK_LOCAL_SDK_DIR_PATH, + MOCK_OUTPUT_CACHE_PATH, + MOCK_OUTPUT_DIR_PATH, + MOCK_OUTPUT_FILE_NAME, + PANDA_SDK_STDLIB_PATH, + RUNTIME_API_PATH, + STDLIB_ESCOMPAT_PATH, + STDLIB_PATH, + STDLIB_STD_PATH +} from "./path-config"; + +export interface ArkTSConfigObject { + compilerOptions: { + package: string, + baseUrl: string, + paths: Record; + dependencies: string[] | undefined; + entry: string; + } +} + +export interface CompileFileInfo { + fileName: string, + filePath: string, + dependentFiles: string[], + abcFilePath: string, + arktsConfigFile: string, + stdLibPath: string +} + +export interface ModuleInfo { + isMainModule: boolean, + packageName: string, + moduleRootPath: string, + sourceRoots: string[], + entryFile: string, + arktsConfigFile: string, + compileFileInfos: CompileFileInfo[], + dependencies?: string[] +} + +export interface DependentModule { + packageName: string, + moduleName: string, + moduleType: string, + modulePath: string, + sourceRoots: string[], + entryFile: string +} + +export type ModuleType = "har" | string; // TODO: module type unclear + +export interface DependentModule { + packageName: string; + moduleName: string; + moduleType: ModuleType; + modulePath: string; + sourceRoots: string[]; + entryFile: string; +} + +export interface BuildConfig { + packageName: string; + compileFiles: string[]; + loaderOutPath: string; + cachePath: string; + pandaSdkPath: string; + buildSdkPath: string; + sourceRoots: string[]; + moduleRootPath: string; + dependentModuleList: DependentModule[]; +} + +export interface ArktsConfigBuilder { + buildConfig: BuildConfig; + entryFiles: Set; + outputDir: string; + cacheDir: string; + pandaSdkPath: string; + buildSdkPath: string; + packageName: string; + sourceRoots: string[]; + moduleRootPath: string; + dependentModuleList: DependentModule[]; + moduleInfos: Map; + mergedAbcFile: string; + // logger: Logger; // TODO + isDebug: boolean; +} + +function writeArkTSConfigFile( + moduleInfo: ModuleInfo, + pathSection: Record, + dependenciesSection: string[] +): void { + if (!moduleInfo.sourceRoots || moduleInfo.sourceRoots.length == 0) { + throw new Error("Write Arkts config: does not have sourceRoots."); + } + + const baseUrl: string = path.resolve(moduleInfo.moduleRootPath, moduleInfo.sourceRoots[0]); + pathSection[moduleInfo.packageName] = [baseUrl]; + const arktsConfig: ArkTSConfigObject = { + compilerOptions: { + package: moduleInfo.packageName, + baseUrl: baseUrl, + paths: pathSection, + dependencies: dependenciesSection.length === 0 ? undefined : dependenciesSection, + entry: moduleInfo.entryFile + } + }; + + ensurePathExists(moduleInfo.arktsConfigFile); + fs.writeFileSync(moduleInfo.arktsConfigFile, JSON.stringify(arktsConfig, null, 2), 'utf-8'); +} + +function getDependentModules( + moduleInfo: ModuleInfo, + moduleInfoMap: Map +): Map { + if (moduleInfo.isMainModule) { + return moduleInfoMap; + } + + const depModules: Map = new Map(); + if (moduleInfo.dependencies) { + moduleInfo.dependencies.forEach((packageName: string) => { + const depModuleInfo: ModuleInfo | undefined = moduleInfoMap.get(packageName); + if (!depModuleInfo) { + throw new Error(`Dependent Module: Module ${packageName} not found in moduleInfos`); + } else { + depModules.set(packageName, depModuleInfo); + } + }); + } + return depModules; +} + +function traverse(currentDir: string, pathSection: Record) { + const items = fs.readdirSync(currentDir); + for (const item of items) { + const itemPath = path.join(currentDir, item); + const stat = fs.statSync(itemPath); + + if (stat.isFile()) { + const basename = path.basename(item, '.d.ets'); + pathSection[basename] = [changeFileExtension(itemPath, '', '.d.ets')]; + } else if (stat.isDirectory()) { + traverse(itemPath, pathSection); + } + } +} + +function mockBuildConfig(): BuildConfig { + return { + packageName: "mock", + compileFiles: [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MOCK_ENTRY_FILE_NAME) + ], + loaderOutPath: path.resolve(getRootPath(), MOCK_OUTPUT_DIR_PATH), + cachePath: path.resolve(getRootPath(), MOCK_OUTPUT_CACHE_PATH), + pandaSdkPath: getPandaSDKPath(), + buildSdkPath: path.resolve(getRootPath(), MOCK_LOCAL_SDK_DIR_PATH), + sourceRoots: [getRootPath()], + moduleRootPath: path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH), + dependentModuleList: [ + { + packageName: "@koalaui/runtime", + moduleName: "@koalaui/runtime", + moduleType: "har", + modulePath: path.resolve(getRootPath(), RUNTIME_API_PATH), + sourceRoots: ["./"], + entryFile: "index.sts" + } + ] + }; +} + +class MockArktsConfigBuilder implements ArktsConfigBuilder { + buildConfig: BuildConfig; + entryFiles: Set; + outputDir: string; + cacheDir: string; + pandaSdkPath: string; + buildSdkPath: string; + packageName: string; + sourceRoots: string[]; + moduleRootPath: string; + dependentModuleList: DependentModule[]; + moduleInfos: Map; + mergedAbcFile: string; + isDebug: boolean; + + constructor(buildConfig?: BuildConfig) { + const _buildConfig: BuildConfig = buildConfig ?? mockBuildConfig(); + this.buildConfig = _buildConfig; + this.entryFiles = new Set(_buildConfig.compileFiles as string[]); + this.outputDir = _buildConfig.loaderOutPath as string; + this.cacheDir = _buildConfig.cachePath as string; + this.pandaSdkPath = path.resolve(_buildConfig.pandaSdkPath as string); + this.buildSdkPath = path.resolve(_buildConfig.buildSdkPath as string); + this.packageName = _buildConfig.packageName as string; + this.sourceRoots = _buildConfig.sourceRoots as string[]; + this.moduleRootPath = path.resolve(_buildConfig.moduleRootPath as string); + this.dependentModuleList = _buildConfig.dependentModuleList as DependentModule[]; + this.isDebug = true; + + this.moduleInfos = new Map(); + this.mergedAbcFile = path.resolve(this.outputDir, MOCK_OUTPUT_FILE_NAME); + + this.generateModuleInfos(); + this.generateArkTSConfigForModules(); + } + + private generateModuleInfos(): void { + if (!this.packageName || !this.moduleRootPath || !this.sourceRoots) { + throw new Error("Main module: packageName, moduleRootPath, and sourceRoots are required"); + } + const mainModuleInfo: ModuleInfo = { + isMainModule: true, + packageName: this.packageName, + moduleRootPath: this.moduleRootPath, + sourceRoots: this.sourceRoots, + entryFile: '', + arktsConfigFile: path.resolve(this.cacheDir, this.packageName, ARKTS_CONFIG_FILE_PATH), + compileFileInfos: [] + } + this.moduleInfos.set(this.moduleRootPath, mainModuleInfo); + this.dependentModuleList.forEach((module: DependentModule) => { + if (!module.packageName || !module.modulePath || !module.sourceRoots || !module.entryFile) { + throw new Error( + "Dependent module: packageName, modulePath, sourceRoots, and entryFile are required" + ); + } + const moduleInfo: ModuleInfo = { + isMainModule: false, + packageName: module.packageName, + moduleRootPath: module.modulePath, + sourceRoots: module.sourceRoots, + entryFile: module.entryFile, + arktsConfigFile: path.resolve(this.cacheDir, module.packageName, ARKTS_CONFIG_FILE_PATH), + compileFileInfos: [] + } + this.moduleInfos.set(module.modulePath, moduleInfo); + }); + this.entryFiles.forEach((file: string) => { + const _file = path.resolve(file); + for (const [modulePath, moduleInfo] of this.moduleInfos) { + if (_file.startsWith(modulePath)) { + const filePathFromModuleRoot: string = path.relative(modulePath, _file); + const filePathInCache: string = path.join( + this.cacheDir, moduleInfo.packageName, filePathFromModuleRoot); + const abcFilePath: string = path.resolve(changeFileExtension(filePathInCache, ABC_SUFFIX)); + + const fileInfo: CompileFileInfo = { + fileName: getFileName(_file), + filePath: _file, + dependentFiles: [], + abcFilePath: abcFilePath, + arktsConfigFile: moduleInfo.arktsConfigFile, + stdLibPath: path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_PATH) + }; + moduleInfo.compileFileInfos.push(fileInfo); + return; + } + } + throw new Error("Entry File does not belong to any module in moduleInfos.") + }); + } + + private generateArkTSConfigForModules(): void { + const pathSection: Record = {}; + pathSection['std'] = [ + path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_STD_PATH) + ]; + pathSection['escompat'] = [ + path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_ESCOMPAT_PATH) + ]; + traverse(this.buildSdkPath, pathSection); + + this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { + pathSection[moduleInfo.packageName] = [ + path.resolve(moduleRootPath, moduleInfo.sourceRoots[0]) + ] + }); + + this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string)=> { + const dependenciesSection: string[] = []; + this.generateDependenciesSection(moduleInfo, dependenciesSection); + writeArkTSConfigFile(moduleInfo, pathSection, dependenciesSection); + }); + } + + private generateDependenciesSection(moduleInfo: ModuleInfo, dependenciesSection: string[]): void { + const depModules: Map = getDependentModules(moduleInfo, this.moduleInfos); + depModules.forEach((depModuleInfo: ModuleInfo) => { + if (depModuleInfo.isMainModule) { + return; + } + dependenciesSection.push(depModuleInfo.arktsConfigFile); + }); + } +} + +export { + mockBuildConfig, + MockArktsConfigBuilder +} \ No newline at end of file diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts new file mode 100644 index 000000000..bbc55431f --- /dev/null +++ b/arkui-plugins/test/utils/compile.ts @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { + arktsGlobal +} from "@koalaui/libarkts/build/lib/es2panda"; +import { + PluginDriver +} from "./plugin-driver"; +import { + PluginContext, + PluginExecutor, +} from "../../common/plugin-context"; +import { + EtsglobalRemover +} from "../../common/etsglobal-remover"; + +function restartCompilerUptoState( + state: arkts.Es2pandaContextState, + restart: boolean +): boolean { + try { + const ast: arkts.EtsScript | undefined = arkts.EtsScript.fromContext(); + if (!ast) { + return false; + } + + if (restart) { + const srcText = new EtsglobalRemover().visitor(ast).dumpSrc() + arktsGlobal.es2panda._DestroyContext(arktsGlobal.context) + arktsGlobal.compilerContext = arkts.Context.createFromString(srcText) + } + + arkts.proceedToState(state); + return true; + } catch (e) { + return false; + } +} + +function insertPlugin( + driver: PluginDriver, + plugin: PluginExecutor | undefined, + state: arkts.Es2pandaContextState +): boolean { + arkts.proceedToState(state); + const pluginContext: PluginContext = driver.getPluginContext(); + const ast: arkts.EtsScript | undefined = arkts.EtsScript.fromContext(); + + if (!ast) { + return false; + } + + if (plugin) { + pluginContext.setArkTSAst(ast); + pluginContext.setArkTSProgram(arktsGlobal.compilerContext.program); + plugin.handler.apply(pluginContext); + } + return true; +} + +export { + restartCompilerUptoState, + insertPlugin +} \ No newline at end of file diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts new file mode 100644 index 000000000..76bfdd523 --- /dev/null +++ b/arkui-plugins/test/utils/global.ts @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from "fs"; +import * as arkts from "@koalaui/libarkts"; +import { arktsGlobal } from "@koalaui/libarkts/build/lib/es2panda"; +import { CompileFileInfo } from "./artkts-config"; + +function initGlobal( + fileInfo: CompileFileInfo, + isDebug: boolean = true +): void { + const config = [ + '_', + '--extension', + 'sts', + '--arktsconfig', + fileInfo.arktsConfigFile, + '--output', + fileInfo.abcFilePath, + ]; + + if (isDebug) { + config.push('--debug-info'); + } + config.push(fileInfo.filePath); + + arktsGlobal.filePath = fileInfo.filePath; + resetConfig(config); + + const source: string = fs.readFileSync(fileInfo.filePath).toString(); + resetContext(source); +} + +function resetContext(source: string): void { + try { + arktsGlobal.context; + } catch (e) { + // Do nothing + } finally { + const context: arkts.Context = arkts.Context.createFromString(source); + arktsGlobal.compilerContext = context; + } +} + +function resetConfig(cmd: string[]): void { + try { + arktsGlobal.config; + destroyConfig(); + } catch (e) { + // Do nothing + } finally { + const arkTSConfig: arkts.Config = arkts.Config.create(cmd); + arktsGlobal.config = arkTSConfig.peer; + } +} + +function destroyContext(): void { + arktsGlobal.es2panda._DestroyContext(arktsGlobal.context); +} + +function destroyConfig(): void { + arkts.destroyConfig(arktsGlobal.config); +} + +function canProceedToState(state: arkts.Es2pandaContextState): boolean { + const stateToSkip: arkts.Es2pandaContextState[] = [ + arkts.Es2pandaContextState.ES2PANDA_STATE_SCOPE_INITED, + arkts.Es2pandaContextState.ES2PANDA_STATE_ASM_GENERATED, + arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR + ]; + + if (state in stateToSkip) { + return false; + } + + const currState = arktsGlobal.es2panda._ContextState(arktsGlobal.context); + return currState < state; +} + +export { + initGlobal, + resetContext, + resetConfig, + canProceedToState +}; \ No newline at end of file diff --git a/arkui-plugins/test/utils/parse-string.ts b/arkui-plugins/test/utils/parse-string.ts new file mode 100644 index 000000000..7bfce8533 --- /dev/null +++ b/arkui-plugins/test/utils/parse-string.ts @@ -0,0 +1,50 @@ +/* + * 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. + */ + +function parseDumpSrc(str: string): string { + let _str: string = filterSource(str); + _str = cleanCopyRight(_str); + _str = removeSpaceAndReturn(_str); + + return _str; +} + +function filterSource(text: string): string { + const filtered: string = text + .replaceAll(/%/g, "_") + .replaceAll(/#/g, "_") + .replaceAll("", "_cctor_") + + return filtered +} + +function cleanCopyRight(str: string): string { + const copyrightBlockRegex = /(?:\/\*.*Copyright \(c\) [- \d]+ Huawei Device Co\., Ltd\..*\*\/)/gs; + + return str.replace(copyrightBlockRegex, ''); +} + +function removeSpaceAndReturn(str: string): string { + const spaceAndReturnRegex = /^[\s\r]+/gm; + + return str.replace(spaceAndReturnRegex, ''); +} + +export { + parseDumpSrc, + filterSource, + cleanCopyRight, + removeSpaceAndReturn +} \ No newline at end of file diff --git a/arkui-plugins/test/utils/path-config.ts b/arkui-plugins/test/utils/path-config.ts new file mode 100644 index 000000000..1ba8e511d --- /dev/null +++ b/arkui-plugins/test/utils/path-config.ts @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from "fs"; +import * as path from "path"; + +export const ARKTS_CONFIG_FILE_PATH: string = 'arktsconfig.json'; +export const PANDA_SDK_PATH: string = 'node_modules/@panda/sdk'; +export const PANDA_SDK_STDLIB_PATH: string = 'lib'; +export const STDLIB_PATH: string = 'stdlib'; +export const STDLIB_STD_PATH: string = 'stdlib/std'; +export const STDLIB_ESCOMPAT_PATH: string = 'stdlib/escompat'; +export const RUNTIME_API_PATH: string = 'demo/runtime-api'; +export const MOCK_ENTRY_DIR_PATH: string = 'demo/mock'; +export const MOCK_ENTRY_FILE_NAME: string = 'entry.ets'; +export const MOCK_OUTPUT_CACHE_PATH: string = 'generated/cache'; +export const MOCK_OUTPUT_DIR_PATH: string = 'generated/abc'; +export const MOCK_OUTPUT_FILE_NAME: string = 'entry.abc'; +export const MOCK_LOCAL_SDK_DIR_PATH: string = 'local'; +export const ETS_SUFFIX: string = '.ets'; +export const ABC_SUFFIX: string = '.abc'; + +function getRootPath(): string { + return path.resolve(__dirname, ".."); +} + +function getPandaSDKPath(): string { + if (!process.env.ETS2PANDA_PATH) { + throw new Error("Environment Error: ets2panda path is not defined"); + } + + return path.resolve(process.env.ETS2PANDA_PATH); +} + +function changeFileExtension(file: string, targetExt: string, originExt = ''): string { + const currentExt: string = originExt.length === 0 ? path.extname(file) : originExt; + const fileWithoutExt: string = file.substring(0, file.lastIndexOf(currentExt)); + return fileWithoutExt + targetExt; +} + +function getFileName(file: string): string { + const fileWithExt: string = path.basename(file); + const currentExt: string = path.extname(file); + return fileWithExt.substring(0, fileWithExt.lastIndexOf(currentExt)); +} + +function ensurePathExists(filePath: string): void { + try { + const dirPath: string = path.dirname(filePath); + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { recursive: true }); + } + } catch (error) { + if (error instanceof Error) { + console.error(`Error: ${error.message}`); + } + } +} + +export { + getRootPath, + getPandaSDKPath, + changeFileExtension, + getFileName, + ensurePathExists +}; \ No newline at end of file diff --git a/arkui-plugins/test/utils/plugin-driver.ts b/arkui-plugins/test/utils/plugin-driver.ts new file mode 100644 index 000000000..62de8d96a --- /dev/null +++ b/arkui-plugins/test/utils/plugin-driver.ts @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { + isNumber +} from "./safe-types"; +import { + Plugins, + PluginContext, + PluginHandler, + PluginState , + PluginExecutor +} from "../../common/plugin-context"; + +export interface PluginDriver { + initPlugins(plugins: Plugins[]): void; + getSortedPlugins(state: arkts.Es2pandaContextState): PluginExecutor[] | undefined; + getPluginContext(): PluginContext; +} + +function toCamelCase(str: string): string { + return str + .split('_') + .map((word, index) => { + if (index === 0) { + return word; + } + return word.charAt(0).toUpperCase() + word.slice(1); + }) + .join(''); +} + +function stateName(value: arkts.Es2pandaContextState): PluginState { + return toCamelCase( + arkts.Es2pandaContextState[value] + .substring("ES2PANDA_STATE_".length) + .toLowerCase() + ) as PluginState; +} + +function selectPlugins(plugins: Plugins[], stage: PluginState): PluginExecutor[] { + const pre: PluginExecutor[] = []; + const normal: PluginExecutor[] = []; + const post: PluginExecutor[] = []; + + plugins + .filter(it => (stage in it)) + .forEach(it => { + const pluginName: string = it.name; + const handler: PluginHandler = it[stage]!; + const order: string | undefined = typeof handler === 'object' ? handler.order : undefined; + const rawPluginHook: PluginExecutor = { + name: pluginName, + handler: typeof handler === 'object' ? handler.handler : handler + }; + + if (order === 'pre') { + pre.push(rawPluginHook); + } else if (order === 'post') { + post.push(rawPluginHook); + } else { + normal.push(rawPluginHook); + } + }); + + return [...pre, ...normal, ...post]; +} + +class MockPluginDriver implements PluginDriver { + private sortedPlugins: Map; + private context: PluginContext; + + constructor() { + this.sortedPlugins = new Map(); + this.context = new PluginContext(); + } + + public initPlugins(plugins: Plugins[]): void { + const pluginsByState = new Map(); + + Object.values(arkts.Es2pandaContextState) + .filter(isNumber) + .forEach(it => { + const selected = selectPlugins(plugins, stateName(it)); + if (selected.length > 0) { + pluginsByState.set(it, selected); + } else { + pluginsByState.set(it, undefined); + } + }); + + this.sortedPlugins = pluginsByState; + } + + public getSortedPlugins(state: arkts.Es2pandaContextState): PluginExecutor[] | undefined { + return this.sortedPlugins.get(state); + } + + public getPluginContext(): PluginContext { + return this.context; + } +} + +export { + stateName, + MockPluginDriver +} \ No newline at end of file diff --git a/arkui-plugins/test/utils/plugin-tester.ts b/arkui-plugins/test/utils/plugin-tester.ts new file mode 100644 index 000000000..56c0c2065 --- /dev/null +++ b/arkui-plugins/test/utils/plugin-tester.ts @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { + ArktsConfigBuilder, + BuildConfig, + CompileFileInfo, + MockArktsConfigBuilder, + ModuleInfo +} from "./artkts-config"; +import { + MockPluginDriver, + PluginDriver, + stateName +} from "./plugin-driver"; +import { + isNumber +} from "./safe-types"; +import { + canProceedToState, + initGlobal +} from "./global"; +import { + insertPlugin, + restartCompilerUptoState +} from "./compile"; +import { + PluginExecutor, + Plugins, + PluginState +} from "../../common/plugin-context"; + +type TestParams = Parameters; + +type SkipFirstParam = T extends [unknown, ...infer Rest] ? Rest : never; + +type PluginTestHooks = { + [K in PluginState | `${PluginState}:${string}`]?: SkipFirstParam; +} + +type TestHooks = { + beforeAll?: Parameters; + afterAll?: Parameters; + beforeEach?: Parameters; + afterEach?: Parameters; +} + +export interface PluginTestContext { + script?: arkts.AstNode, + errors?: string[], + warnings?: string[] +} + +export interface PluginTesterOptions { + stopAfter: PluginState, + buildConfig?: BuildConfig +} + +class PluginTester { + private configBuilder: ArktsConfigBuilder; + private pluginDriver: PluginDriver; + private describe: string; + private cache?: PluginTestContext; + + constructor(describe: string, buildConfig?: BuildConfig) { + this.describe = describe; + this.configBuilder = new MockArktsConfigBuilder(buildConfig); + this.pluginDriver = new MockPluginDriver(); + } + + private loadPluginDriver(plugins: Plugins[]): void { + this.pluginDriver.initPlugins(plugins); + } + + private test( + key: PluginState | `${PluginState}:${string}`, + index: arkts.Es2pandaContextState, + testName: string, + pluginHooks: PluginTestHooks, + plugin?: PluginExecutor + ): void { + if (!this.cache) { + this.cache = {}; + } + if (index > arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) { + return; + } + if (canProceedToState(index)) { + // TODO: this is a bug from compiler. + if (index > arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) { + restartCompilerUptoState(index, true); + } + arkts.proceedToState(index); + } + if (plugin) { + insertPlugin(this.pluginDriver, plugin, index); + // TODO: add error/warning handling after plugin + this.cache.script = arkts.EtsScript.fromContext(); + } + const hook: SkipFirstParam | undefined = pluginHooks[key]; + if (!!hook) { + test(testName, hook[0]?.bind(this.cache), hook[1]); + } + } + + private proceedToState( + state: PluginState, + index: arkts.Es2pandaContextState, + testName: string, + pluginHooks: PluginTestHooks, + plugins?: PluginExecutor[] + ): void { + if (plugins && plugins.length > 0){ + plugins.forEach((plugin) => { + const pluginName: string = plugin.name; + const key: `${PluginState}:${string}` = `${state}:${pluginName}`; + this.test(key, index, `[${key}] ${testName}`, pluginHooks, plugin); + }) + } + this.test(state, index, `[${state}] ${testName}`, pluginHooks); + } + + private singleFileCompile( + fileInfo: CompileFileInfo, + moduleInfo: ModuleInfo, + testName: string, + pluginHooks: PluginTestHooks, + stopAfter: PluginState + ): void { + let shouldStop: boolean = false; + + initGlobal(fileInfo, this.configBuilder.isDebug); + + Object.values(arkts.Es2pandaContextState) + .filter(isNumber) + .forEach(it => { + if (shouldStop) return; + const state: PluginState = stateName(it); + const plugins: PluginExecutor[] | undefined = this.pluginDriver.getSortedPlugins(it); + this.proceedToState( + state, + it, + `${moduleInfo.packageName} - ${fileInfo.fileName}: ${testName}`, + pluginHooks, + plugins + ) + shouldStop = state === stopAfter; + }); + } + + private traverseFile( + testName: string, + pluginHooks: PluginTestHooks, + stopAfter: PluginState + ): void { + this.configBuilder.moduleInfos.forEach((moduleInfo) => { + moduleInfo.compileFileInfos.forEach((fileInfo) => { + this.singleFileCompile(fileInfo, moduleInfo, testName, pluginHooks, stopAfter); + }); + }); + } + + run( + testName: string, + plugins: Plugins[], + pluginHooks: PluginTestHooks, + options: PluginTesterOptions, + testHooks?: TestHooks + ): void { + if (!!options.buildConfig) { + this.configBuilder = new MockArktsConfigBuilder(options.buildConfig); + } + + this.loadPluginDriver(plugins); + + describe(this.describe, () => { + if (testHooks?.beforeAll) { + beforeAll(...testHooks.beforeAll); + } + if (testHooks?.afterAll) { + afterAll(...testHooks.afterAll); + } + if (testHooks?.beforeEach) { + beforeEach(...testHooks.beforeEach); + } + if (testHooks?.afterEach) { + afterEach(...testHooks.afterEach); + } + this.traverseFile(testName, pluginHooks, options.stopAfter); + }); + } +} + +export { + PluginTester +} diff --git a/arkui-plugins/test/utils/safe-types.ts b/arkui-plugins/test/utils/safe-types.ts new file mode 100644 index 000000000..5802b5b2e --- /dev/null +++ b/arkui-plugins/test/utils/safe-types.ts @@ -0,0 +1,22 @@ +/* + * 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. + */ + +function isNumber(value: any): value is number { + return typeof value === `number`; +} + +export { + isNumber +} \ No newline at end of file diff --git a/arkui-plugins/tsconfig.build.json b/arkui-plugins/tsconfig.build.json new file mode 100644 index 000000000..7efa8486d --- /dev/null +++ b/arkui-plugins/tsconfig.build.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "target": "es2018", + "lib": ["ESNext", "ESNext.WeakRef", "DOM"], + "module": "CommonJS", + "rootDir": ".", + "baseUrl": ".", + "outDir": "./lib", + "moduleResolution": "node", + "incremental": false, + "declarationMap": false, + "sourceMap": false, + "declaration": false, + "noEmitOnError": true, + "strict": true, + "skipLibCheck": true, + "removeComments": false + }, + "include": [ + "./common/**/*.ts", + "./memo-plugins/**/*.ts", + "./ui-plugins/**/*.ts", + "./interop-plugins/**/*.ts", + ], + "exclude": [ + "./test/**" + ] +} diff --git a/arkui-plugins/tsconfig.json b/arkui-plugins/tsconfig.json new file mode 100644 index 000000000..eab872848 --- /dev/null +++ b/arkui-plugins/tsconfig.json @@ -0,0 +1,33 @@ +{ + "compilerOptions": { + "target": "es2018", + "lib": ["ESNext", "ESNext.WeakRef", "DOM"], + "module": "CommonJS", + "rootDir": ".", + "baseUrl": ".", + "outDir": "./lib", + "moduleResolution": "node", + "composite": true, + "incremental": true, + "declarationMap": true, + "sourceMap": true, + "declaration": true, + "noEmitOnError": true, + "strict": true, + "skipLibCheck": true, + "removeComments": false + }, + "include": [ + "./common/**/*.ts", + "./memo-plugins/**/*.ts", + "./ui-plugins/**/*.ts", + "./interop-plugins/**/*.ts", + "./path.ts", + "./test/ut/**/*.ts", + "./test/utils/**/*.ts" + ], + "exclude": [ + "./test/demo/", + "./test/local/" + ] +} diff --git a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts new file mode 100644 index 000000000..dbe3ce61f --- /dev/null +++ b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts @@ -0,0 +1,566 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { AbstractVisitor } from "../common/abstract-visitor"; +import { + BuilderLambdaNames, + findBuilderLambdaDecl, + findBuilderLambdaInCall, + isBuilderLambdaAnnotation, + isBuilderLambdaCall +} from "./utils"; +import { + annotation, + filterDefined, + removeAnnotationByName, + backingField +} from "../common/arkts-utils"; +import { DecoratorNames } from "./property-translators/utils"; + +function createStyleArgInBuilderLambda( + lambdaBody: arkts.Expression | undefined, + typeNode: arkts.TypeNode | undefined, +): arkts.UndefinedLiteral | arkts.ArrowFunctionExpression { + if (!lambdaBody) { + return arkts.factory.createUndefinedLiteral(); + } + + const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, + typeNode + ), + undefined + ); + + const body: arkts.BlockStatement = arkts.factory.createBlock([ + arkts.factory.createExpressionStatement(lambdaBody), + arkts.factory.createReturnStatement() + ]); + + const func = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [styleLambdaParam], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ) + + return arkts.factory.createArrowFunction(func); +} + +function createStyleArgInBuilderLambdaDecl( + typeNode: arkts.TypeNode | undefined, + isFunctionCall: boolean +): arkts.ETSParameterExpression { + const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, + typeNode + ), + undefined + ); + const funcType = arkts.factory.createFunctionType( + arkts.FunctionSignature.createFunctionSignature( + undefined, + [styleLambdaParam], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + ) + + let parameter: arkts.ETSParameterExpression; + if (isFunctionCall) { + parameter = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + BuilderLambdaNames.STYLE_PARAM_NAME, + funcType + ), + undefined + ).setOptional(true); + } else { + const optionalFuncType = arkts.factory.createUnionType([ + funcType, + arkts.factory.createETSUndefinedType() + ]); + parameter = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + BuilderLambdaNames.STYLE_PARAM_NAME, + optionalFuncType + ), + undefined + ); + } + parameter.annotations = [annotation("memo")]; + return parameter; +} + +function updateFactoryArgInBuilderLambda( + arg: arkts.Expression | undefined, + typeNode: arkts.TypeNode | undefined +): arkts.ArrowFunctionExpression | undefined { + if (!arg || !arkts.isArrowFunctionExpression(arg)) { + throw new Error("first argument in $_instantiate is undefined"); + }; + + const func: arkts.ScriptFunction = arg.scriptFunction; + const updateFunc = arkts.factory.updateScriptFunction( + func, + func.body, + arkts.FunctionSignature.createFunctionSignature( + func.typeParams, + func.params, + typeNode, + false + ), + func.flags, + func.modifiers + ) + return arkts.factory.updateArrowFunction( + arg, + updateFunc + ); +} + +function updateContentBodyInBuilderLambda( + statement: arkts.Statement, + isExternal?: boolean +): arkts.Statement { + if ( + arkts.isExpressionStatement(statement) + && arkts.isCallExpression(statement.expression) + && isBuilderLambda(statement.expression, isExternal) + ) { + return arkts.factory.updateExpressionStatement( + statement, + transformBuilderLambda(statement.expression) + ); + } + return statement; +} + +/** + * Used in finding "XXX" in BuilderLambda("XXX") + * @deprecated + */ +function builderLambdaArgumentName(annotation: arkts.AnnotationUsage): string | undefined { + if (!isBuilderLambdaAnnotation(annotation)) return undefined; + + const property = annotation.properties.at(0); + if (!property || !arkts.isClassProperty(property)) return undefined; + if (!property.value || !arkts.isStringLiteral(property.value)) return undefined; + + return property.value.str; +} + +function builderLambdaFunctionName(node: arkts.CallExpression): string | undefined { + const annotation = findBuilderLambdaInCall(node); + if (!annotation) return undefined; + + if (arkts.isIdentifier(node.expression)) { + return node.expression.name; + } + if ( + arkts.isMemberExpression(node.expression) + && arkts.isIdentifier(node.expression.property) + && node.expression.property.name === BuilderLambdaNames.ORIGIN_METHOD_NAME + ) { + return BuilderLambdaNames.TRANSFORM_METHOD_NAME + } + return undefined; +} + +function replaceBuilderLambdaDeclMethodName(name: string | undefined): string | undefined { + if (!!name && name === BuilderLambdaNames.ORIGIN_METHOD_NAME) { + return BuilderLambdaNames.TRANSFORM_METHOD_NAME + } + return undefined; +} + +function callIsGoodForBuilderLambda(leaf: arkts.CallExpression): boolean { + const node = leaf.expression; + return arkts.isIdentifier(node) || arkts.isMemberExpression(node); +} + +function builderLambdaTypeName(leaf: arkts.CallExpression): string | undefined{ + if (!callIsGoodForBuilderLambda(leaf)) return undefined; + const node = leaf.expression; + let name: string | undefined; + if (arkts.isIdentifier(node)) { + name = node.name; + } + if (arkts.isMemberExpression(node) && arkts.isIdentifier(node.object)) { + name = node.object.name; + } + return name; +} + +function builderLambdaType( + leaf: arkts.CallExpression, +): arkts.TypeNode | undefined { + const name: string | undefined = builderLambdaTypeName(leaf); + if(!name) return undefined; + + // TODO: it should be the return type of the function annotated with the @BuilderLambda + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(`${name}Attribute`) + ) + ); +} + +function builderLambdaMethodDeclType(method: arkts.MethodDefinition): arkts.TypeNode | undefined { + if (!method || !method.scriptFunction) return undefined; + return method.scriptFunction.returnTypeAnnotation; +} + +function isBuilderLambdaFunctionCall(decl: arkts.AstNode | undefined): boolean { + if (!decl) return false; + if (arkts.isMethodDefinition(decl)) { + return ( + decl.name.name != BuilderLambdaNames.ORIGIN_METHOD_NAME + && decl.name.name != BuilderLambdaNames.TRANSFORM_METHOD_NAME + ); + } + return false; +} + +function findBuilderLambdaDeclInfo( + node: arkts.CallExpression +): BuilderLambdaDeclInfo | undefined { + const decl = findBuilderLambdaDecl(node); + if (!decl) return undefined; + + if (arkts.isMethodDefinition(decl)) { + const params = decl.scriptFunction.params.map((p) => p.clone()); + const isFunctionCall = isBuilderLambdaFunctionCall(decl); + return { isFunctionCall, params }; + } + + return undefined; +} + +function builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { + if (!callIsGoodForBuilderLambda(leaf)) return undefined; + const node = leaf.expression; + + const funcName = builderLambdaFunctionName(leaf); + if (!funcName) return undefined; + + if (arkts.isIdentifier(node)) { + return arkts.factory.createIdentifier(funcName); + } + if (arkts.isMemberExpression(node)) { + return arkts.factory.createMemberExpression( + node.object, + arkts.factory.createIdentifier(funcName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + node.computed, + node.optional + ) + } + return undefined; +} + +function createOrUpdateArgInBuilderLambda( + arg: arkts.Expression | undefined, + isExternal?: boolean, + typeName?: string, + fallback?: arkts.AstNode +) { + if (!arg) { + return fallback ?? arkts.factory.createUndefinedLiteral(); + } + if (arkts.isArrowFunctionExpression(arg)) { + const func: arkts.ScriptFunction = arg.scriptFunction; + const updateFunc = arkts.factory.updateScriptFunction( + func, + !!func.body && arkts.isBlockStatement(func.body) ? arkts.factory.updateBlock( + func.body, + func.body.statements.map( + (st) => updateContentBodyInBuilderLambda(st, isExternal) + ) + ) : undefined, + arkts.FunctionSignature.createFunctionSignature( + func.typeParams, + func.params, + func.returnTypeAnnotation, + false + ), + func.flags, + func.modifiers + ) + + return arkts.factory.updateArrowFunction( + arg, + updateFunc + ); + } + + const isReusable: boolean = typeName + ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable + : false; + + if (arkts.isTSAsExpression(arg) && arg.expr && arkts.isObjectExpression(arg.expr)) { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); + const properties = arg.expr.properties as arkts.Property[]; + properties.forEach((prop, index) => { + if ( + prop.key && + prop.value && + arkts.isIdentifier(prop.key) && + arkts.isMemberExpression(prop.value) && + arkts.isThisExpression(prop.value.object) && + arkts.isIdentifier(prop.value.property) + ) { + const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; + if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { + properties[index] = arkts.Property.updateProperty( + prop, + arkts.factory.createIdentifier(backingField(prop.key.name)), + arkts.factory.updateMemberExpression( + prop.value, + prop.value.object, + arkts.factory.createIdentifier(backingField(prop.value.property.name)), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + ); + } + } + }); + const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( + arg.expr, + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + properties, + false, + ); + return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); + } + return arg; +} + +function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { + let instanceCalls: arkts.CallExpression[] = []; + let leaf: arkts.CallExpression = node; + + while (true + && arkts.isMemberExpression(leaf.expression) + && arkts.isIdentifier(leaf.expression.property) + && arkts.isCallExpression(leaf.expression.object) + ) { + instanceCalls.push( + arkts.factory.createCallExpression( + leaf.expression.property, + undefined, + leaf.arguments + ) + ); + leaf = leaf.expression.object; + } + + const replace: arkts.Identifier | arkts.MemberExpression | undefined + = builderLambdaReplace(leaf); + const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(leaf); + if (!replace || !declInfo) return node; + + const { params } = declInfo; + + let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; + if (instanceCalls.length > 0) { + instanceCalls = instanceCalls.reverse(); + lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); + instanceCalls.forEach((call)=> { + if (!arkts.isIdentifier(call.expression)) { + throw new Error('call expression should be identifier'); + } + lambdaBody = arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + lambdaBody!, + call.expression, + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + call.arguments + ); + }); + } + + + const typeNode: arkts.TypeNode | undefined = builderLambdaType(leaf); + const typeName: string | undefined = builderLambdaTypeName(leaf); + const args: (arkts.AstNode | undefined)[] = [ + createStyleArgInBuilderLambda(lambdaBody, typeNode) + ] + let index = 0; + while (index < params.length) { + const isReusable: boolean = typeName + ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable + : false; + if (isReusable && index == params.length - 1) { + const reuseId = arkts.factory.createStringLiteral(typeName!); + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName, reuseId)); + } else { + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName)); + } + index++; + } + + return arkts.factory.updateCallExpression( + node, + replace, + undefined, + filterDefined(args) + ); +} + +function transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { + const func: arkts.ScriptFunction = node.scriptFunction; + const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); + const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); + const updateFunc = arkts.factory.updateScriptFunction( + func, + func.body, + arkts.FunctionSignature.createFunctionSignature( + func.typeParams, + [ + createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall), + ...func.params + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + func.flags, + func.modifiers + ).setAnnotations( + removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME) + ); + + return arkts.factory.updateMethodDefinition( + node, + node.kind, + arkts.factory.updateIdentifier( + node.name, + replaceBuilderLambdaDeclMethodName(node.name.name) ?? node.name.name + ), + arkts.factory.createFunctionExpression(updateFunc), + node.modifiers, + false // TODO: how do I get it? + ); +} + +function isBuilderLambda(node: arkts.AstNode, isExternal?: boolean): boolean { + const builderLambdaCall: arkts.AstNode | undefined = getDeclForBuilderLambda(node); + return !!builderLambdaCall; +} + +function isBuilderLambdaMethodDecl(node: arkts.AstNode, isExternal?: boolean): boolean { + const builderLambdaMethodDecl: arkts.AstNode | undefined = getDeclForBuilderLambdaMethodDecl(node); + return !!builderLambdaMethodDecl; +} + +function getDeclForBuilderLambdaMethodDecl(node: arkts.AstNode, isExternal?: boolean): arkts.AstNode | undefined { + if (!node || !arkts.isMethodDefinition(node)) return undefined; + + const isBuilderLambda: boolean = !!node.name && isBuilderLambdaCall(node.name); + const isMethodDecl: boolean = !!node.scriptFunction + && arkts.hasModifierFlag(node.scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE); + if ( + isBuilderLambda + && isMethodDecl + ) { + return node; + } + return undefined; +} + +function getDeclForBuilderLambda(node: arkts.AstNode, isExternal?: boolean): arkts.AstNode | undefined { + if (!node || !arkts.isCallExpression(node)) return undefined; + + let currNode: arkts.AstNode = node; + while ( + !!currNode + && arkts.isCallExpression(currNode) + && !!currNode.expression + && arkts.isMemberExpression(currNode.expression) + ) { + const _node: arkts.MemberExpression = currNode.expression; + + if ( + !!_node.property + && arkts.isIdentifier(_node.property) + && isBuilderLambdaCall(_node.property) + ) { + return node; + } + + if ( + !!_node.object + && arkts.isCallExpression(_node.object) + && isBuilderLambdaCall(_node.object) + ) { + return node; + } + + currNode = _node.object; + } + + if (isBuilderLambdaCall(node)) { + return node; + } + return undefined; +} + +type BuilderLambdaDeclInfo = { + isFunctionCall: boolean, // isFunctionCall means it is from $_instantiate. + params: readonly arkts.Expression[] +} + +export class BuilderLambdaTransformer extends AbstractVisitor { + visitEachChild(node: arkts.AstNode): arkts.AstNode { + if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + return node; + } + if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + return node; + } + + return super.visitEachChild(node); + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + const node = this.visitEachChild(beforeChildren) + + if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + const lambda = transformBuilderLambda(node, this.isExternal); + return lambda; + } + if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + const lambda = transformBuilderLambdaMethodDecl(node); + return lambda; + } + + return node; + } +} diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts new file mode 100644 index 000000000..ef8a660fc --- /dev/null +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -0,0 +1,407 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { getInteropPath } from "../path"; +const interop = require(getInteropPath()) +const nullptr = interop.nullptr +import { + AbstractVisitor, + VisitorOptions +} from "../common/abstract-visitor"; +import { + CustomComponentNames, + getCustomComponentOptionsName, + createOptionalClassProperty, + findLocalImport +} from "./utils"; +import { + isAnnotation, + updateStructMetadata, + backingField, + expectName, + annotation +} from "../common/arkts-utils"; +import { + EntryWrapperNames, + findEntryWithStorageInClassAnnotations +} from "./entry-translators/utils"; +import { + factory as entryFactory +} from "./entry-translators/factory"; +import { + hasDecorator, + DecoratorNames, + getStateManagementType, + collectPropertyDecorators +} from "./property-translators/utils"; +import { + factory +} from "./ui-factory"; + +export interface ComponentTransformerOptions extends VisitorOptions { + arkui?: string +} + +type ScopeInfo = { + name: string, + isEntry?: boolean, + isComponent?: boolean, + isReusable?: boolean +} + +interface ComponentContext { + structMembers: Map, + reusableComps: Map +} + +export class ComponentTransformer extends AbstractVisitor { + private scopeInfos: ScopeInfo[] = []; + private componentInterfaceCollection: arkts.TSInterfaceDeclaration[] = []; + private entryNames: string[] = []; + private reusableNames: string[] = []; + private readonly arkui?: string; + private context: ComponentContext = { structMembers: new Map(), reusableComps: new Map()}; + private isCustomComponentImported: boolean = false; + private isEntryPointImported: boolean = false; + + constructor(options?: ComponentTransformerOptions) { + const _options: ComponentTransformerOptions = options ?? {}; + super(_options); + this.arkui = _options.arkui; + } + + reset(): void { + super.reset(); + this.scopeInfos = []; + this.componentInterfaceCollection = []; + this.entryNames = []; + this.reusableNames = []; + this.context = { structMembers: new Map(), reusableComps: new Map() }; + this.isCustomComponentImported = false; + this.isEntryPointImported = false; + } + + enter(node: arkts.AstNode) { + if (arkts.isStructDeclaration(node) && !!node.definition.ident) { + const scopeInfo: ScopeInfo = { name: node.definition.ident.name }; + node.definition.annotations.forEach((anno) => { + scopeInfo.isEntry ||= isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION_NAME); + scopeInfo.isComponent ||= isAnnotation(anno, CustomComponentNames.COMPONENT_ANNOTATION_NAME); + scopeInfo.isReusable ||= isAnnotation(anno, CustomComponentNames.RESUABLE_ANNOTATION_NAME); + }); + this.scopeInfos.push(scopeInfo); + } + if (arkts.isETSImportDeclaration(node) && !this.isCustomComponentImported) { + this.isCustomComponentImported = !!findLocalImport( + node, + CustomComponentNames.COMPONENT_DEFAULT_IMPORT, + CustomComponentNames.COMPONENT_CLASS_NAME + ); + } + if (arkts.isETSImportDeclaration(node) && !this.isEntryPointImported) { + this.isEntryPointImported = !!findLocalImport( + node, + EntryWrapperNames.ENTRY_DEFAULT_IMPORT, + EntryWrapperNames.ENTRY_POINT_CLASS_NAME + ); + } + } + + exit(node: arkts.AstNode) { + if (arkts.isStructDeclaration(node) || arkts.isClassDeclaration(node)) { + if (!node.definition || !node.definition.ident || this.scopeInfos.length === 0) return; + if (this.scopeInfos[this.scopeInfos.length - 1]?.name === node.definition.ident.name) { + this.scopeInfos.pop(); + } + } + } + + isComponentStruct(): boolean { + if (this.scopeInfos.length === 0) return false; + const scopeInfo: ScopeInfo = this.scopeInfos[this.scopeInfos.length - 1]; + return !!scopeInfo.isComponent; + } + + createImportDeclaration(): void { + const source: arkts.StringLiteral = arkts.factory.create1StringLiteral( + this.arkui ?? CustomComponentNames.COMPONENT_DEFAULT_IMPORT + ); + const imported: arkts.Identifier = arkts.factory.createIdentifier( + CustomComponentNames.COMPONENT_CLASS_NAME + ); + const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + source, + [ + arkts.factory.createImportSpecifier( + imported, + imported + ) + ], + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE + ) + // Insert this import at the top of the script's statements. + arkts.importDeclarationInsert(importDecl); + return; + } + + processEtsScript(node: arkts.EtsScript): arkts.EtsScript { + if ( + this.isExternal + && this.componentInterfaceCollection.length === 0 + && this.entryNames.length === 0 + ) { + return node; + } + let updateStatements: arkts.AstNode[] = []; + if (this.componentInterfaceCollection.length > 0) { + if (!this.isCustomComponentImported) this.createImportDeclaration(); + updateStatements.push(...this.componentInterfaceCollection); + } + + if (this.entryNames.length > 0) { + if (!this.isEntryPointImported) entryFactory.createAndInsertEntryPointImport(); + // TODO: normally, we should only have at most one @Entry component in a single file. + // probably need to handle error message here. + updateStatements.push( + ...this.entryNames.map(entryFactory.generateEntryWrapper) + ); + } + if (updateStatements.length > 0) { + return arkts.factory.updateEtsScript( + node, + [ + ...node.statements, + ...updateStatements, + ] + ) + } + return node; + } + + processReusableComponent(className: string) { + const first = arkts.factory.createClassProperty( + arkts.factory.createIdentifier("__class_name"), + undefined, + arkts.factory.createETSStringLiteralType(className), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + false + ) + const second = arkts.factory.createClassProperty( + arkts.factory.createIdentifier("__reuseId"), + undefined, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier("string") + ) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + false + ) + this.context.reusableComps.set(className, [first, second]) + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); + currentStructInfo.isReusable = true; + arkts.GlobalInfo.getInfoInstance().setStructInfo(className, currentStructInfo); + } + + createStaticMethod(definition: arkts.ClassDefinition):arkts.MethodDefinition { + const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + CustomComponentNames.OPTIONS, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(getCustomComponentOptionsName(definition.ident!.name)) + ) + ) + ), + undefined + ); + + const script = arkts.factory.createScriptFunction( + arkts.factory.createBlock([arkts.factory.createReturnStatement()]), + arkts.FunctionSignature.createFunctionSignature( + undefined, + [param], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + ) + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + arkts.factory.createIdentifier(CustomComponentNames.BUILDCOMPATIBLENODE), + arkts.factory.createFunctionExpression(script), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + false + ) + } + + processComponent(node: arkts.ClassDeclaration | arkts.StructDeclaration): arkts.ClassDeclaration | arkts.StructDeclaration { + const scopeInfo = this.scopeInfos[this.scopeInfos.length - 1]; + const className = node.definition?.ident?.name; + if (!className || scopeInfo?.name !== className) { + return node; + } + + arkts.GlobalInfo.getInfoInstance().add(className); + + if (arkts.isStructDeclaration(node)) { + this.collectComponentMembers(node, className); + } + + if(scopeInfo.isReusable){ + this.processReusableComponent(className); + } + + this.componentInterfaceCollection.push(this.generateComponentInterface(className, node.modifiers)); + + const definition: arkts.ClassDefinition = node.definition; + const newDefinitionBody: arkts.AstNode[] = []; + if (scopeInfo.isEntry) { + this.entryNames.push(className); + const entryWithStorage: arkts.ClassProperty | undefined = + findEntryWithStorageInClassAnnotations(definition); + if (!!entryWithStorage) { + newDefinitionBody.push(entryFactory.createEntryLocalStorageInClass(entryWithStorage)); + } + } + + const staticMethonBody: arkts.AstNode[] = []; + const hasExportFlag = (node.modifiers & arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT) === arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; + if (hasExportFlag) { + const buildCompatibleNode:arkts.MethodDefinition = this.createStaticMethod(definition); + if(!!buildCompatibleNode) { + staticMethonBody.push(buildCompatibleNode); + } + } + + const newDefinition = arkts.factory.updateClassDefinition( + definition, + definition.ident, + undefined, + undefined, // superTypeParams doen't work + definition.implements, + undefined, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + scopeInfo.isReusable ? arkts.factory.createIdentifier('ArkReusableStructBase'): + arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_CLASS_NAME), + arkts.factory.createTSTypeParameterInstantiation( + [ + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(className) + ) + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier( + `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${className}` + ) + ) + ), + ] + ) + ) + ), + [...newDefinitionBody, ...definition.body, ...staticMethonBody], + definition.modifiers, + arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL + ) + + if (arkts.isStructDeclaration(node)) { + const _node = arkts.factory.createClassDeclaration(newDefinition); + _node.modifiers = node.modifiers; + return _node; + } else { + return arkts.factory.updateClassDeclaration( + node, + newDefinition + ) + } + } + + generateComponentInterface(name: string, modifiers: number): arkts.TSInterfaceDeclaration { + const interfaceNode = arkts.factory.createInterfaceDeclaration( + [], + arkts.factory.createIdentifier( + getCustomComponentOptionsName(name) + ), + nullptr, // TODO: wtf + arkts.factory.createInterfaceBody( + [ + ...(this.context.reusableComps.get(name) || []), + ...(this.context.structMembers.get(name) || []) + ] + ), + false, + false + ); + interfaceNode.modifiers = modifiers; + return interfaceNode; + } + + collectComponentMembers(node: arkts.StructDeclaration, className: string): void { + const structInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); + if (!this.context.structMembers.has(className)) { + this.context.structMembers.set(className, []); + } + node.definition.body.map(it => { + if (arkts.isClassProperty(it)) { + this.context.structMembers.get(className)!.push( + ...this.createInterfaceInnerMember(it, structInfo) + ); + } + }); + arkts.GlobalInfo.getInfoInstance().setStructInfo(className, structInfo); + } + + createInterfaceInnerMember(member: arkts.ClassProperty, structInfo: arkts.StructInfo): arkts.ClassProperty[] { + const originalName: string = expectName(member.key); + const newName: string = backingField(originalName); + + const properties = collectPropertyDecorators(member); + const hasStateManagementType = properties.length > 0; + updateStructMetadata(structInfo, originalName, properties, member.modifiers, hasStateManagementType); + + const originMember: arkts.ClassProperty = createOptionalClassProperty(originalName, member, + '', arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC); + if (member.annotations.length > 0 && !hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { + const newMember: arkts.ClassProperty = createOptionalClassProperty(newName, member, + getStateManagementType(member), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC); + return [originMember, newMember]; + } + if (hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { + originMember.setAnnotations([annotation("memo")]); + } + return [originMember]; + } + + visitor(node: arkts.AstNode): arkts.AstNode { + this.enter(node); + const newNode = this.visitEachChild(node) + if (arkts.isEtsScript(newNode)) { + return this.processEtsScript(newNode); + } + if (arkts.isStructDeclaration(newNode) && this.isComponentStruct()) { + const updateNode = this.processComponent(newNode); + this.exit(newNode); + return updateNode; + } + return newNode + } +} diff --git a/arkui-plugins/ui-plugins/entry-translators/entry-transformer.ts b/arkui-plugins/ui-plugins/entry-translators/entry-transformer.ts new file mode 100644 index 000000000..bb936a3e3 --- /dev/null +++ b/arkui-plugins/ui-plugins/entry-translators/entry-transformer.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +import { AbstractVisitor } from "../../common/abstract-visitor"; +import { isEntryWrapperClass } from "./utils"; +import { factory } from "./factory"; + +export class EntryTransformer extends AbstractVisitor { + visitor(node: arkts.AstNode): arkts.AstNode { + const newNode = this.visitEachChild(node); + if (isEntryWrapperClass(newNode)) { + return factory.registerEntryFunction(newNode); + } + return newNode; + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts new file mode 100644 index 000000000..99404e7b1 --- /dev/null +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { getInteropPath } from "../../path" +const interop = require(getInteropPath()) +const nullptr = interop.nullptr +import { EntryWrapperNames } from "./utils"; +import { annotation } from "../../common/arkts-utils"; +import { factory as uiFactory } from "../ui-factory"; + +export class factory { + /** + * insert an 'entry' method to an entry wrapper class. + * + * @param node entry wrapper class declaration node. + */ + static registerEntryFunction(node: arkts.ClassDeclaration): arkts.AstNode { + const definition: arkts.ClassDefinition | undefined = node.definition; + const classname = node?.definition?.ident?.name + if (!definition || !classname) { + throw new Error("Node definition is undefined"); + } + const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( + definition, + definition.ident, + definition.typeParams, + definition.superTypeParams, + definition.implements, + undefined, + definition.super, + [...definition.body, factory.generateEntryFunction(classname)], + definition.modifiers, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); + return arkts.factory.updateClassDeclaration(node, updateClassDef); + } + + /** + * insert an 'entry' property to an entry wrapper class. + * + * @param node entry wrapper class declaration node. + * @deprecated + */ + static registerEntryProperty(node: arkts.ClassDeclaration): arkts.AstNode { + const definition: arkts.ClassDefinition | undefined = node.definition; + const classname = node?.definition?.ident?.name + if (!definition || !classname) { + throw new Error("Node definition is undefined"); + } + const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( + definition, + definition.ident, + definition.typeParams, + definition.superTypeParams, + definition.implements, + undefined, + definition.super, + [...definition.body, factory.generateEntryProperty(classname)], + definition.modifiers, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); + return arkts.factory.updateClassDeclaration(node, updateClassDef); + } + + /** + * create `entry(): void { (); }` class method for the entry wrapper class, + * which calls the struct within the method. + * + * @param name class/struct name that has `@Entry` annotation. + */ + static generateEntryFunction(name: string): arkts.MethodDefinition { + const exp = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createIdentifier(name), + undefined, + [arkts.factory.createUndefinedLiteral()], // TODO: Add this undefined later + ) + ); + const key: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_FUNC); + const block = arkts.factory.createBlock([exp]); + const entryScript = arkts.factory.createScriptFunction( + block, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ).setIdent(key); + + const def = arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + key, + arkts.factory.createFunctionExpression(entryScript), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + + return def; + } + + /** + * create `entry = (): void => { (); }` class property for the entry wrapper class, + * which calls the struct within the arrow function. + * + * @param name class/struct name that has `@Entry` annotation. + * @deprecated + */ + static generateEntryProperty(name: string): arkts.ClassProperty { + const exp = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createIdentifier(name), + undefined, + [arkts.factory.createUndefinedLiteral()], // TODO: Add this undefined later + ) + ); + const key: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_FUNC); + const block: arkts.BlockStatement = arkts.factory.createBlock([exp]); + const signature: arkts.FunctionSignature = arkts.FunctionSignature.createFunctionSignature( + undefined, + [], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ); + const entryScript: arkts.ScriptFunction = arkts.factory.createScriptFunction( + block, + signature, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ).setIdent(key); + + const def = arkts.factory.createClassProperty( + key, + arkts.factory.createArrowFunction(entryScript), + arkts.factory.createFunctionType( + signature, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + + return def; + } + + /** + * create `__EntryWrapper_Entry` entry wrapper class that contains an 'entry' method that + * calls the struct within the method. + * + * @param name class/struct name that has `@Entry` annotation. + */ + static generateEntryWrapper(name: string): arkts.ClassDeclaration { + const definition: arkts.ClassDefinition = arkts.factory.createClassDefinition( + arkts.factory.createIdentifier(EntryWrapperNames.WRAPPER_CLASS_NAME), + undefined, + undefined, + [], + undefined, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME) + ) + ), + [factory.generateEntryFunction(name)], + arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_CLASS_DECL + | arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_DECLARATION + | arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_ID_REQUIRED, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + const newClass = arkts.factory.createClassDeclaration(definition); + newClass.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE; + return newClass; + } + + /** + * add `@memo` to all class methods that are named 'entry'. + * + * @param node class declaration node + */ + static addMemoToEntryWrapperClassMethods(node: arkts.ClassDeclaration): void { + node.definition?.body.forEach(member => { + if ( + arkts.isMethodDefinition(member) + && !!member.scriptFunction.id + && member.scriptFunction.id.name == EntryWrapperNames.ENTRY_FUNC + ) { + member.scriptFunction.setAnnotations([annotation("memo")]); + } + }); + } + + /** + * add `@memo` to the class property's value (expecting an arrow function), where the property is named 'entry'. + * + * @param node class declaration node + * @deprecated + */ + static addMemoToEntryWrapperPropertyValue(node: arkts.ClassDeclaration): void { + node.definition?.body.forEach(member => { + if ( + arkts.isClassProperty(member) + && !!member.value + && arkts.isArrowFunctionExpression(member.value) + && !!member.key + && arkts.isIdentifier(member.key) + && member.key.name == EntryWrapperNames.ENTRY_FUNC + ) { + member.setAnnotations([annotation("memo")]); + } + }); + } + + /** + * create `private _entry_local_storage_ = ;` class property + * from `{storage: ""}` in `@Entry`'s properties. + * + * @param annotation `@Entry` annotation. + */ + static createEntryLocalStorageInClass(property: arkts.ClassProperty) { + const value = property.value as arkts.StringLiteral; + return arkts.factory.createClassProperty( + arkts.factory.createIdentifier( + EntryWrapperNames.ENTRY_STORAGE_LOCAL_STORAGE_PROPERTY_NAME + ), + arkts.factory.createIdentifier(value.str), + undefined, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + } + + /** + * create and insert `import { EntryPoint as EntryPoint } from "@ohos.arkui.UserView";` + * to the top of script's statements. + */ + static createAndInsertEntryPointImport() { + const source: arkts.StringLiteral = arkts.factory.create1StringLiteral( + EntryWrapperNames.ENTRY_DEFAULT_IMPORT + ); + const imported: arkts.Identifier = arkts.factory.createIdentifier( + EntryWrapperNames.ENTRY_POINT_CLASS_NAME + ); + const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + source, + [ + arkts.factory.createImportSpecifier( + imported, + imported + ) + ], + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE + ) + // Insert this import at the top of the script's statements. + arkts.importDeclarationInsert(importDecl); + return; + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/entry-translators/utils.ts b/arkui-plugins/ui-plugins/entry-translators/utils.ts new file mode 100644 index 000000000..9f523345b --- /dev/null +++ b/arkui-plugins/ui-plugins/entry-translators/utils.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { factory } from "./factory"; +import { isAnnotation } from "../../common/arkts-utils"; +import { CustomComponentNames } from "../utils"; + +export enum EntryWrapperNames { + ENTRY_FUNC = 'entry', + WRAPPER_CLASS_NAME = '__EntryWrapper', + ENTRY_STORAGE_ANNOTATION_KEY = 'storage', + ENTRY_STORAGE_LOCAL_STORAGE_PROPERTY_NAME = '_entry_local_storage_', + ENTRY_DEFAULT_IMPORT = '@ohos.arkui.component', + ENTRY_POINT_CLASS_NAME = 'EntryPoint' +} + +/** + * @deprecated + */ +export class EntryHandler { + private entryDefClassName: Set; + + private static instance: EntryHandler; + + private constructor() { + this.entryDefClassName = new Set(); + } + + public static getInstance(): EntryHandler { + if (!this.instance) { + this.instance = new EntryHandler(); + } + return this.instance; + } + + public rememberEntryFunction(classname: string): void { + this.entryDefClassName.add(classname); + } + + public createEntryWrapper(): arkts.ClassDeclaration[] { + let result: arkts.ClassDeclaration[] = []; + this.entryDefClassName.forEach(classname => { + result.push(factory.generateEntryWrapper(classname)) + }); + return result; + } +} + +export function isEntryWrapperClass(node: arkts.AstNode): node is arkts.ClassDeclaration { + if (!arkts.isClassDeclaration(node)) return false; + const className = node?.definition?.ident?.name; + if (!className) return false; + return className === EntryWrapperNames.WRAPPER_CLASS_NAME; +} + +/** + * find `{storage: ""}` in `@Entry({storage: ""})` (i.e. annotation's properties). + * + * @param node class definition node + */ +export function findEntryWithStorageInClassAnnotations( + node: arkts.ClassDefinition +): arkts.ClassProperty | undefined { + const annotation = node.annotations.find( + (anno) => { + if (!isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION_NAME)) return false; + const property = anno.properties?.at(0); + if (!property || !arkts.isClassProperty(property)) return false; + if (!property.key || !arkts.isIdentifier(property.key)) return false; + if (!property.value || !arkts.isStringLiteral(property.value)) return false; + return property.key.name === EntryWrapperNames.ENTRY_STORAGE_ANNOTATION_KEY; + } + ); + return annotation?.properties?.at(0) as arkts.ClassProperty | undefined; +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts new file mode 100644 index 000000000..e1d778524 --- /dev/null +++ b/arkui-plugins/ui-plugins/index.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { ComponentTransformer } from './component-transformer' +import { PreprocessorTransformer } from './preprocessor-transform' +import { BuilderLambdaTransformer } from './builder-lambda-transformer' +import { StructTransformer } from './struct-transformer' +import { Plugins, PluginContext } from "../common/plugin-context" +import { ProgramVisitor } from "../common/program-visitor" +import { EXTERNAL_SOURCE_PREFIX_NAMES } from "../common/predefines" +import { debugDump, debugLog, getDumpFileName } from "../common/debug" + +export function uiTransform(): Plugins { + return { + name: 'ui-plugin', + parsed(this: PluginContext) { + console.log('[UI PLUGIN] AFTER PARSED ENTER'); + let program = arkts.arktsGlobal.compilerContext.program; + let script = program.astNode; + if (script) { + debugLog('[BEFORE PARSED SCRIPT] script: ', script.dumpSrc()); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true); + + const componentTransformer = new ComponentTransformer(); + const preprocessorTransformer = new PreprocessorTransformer(); + const programVisitor = new ProgramVisitor({ + pluginName: uiTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + visitors: [componentTransformer, preprocessorTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES + }); + + program = programVisitor.programVisitor(program); + script = program.astNode; + + debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), true); + + this.setArkTSAst(script); + console.log('[UI PLUGIN] AFTER PARSED EXIT'); + return script; + } + console.log('[UI PLUGIN] AFTER PARSED EXIT WITH NO TRANSFORM'); + }, + checked(this: PluginContext) { + console.log('[UI PLUGIN] AFTER CHECKED ENTER'); + let program = arkts.arktsGlobal.compilerContext.program; + let script = program.astNode; + if (script) { + debugLog('[BEFORE STRUCT SCRIPT] script: ', script.dumpSrc()); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true); + + const builderLambdaTransformer = new BuilderLambdaTransformer(); + const structTransformer = new StructTransformer(this.getProjectConfig()); + const programVisitor = new ProgramVisitor({ + pluginName: uiTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [structTransformer, builderLambdaTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + }); + + program = programVisitor.programVisitor(program); + script = program.astNode; + debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true); + + arkts.recheckSubtree(script); + this.setArkTSAst(script); + console.log('[UI PLUGIN] AFTER CHECKED EXIT'); + return script; + } + console.log('[UI PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); + }, + }; +} diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts new file mode 100644 index 000000000..57ce8393f --- /dev/null +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { + AbstractVisitor, + VisitorOptions +} from "../common/abstract-visitor"; +import { + CustomComponentNames +} from "./utils"; +import { + factory +} from "./ui-factory"; +import { + IMPORT_SOURCE_MAP, + OUTPUT_DEPENDENCY_MAP +} from "../common/predefines"; + +export class PreprocessorTransformer extends AbstractVisitor { + private outNameArr: string[] = []; + private structInterfaceImport: arkts.ETSImportDeclaration[] = []; + + reset(): void { + super.reset(); + this.outNameArr = []; + this.structInterfaceImport = []; + } + + isCustomConponentDecl(node: arkts.CallExpression) { + const structCollection: Set = + arkts.GlobalInfo.getInfoInstance().getStructCollection(); + const nodeName: string = node.expression.dumpSrc(); + if (structCollection.has(nodeName)) { + return true; + } + return false; + } + + transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { + if (arkts.isObjectExpression(node.arguments[0])) { + const componentName: string = + `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${node.expression.dumpSrc()}`; + const newArg = arkts.factory.createTSAsExpression( + node.arguments[0].clone(), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(componentName) + ) + ), + true + ); + return arkts.factory.updateCallExpression( + node, + node.expression, + node.typeArguments, + [newArg, ...node.arguments.slice(1)], + node.trailingBlock + ); + } else { + return node; + } + } + + addDependencesImport(node: arkts.ETSImportDeclaration): void { + const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); + node.specifiers.forEach((item: arkts.AstNode) => { + if (!arkts.isImportSpecifier(item)) return; + + if ( + item.imported?.name && + structCollection.has(item.imported?.name) && + this.isExternal === false + ) { + const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + item.imported?.name; + const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + node.source?.clone(), + [factory.createAdditionalImportSpecifier(interfaceName, interfaceName)], + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE + ); + this.structInterfaceImport.push(newImport); + } else { + this.addImportWithSpecifier(item); + } + } + ); + } + + getSourceDependency(sourceName: string): string { + let dependencyName: string = ""; + IMPORT_SOURCE_MAP.forEach((value: Set, key: string) => { + if (value.has(sourceName)) { + dependencyName = key; + } + }) + return dependencyName; + } + + getOutDependencyName(inputName: string): string[] { + const sourceName: string[] = []; + if (OUTPUT_DEPENDENCY_MAP.has(inputName)) { + OUTPUT_DEPENDENCY_MAP.get(inputName)!.forEach((item: string) => { + sourceName.push(item); + }) + } + return sourceName; + } + + addImportWithSpecifier(node: arkts.ImportSpecifier): void { + if (!node.imported?.name) { + return; + } + + const outName: string[] = this.getOutDependencyName(node.imported?.name); + this.outNameArr.push(...outName); + } + + updateScriptWithImport(): void { + new Set(this.outNameArr).forEach((item: string) => { + const source: string = this.getSourceDependency(item); + const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + arkts.factory.create1StringLiteral(source), + [factory.createAdditionalImportSpecifier(item, item)], + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE + ); + arkts.importDeclarationInsert(newImport); + }); + this.structInterfaceImport.forEach((element: arkts.ETSImportDeclaration) => { + arkts.importDeclarationInsert(element); + }); + } + + visitor(node: arkts.AstNode): arkts.AstNode { + const newNode = this.visitEachChild(node) + if (arkts.isCallExpression(newNode) && this.isCustomConponentDecl(newNode)) { + return this.transformComponentCall(newNode); + } else if (arkts.isETSImportDeclaration(newNode)) { + this.addDependencesImport(newNode); + } else if (arkts.isEtsScript(node)) { + this.updateScriptWithImport(); + } + return newNode; + } +} diff --git a/arkui-plugins/ui-plugins/printer-transformer.ts b/arkui-plugins/ui-plugins/printer-transformer.ts new file mode 100644 index 000000000..8f40aace0 --- /dev/null +++ b/arkui-plugins/ui-plugins/printer-transformer.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { PrintVisitor } from '../common/print-visitor' + +export interface TransformerOptions { + trace?: boolean, +} + +export default function printerTransformer( + userPluginOptions?: TransformerOptions +) { + return (node: arkts.EtsScript) => { + return new PrintVisitor().visitor(node) + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/base.ts b/arkui-plugins/ui-plugins/property-translators/base.ts new file mode 100644 index 000000000..bcc469225 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/base.ts @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { createGetter, createSetter, getStageManagementIdent } from './utils'; +import { createOptionalClassProperty } from '../utils'; + +export abstract class PropertyTranslator { + constructor( + protected property: arkts.ClassProperty, + protected structName: string, + ) {} + + abstract translateMember(): arkts.AstNode[]; + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field = createOptionalClassProperty( + newName, + this.property, + getStageManagementIdent(this.property), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + ); + + const member = arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + ); + const thisValue: arkts.MemberExpression = arkts.factory.createMemberExpression( + member, + arkts.factory.createIdentifier('value'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ); + + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisValue, + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisValue, + ); + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.MemberExpression, + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + left: arkts.MemberExpression, + ): arkts.MethodDefinition { + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('observableProxy'), + undefined, + [arkts.factory.createIdentifier('value')], + ); + return createSetter(originalName, typeAnnotation, left, right); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts new file mode 100644 index 000000000..eb164a03d --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +import { + createGetter, + createSetter, + generateThisBackingValue, + generateThisBacking, + getValueInAnnotation, + DecoratorNames +} from "./utils"; +import { PropertyTranslator } from "./base"; +import { + GetterSetter, + InitializerConstructor +} from "./types"; +import { + backingField, + expectName +} from "../../common/arkts-utils"; +import { createOptionalClassProperty } from "../utils"; +import { factory } from "./factory"; + +export class BuilderParamTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const mutableThis: arkts.Expression = generateThisBacking(newName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(mutableThis, originalName); + // const updateStruct: arkts.AstNode = this.generateUpdateStruct(mutableThis, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + // currentStructInfo.updateBody.push(updateStruct); + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, '', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const thisGetValue: arkts.Expression = generateThisBacking(newName, false, true); + const thisSetValue: arkts.Expression = generateThisBacking(newName, false, false); + const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisGetValue); + const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisSetValue); + + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + left: arkts.Expression + ): arkts.MethodDefinition { + const right: arkts.Identifier = arkts.factory.createIdentifier('value'); + return createSetter(originalName, typeAnnotation, left, right, true); + } + + generateInitializeStruct( + mutableThis: arkts.Expression, + originalName: string + ): arkts.AstNode { + return arkts.factory.createAssignmentExpression( + mutableThis, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier("initializers"), originalName)); + } + + generateUpdateStruct( + mutableThis: arkts.Expression, + originalName: string + ): arkts.AstNode { + const right: arkts.MemberExpression = arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('initializers'), + arkts.factory.createIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + true + ); + return arkts.factory.createAssignmentExpression( + mutableThis, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + right + ); + } + +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/consume.ts b/arkui-plugins/ui-plugins/property-translators/consume.ts new file mode 100644 index 000000000..7f10bc8ac --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/consume.ts @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +import { + createGetter, + createSetter, + generateThisBackingValue, + generateThisBacking, + getValueInAnnotation, + DecoratorNames +} from "./utils"; +import { PropertyTranslator } from "./base"; +import { + GetterSetter, + InitializerConstructor +} from "./types"; +import { + backingField, + expectName +} from "../../common/arkts-utils"; +import { createOptionalClassProperty } from "../utils"; + +export class ConsumeTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, 'MutableState', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const thisValue: arkts.MemberExpression = generateThisBackingValue(newName, false, true); + const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisValue); + const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisValue); + + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.MemberExpression + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + left: arkts.MemberExpression + ): arkts.MethodDefinition { + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('observableProxy'), + undefined, + [arkts.factory.createIdentifier('value')] + ); + + return createSetter(originalName, typeAnnotation, left, right); + } + + generateInitializeStruct( + newName: string, + originalName: string + ): arkts.AstNode { + let consumeValueStr: string | undefined = getValueInAnnotation(this.property, DecoratorNames.CONSUME); + if (!consumeValueStr) { + consumeValueStr = originalName; + } + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('contextLocal'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : undefined, + [arkts.factory.create1StringLiteral(consumeValueStr)] + ); + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + right + ); + } + +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts new file mode 100644 index 000000000..bb1ce0de9 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { getInteropPath } from "../../path"; +import { GenSymGenerator } from "../../common/gensym-generator"; +const interop = require(getInteropPath()) +const nullptr = interop.nullptr + +export class factory { + /** + * generate an substitution for optional expression ?., e.g. `{let _tmp = xxx; _tmp == null ? undefined : xxx}`. + * + * @param object item before ?.. + * @param key item after ?.. + */ + static createBlockStatementForOptionalExpression(object: arkts.AstNode, key: string, isCall: boolean = false): arkts.Expression { + let id = GenSymGenerator.getInstance().id(key); + const statements: arkts.Statement[] = [ + factory.generateLetVariableDecl( + arkts.factory.createIdentifier(id), + object + ), + factory.generateTernaryExpression(id, key, isCall) + ]; + return arkts.factory.createBlockExpression(statements); + } + + /** + * generate a variable declaration, e.g. `let = `; + * + * @param left left expression. + * @param right right expression. + */ + static generateLetVariableDecl(left: arkts.Identifier , right: arkts.AstNode): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + left, + right + )] + ); + } + + /** + * generate a ternary expression, e.g. ` ? : `; + * + * @param testLeft the left hand of the test condition. + * @param key item after ?. + */ + static generateTernaryExpression(testLeft: string, key: string, isCall: boolean = false): arkts.ExpressionStatement { + const test = arkts.factory.createBinaryExpression( + arkts.factory.createIdentifier(testLeft), + arkts.factory.createNullLiteral(), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_EQUAL + ); + const consequent: arkts.Expression = arkts.factory.createUndefinedLiteral(); + const alternate: arkts.MemberExpression = arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(testLeft), + arkts.factory.createIdentifier(key), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); + return arkts.factory.createExpressionStatement( + arkts.factory.createConditionalExpression(test, consequent, isCall? arkts.factory.createCallExpression(alternate, undefined, undefined) : alternate) + ); + } + + /** + * generate an substitution for two optional expression ?., e.g. a?.b?.c. + * + * @param node entry wrapper class declaration node. + */ + static createDoubleBlockStatementForOptionalExpression( + object: arkts.AstNode, + key1: string, + key2: string + ): arkts.Expression { + let id = GenSymGenerator.getInstance().id(key1); + let initial: arkts.Expression = factory.createBlockStatementForOptionalExpression(object, key1) + const statements: arkts.Statement[] = [ + factory.generateLetVariableDecl( + arkts.factory.createIdentifier(id), + initial + ), + factory.generateTernaryExpression(id, key2) + ]; + return arkts.factory.createBlockExpression(statements); + } + + /** + * generate an memberExpression with nonNull or optional, e.g. object.property, object?.property or object!.property + * + * @param object item before point. + * @param property item after point. + */ + static createNonNullOrOptionalMemberExpression( + object: string, + property: string, + optional: boolean, + nonNull: boolean + ): arkts.Expression { + const objectNode: arkts.Identifier = arkts.factory.createIdentifier(object); + return arkts.factory.createMemberExpression( + nonNull ? arkts.factory.createTSNonNullExpression(objectNode) : objectNode, + arkts.factory.createIdentifier(property), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + optional + ); + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/index.ts b/arkui-plugins/ui-plugins/property-translators/index.ts new file mode 100644 index 000000000..7062476af --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/index.ts @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +import { PropertyTranslator } from './base'; +import { DecoratorNames, hasDecorator } from './utils'; +import { StateTranslator } from './state'; +import { PropTranslator } from './prop'; +import { StorageLinkTranslator } from './storagelink'; +import { LocalStorageLinkTranslator } from './localstoragelink'; +import { WatchTranslator } from './watch'; +import { LinkTranslator } from './link'; +import { ObjectLinkTranslator } from './objectlink'; +import { LocalStoragePropTranslator } from './localstorageprop'; +import { regularPropertyTranslator } from './regularProperty'; +import { staticPropertyTranslator } from './staticProperty'; +import { isStatic } from '../utils'; +import { StoragePropTranslator } from './storageProp'; +import { ConsumeTranslator } from './consume'; +import { ProvideTranslator } from './provide'; +import { BuilderParamTranslator } from './builderParam'; + +export { PropertyTranslator }; + +export function classifyProperty( + member: arkts.AstNode, + structName: string, + skipDecorator?: DecoratorNames[], +): PropertyTranslator | undefined { + if (!arkts.isClassProperty(member)) return undefined; + if (isStatic(member)) return new staticPropertyTranslator(member, structName); + + if (!skipDecorator?.includes(DecoratorNames.WATCH) && hasDecorator(member, DecoratorNames.WATCH)) { + return new WatchTranslator(member, structName, classifyProperty(member, structName, [DecoratorNames.WATCH])); + } + + if (!skipDecorator?.includes(DecoratorNames.STATE) && hasDecorator(member, DecoratorNames.STATE)) { + return new StateTranslator(member, structName); + } + if (!skipDecorator?.includes(DecoratorNames.STORAGE_LINK) && hasDecorator(member, DecoratorNames.STORAGE_LINK)) { + return new StorageLinkTranslator(member, structName); + } + if ( + !skipDecorator?.includes(DecoratorNames.LOCAL_STORAGE_LINK) && + hasDecorator(member, DecoratorNames.LOCAL_STORAGE_LINK) + ) { + return new LocalStorageLinkTranslator(member, structName); + } + if (!skipDecorator?.includes(DecoratorNames.LINK) && hasDecorator(member, DecoratorNames.LINK)) { + return new LinkTranslator(member, structName); + } + if (!skipDecorator?.includes(DecoratorNames.OBJECT_LINK) && hasDecorator(member, DecoratorNames.OBJECT_LINK)) { + return new ObjectLinkTranslator(member, structName); + } + if ( + !skipDecorator?.includes(DecoratorNames.LOCAL_STORAGE_PROP) && + hasDecorator(member, DecoratorNames.LOCAL_STORAGE_PROP) + ) { + return new LocalStoragePropTranslator(member, structName); + } + if (!skipDecorator?.includes(DecoratorNames.STORAGE_PROP) && hasDecorator(member, DecoratorNames.STORAGE_PROP)) { + return new StoragePropTranslator(member, structName); + } + if (!skipDecorator?.includes(DecoratorNames.PROP) && hasDecorator(member, DecoratorNames.PROP)) { + return new PropTranslator(member, structName); + } + if (!skipDecorator?.includes(DecoratorNames.PROVIDE) && hasDecorator(member, DecoratorNames.PROVIDE)) { + return new ProvideTranslator(member, structName); + } + if (!skipDecorator?.includes(DecoratorNames.CONSUME) && hasDecorator(member, DecoratorNames.CONSUME)) { + return new ConsumeTranslator(member, structName); + } + if (!skipDecorator?.includes(DecoratorNames.BUILDER_PARAM) && hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { + return new BuilderParamTranslator(member, structName); + } + + return new regularPropertyTranslator(member, structName); +} diff --git a/arkui-plugins/ui-plugins/property-translators/link.ts b/arkui-plugins/ui-plugins/property-translators/link.ts new file mode 100644 index 000000000..c9e9ddbdd --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/link.ts @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +import { generateToRecord, createGetter, createSetter2, generateThisBacking, generateGetOrSetCall } from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { factory } from './factory'; +import { createOptionalClassProperty } from '../utils'; + +export class LinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + generateInitializeStruct(newName: string, originalName: string) { + const test = factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + newName, + ); + + const first = arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + arkts.BlockStatement.createBlockStatement([ + arkts.factory.createReturnStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + arkts.factory.createIdentifier('initializers'), + ), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + ), + arkts.factory.createIdentifier('get'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + undefined, + undefined, + ), + ), + ]), + arkts.factory.createFunctionSignature(undefined, [], undefined, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ), + ); + + const second = arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + arkts.BlockStatement.createBlockStatement([ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + arkts.factory.createIdentifier('initializers'), + ), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + ), + arkts.factory.createIdentifier('set'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + undefined, + [arkts.factory.createIdentifier('newValue')], + ), + ), + ]), + arkts.factory.createFunctionSignature( + undefined, + [ + arkts.ETSParameterExpression.create( + arkts.factory.createIdentifier('newValue', this.property.typeAnnotation), + undefined, + ), + ], + undefined, + false, + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ), + ); + + const consequent = arkts.BlockStatement.createBlockStatement([ + arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('LinkDecoratedVariable'), + arkts.factory.createTSTypeParameterInstantiation( + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + ), + ), + ), + [first, second], + ), + ), + ), + ]); + + return arkts.factory.createExpressionStatement(arkts.factory.createIfStatement(test, consequent)); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field: arkts.ClassProperty = createOptionalClassProperty( + newName, + this.property, + 'LinkDecoratedVariable', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + ); + const thisValue: arkts.Expression = generateThisBacking(newName, false, true); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( + generateGetOrSetCall(thisValue, 'set'), + ); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisGet, + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisSet, + ); + + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression, + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + statement: arkts.AstNode, + ): arkts.MethodDefinition { + return createSetter2(originalName, typeAnnotation, statement); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts new file mode 100755 index 000000000..cadc63e5d --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +import { backingField, expectName } from '../../common/arkts-utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { DecoratorNames, generateToRecord } from './utils'; + +function getLocalStorageLinkValueStr(node: arkts.AstNode): string | undefined { + if (!arkts.isClassProperty(node) || !node.value) return undefined; + return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +} + +function getLocalStorageLinkAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { + const isStorageLinkAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.LOCAL_STORAGE_LINK; + + if (isStorageLinkAnnotation && anno.properties.length === 1) { + return getLocalStorageLinkValueStr(anno.properties.at(0)!); + } + return undefined; +} + +function getLocalStorageLinkValueInAnnotation(node: arkts.ClassProperty): string | undefined { + const annotations: readonly arkts.AnnotationUsage[] = node.annotations; + + for (let i = 0; i < annotations.length; i++) { + const anno: arkts.AnnotationUsage = annotations[i]; + const str: string | undefined = getLocalStorageLinkAnnotationValue(anno); + if (!!str) { + return str; + } + } + + return undefined; +} + +export class LocalStorageLinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } + + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + const localStorageLinkValueStr: string | undefined = getLocalStorageLinkValueInAnnotation(this.property); + if (!localStorageLinkValueStr) { + throw new Error('LocalStorageLink required only one value!!'); // TODO: replace this with proper error message. + } + + const call = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('StorageLinkState'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + [ + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('_entry_local_storage_'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + arkts.factory.createStringLiteral(localStorageLinkValueStr), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + ], + ); + + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + call, + ); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts new file mode 100644 index 000000000..bddb14555 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +import { DecoratorNames, generateToRecord } from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; + +function getLocalStorageporpValueStr(node: arkts.AstNode): string | undefined { + if (!arkts.isClassProperty(node) || !node.value) return undefined; + + return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +} +function getLocalStorageporpAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { + const isLocalStorageporpAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.LOCAL_STORAGE_PROP; + + if (isLocalStorageporpAnnotation && anno.properties.length === 1) { + return getLocalStorageporpValueStr(anno.properties.at(0)!); + } + return undefined; +} + +function getLocalStorageporpValueInAnnotation(node: arkts.ClassProperty): string | undefined { + const annotations: readonly arkts.AnnotationUsage[] = node.annotations; + + for (let i = 0; i < annotations.length; i++) { + const anno: arkts.AnnotationUsage = annotations[i]; + const str: string | undefined = getLocalStorageporpAnnotationValue(anno); + if (!!str) { + return str; + } + } + + return undefined; +} + +export class LocalStoragePropTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const updateStruct: arkts.AstNode = this.generateUpdateStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + currentStructInfo.updateBody.push(updateStruct); + + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } + + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + const localStorageporpValueStr: string | undefined = getLocalStorageporpValueInAnnotation(this.property); + if (!localStorageporpValueStr) { + throw new Error('LocalStorageProp required only one value!!'); // TODO: replace this with proper error message. + } + const insideMember = arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('_entry_local_storage_'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ); + const binaryItem = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('StorageLinkState'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + [ + insideMember, + arkts.factory.createStringLiteral(localStorageporpValueStr), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + ], + ); + const call = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('propState'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + [ + arkts.factory.createMemberExpression( + binaryItem, + arkts.factory.createIdentifier('value'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + ], + ); + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + call, + ); + } + + generateUpdateStruct(newName: string, originalName: string): arkts.AstNode { + const localStorageporpValueStr: string | undefined = getLocalStorageporpValueInAnnotation(this.property); + if (!localStorageporpValueStr) { + throw new Error('StorageLink required only one value!!'); // TODO: replace this with proper error message. + } + + const StorageLinkStateValue = arkts.factory.createMemberExpression( + arkts.factory.createCallExpression( + arkts.factory.createIdentifier('StorageLinkState'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + [ + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('_entry_local_storage_'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + arkts.factory.createStringLiteral(localStorageporpValueStr), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + ], + ), + arkts.factory.createIdentifier('value'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ); + + const test = arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ); + + const consequent = arkts.BlockStatement.createBlockStatement([ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression(test), + arkts.factory.createIdentifier('update'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + undefined, + [StorageLinkStateValue], + ), + ), + ]); + + return arkts.factory.createExpressionStatement(arkts.factory.createIfStatement(test, consequent)); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/objectlink.ts b/arkui-plugins/ui-plugins/property-translators/objectlink.ts new file mode 100644 index 000000000..2a21e8200 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/objectlink.ts @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +import { generateToRecord } from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { factory } from './factory'; + +export class ObjectLinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const updateStruct: arkts.AstNode = this.generateUpdateStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + currentStructInfo.updateBody.push(updateStruct); + + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } + + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + const call = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('objectLinkState'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + [], + ); + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + call, + ); + } + + generateUpdateStruct(newName: string, originalName: string): arkts.AstNode { + const test = arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ); + + const consequent = arkts.BlockStatement.createBlockStatement([ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression(test), + arkts.factory.createIdentifier('update'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + undefined, + [ + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName, + ), + ], + ), + ), + ]); + return arkts.factory.createExpressionStatement(arkts.factory.createIfStatement(test, consequent)); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts new file mode 100644 index 000000000..21942313f --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +import { + createGetter, + createSetter2, + generateGetOrSetCall, + generateThisBacking +} from "./utils"; +import { PropertyTranslator } from "./base"; +import { + GetterSetter, + InitializerConstructor +} from "./types"; +import { + backingField, + expectName +} from "../../common/arkts-utils"; +import { createOptionalClassProperty } from "../utils"; +import { factory } from "./factory"; + +export class PropTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const mutableThis: arkts.Expression = generateThisBacking(newName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const updateStruct: arkts.AstNode = this.generateUpdateStruct(mutableThis, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + currentStructInfo.updateBody.push(updateStruct); + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, "PropDecoratedVariable", + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const thisValue: arkts.Expression = generateThisBacking(newName, false, true); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, "get"); + const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( + generateGetOrSetCall(thisValue, "set")); + const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisGet); + const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisSet); + + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + statement: arkts.AstNode + ): arkts.MethodDefinition { + return createSetter2(originalName, typeAnnotation, statement); + } + + generateInitializeStruct( + newName: string, + originalName: string + ): arkts.AstNode { + const binaryItem = arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName + ), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ); + const nonNullItem =arkts.factory.createTSNonNullExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true)); + const right = arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier("PropDecoratedVariable"), + arkts.factory.createTSTypeParameterInstantiation( + this.property.typeAnnotation ? [this.property.typeAnnotation] : [] + ) + ) + ), + [this.property.value ? binaryItem : nonNullItem] + ); + const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( + generateThisBacking(newName), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + right + ); + return arkts.factory.createExpressionStatement(assign); + } + + generateUpdateStruct( + mutableThis: arkts.Expression, + originalName: string + ): arkts.AstNode { + const binaryItem = arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName + ), + arkts.factory.createUndefinedLiteral(), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL + ); + const member: arkts.MemberExpression = arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression(mutableThis), + arkts.factory.createIdentifier('update'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); + const nonNullItem =arkts.factory.createTSNonNullExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true)); + return arkts.factory.createIfStatement( + binaryItem, + arkts.factory.createBlock( + [arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression(member, undefined, [nonNullItem]))] + ) + ); + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/provide.ts b/arkui-plugins/ui-plugins/property-translators/provide.ts new file mode 100644 index 000000000..83cd56990 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/provide.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +import { + createGetter, + createSetter, + generateThisBackingValue, + getValueInAnnotation, + DecoratorNames +} from "./utils"; +import { PropertyTranslator } from "./base"; +import { + GetterSetter, + InitializerConstructor +} from "./types"; +import { + backingField, + expectName +} from "../../common/arkts-utils"; +import { createOptionalClassProperty } from "../utils"; +import { factory } from "./factory"; + +export class ProvideTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, 'MutableState', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const thisValue: arkts.MemberExpression = generateThisBackingValue(newName, false, true); + const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisValue); + const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisValue); + + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.MemberExpression + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + left: arkts.MemberExpression + ): arkts.MethodDefinition { + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('observableProxy'), + undefined, + [arkts.factory.createIdentifier('value')] + ); + + return createSetter(originalName, typeAnnotation, left, right); + } + + generateInitializeStruct( + newName: string, + originName: string + ): arkts.AstNode { + let provideValueStr: string | undefined = getValueInAnnotation(this.property, DecoratorNames.PROVIDE); + if (!provideValueStr) { + provideValueStr = originName; + } + const memExp: arkts.Expression = + factory.createDoubleBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), newName, 'value'); + const body: arkts.BlockStatement = arkts.factory.createBlock( + [ + arkts.factory.createReturnStatement( + arkts.factory.createBinaryExpression( + memExp, + this.property.value, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ) + ) + ] + ); + const script = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [], + this.property.typeAnnotation, + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ); + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('contextLocalStateOf'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : undefined, + [ + arkts.factory.create1StringLiteral(provideValueStr), + arkts.factory.createArrowFunction(script) + ] + ); + return arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + right + ) + ); + } + +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts new file mode 100644 index 000000000..3e569b3f1 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +import { + createGetter, + createSetter, +} from "./utils"; +import { PropertyTranslator } from "./base"; +import { + GetterSetter, + InitializerConstructor +} from "./types"; +import { + backingField, + expectName +} from "../../common/arkts-utils"; + +export class regularPropertyTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void {} + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + return [this.property]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + left: arkts.MemberExpression + ): arkts.MethodDefinition { + const right: arkts.Identifier = arkts.factory.createIdentifier('value'); + return createSetter(originalName, typeAnnotation, left, right); + } + + generateInitializeStruct( + newName: string, + originalName: string + ): arkts.AstNode { + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('this'), + arkts.factory.createIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + this.property.value ?? arkts.factory.createIdentifier('undefined') + ); + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts new file mode 100644 index 000000000..718c22fab --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +import { + generateToRecord, + createGetter, + createSetter2, + generateThisBacking, + generateGetOrSetCall +} from "./utils"; +import { PropertyTranslator } from "./base"; +import { + GetterSetter, + InitializerConstructor +} from "./types"; +import { + backingField, + expectName +} from "../../common/arkts-utils"; +import { createOptionalClassProperty } from "../utils"; +import { factory } from "./factory"; + +export class StateTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, "StateDecoratedVariable", + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const thisValue: arkts.Expression = generateThisBacking(newName, false, true); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, "get"); + const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( + generateGetOrSetCall(thisValue, "set")); + const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisGet); + const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisSet); + + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + statement: arkts.AstNode + ): arkts.MethodDefinition { + return createSetter2(originalName, typeAnnotation, statement); + } + + generateInitializeStruct( + newName: string, + originalName: string + ): arkts.AstNode { + const binaryItem = arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression(arkts.factory.createIdentifier('initializers'), originalName), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ); + const right = arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier("StateDecoratedVariable"), + arkts.factory.createTSTypeParameterInstantiation( + this.property.typeAnnotation ? [this.property.typeAnnotation] : [] + ) + ) + ), + [binaryItem] + ); + const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( + generateThisBacking(newName), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + right + ); + return arkts.factory.createExpressionStatement(assign); + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/staticProperty.ts b/arkui-plugins/ui-plugins/property-translators/staticProperty.ts new file mode 100644 index 000000000..283fc8812 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/staticProperty.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +import { + createGetter, + createSetter, +} from "./utils"; +import { PropertyTranslator } from "./base"; +import { + GetterSetter, + InitializerConstructor +} from "./types"; +import { + backingField, + expectName +} from "../../common/arkts-utils"; + +export class staticPropertyTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void {} + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + return [this.property]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + left: arkts.MemberExpression + ): arkts.MethodDefinition { + const right: arkts.Identifier = arkts.factory.createIdentifier('value'); + return createSetter(originalName, typeAnnotation, left, right); + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/storageProp.ts b/arkui-plugins/ui-plugins/property-translators/storageProp.ts new file mode 100644 index 000000000..797e9acb8 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/storageProp.ts @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +import { backingField, expectName } from '../../common/arkts-utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { + DecoratorNames, + generateToRecord, + createGetter, + createSetter2, + generateThisBacking, + generateGetOrSetCall, +} from './utils'; +import { createOptionalClassProperty } from '../utils'; + +function getStoragePropValueStr(node: arkts.AstNode): string | undefined { + if (!arkts.isClassProperty(node) || !node.value) return undefined; + + return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +} + +function getStoragePropAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { + const isStoragePropAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.STORAGE_PROP; + + if (isStoragePropAnnotation && anno.properties.length === 1) { + return getStoragePropValueStr(anno.properties.at(0)!); + } + return undefined; +} + +function getStoragePropValueInAnnotation(node: arkts.ClassProperty): string | undefined { + const annotations: readonly arkts.AnnotationUsage[] = node.annotations; + + for (let i = 0; i < annotations.length; i++) { + const anno: arkts.AnnotationUsage = annotations[i]; + const str: string | undefined = getStoragePropAnnotationValue(anno); + if (!!str) { + return str; + } + } + return undefined; +} + +export class StoragePropTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } + + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + const storagePropValueStr: string | undefined = getStoragePropValueInAnnotation(this.property); + if (!storagePropValueStr) { + throw new Error('StorageProp required only one value!!'); // TODO: replace this with proper error message. + } + + const newClass = arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('StoragePropDecoratedVariable'), + arkts.factory.createTSTypeParameterInstantiation( + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + ), + ), + ), + [ + arkts.factory.createStringLiteral(storagePropValueStr), + arkts.factory.create1StringLiteral(originalName), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + ], + ); + + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + newClass, + ); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field = createOptionalClassProperty( + newName, + this.property, + 'StoragePropDecoratedVariable', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + ); + const thisValue: arkts.Expression = generateThisBacking(newName, false, true); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( + generateGetOrSetCall(thisValue, 'set'), + ); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisGet, + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisSet, + ); + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression, + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + statement: arkts.AstNode, + ): arkts.MethodDefinition { + return createSetter2(originalName, typeAnnotation, statement); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/storagelink.ts b/arkui-plugins/ui-plugins/property-translators/storagelink.ts new file mode 100644 index 000000000..25720833d --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/storagelink.ts @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +import { backingField, expectName } from '../../common/arkts-utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { + DecoratorNames, + generateToRecord, + createGetter, + createSetter2, + generateThisBacking, + generateGetOrSetCall, +} from './utils'; +import { createOptionalClassProperty } from '../utils'; + +function getStorageLinkValueStr(node: arkts.AstNode): string | undefined { + if (!arkts.isClassProperty(node) || !node.value) return undefined; + + return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +} + +function getStorageLinkAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { + const isStorageLinkAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.STORAGE_LINK; + + if (isStorageLinkAnnotation && anno.properties.length === 1) { + return getStorageLinkValueStr(anno.properties.at(0)!); + } + return undefined; +} + +function getStorageLinkValueInAnnotation(node: arkts.ClassProperty): string | undefined { + const annotations: readonly arkts.AnnotationUsage[] = node.annotations; + + for (let i = 0; i < annotations.length; i++) { + const anno: arkts.AnnotationUsage = annotations[i]; + const str: string | undefined = getStorageLinkAnnotationValue(anno); + if (!!str) { + return str; + } + } + return undefined; +} + +export class StorageLinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { + translateMember(): arkts.AstNode[] { + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + + this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + return this.translateWithoutInitializer(newName, originalName); + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } + + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } + + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + const storageLinkValueStr: string | undefined = getStorageLinkValueInAnnotation(this.property); + if (!storageLinkValueStr) { + throw new Error('StorageLink required only one value!!'); // TODO: replace this with proper error message. + } + + const newClass = arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('StorageLinkDecoratedVariable'), + arkts.factory.createTSTypeParameterInstantiation( + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + ), + ), + ), + [ + arkts.factory.createStringLiteral(storageLinkValueStr), + arkts.factory.create1StringLiteral(originalName), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + ], + ); + + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + newClass, + ); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field = createOptionalClassProperty( + newName, + this.property, + 'StorageLinkDecoratedVariable', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + ); + const thisValue: arkts.Expression = generateThisBacking(newName, false, true); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( + generateGetOrSetCall(thisValue, 'set'), + ); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisGet, + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisSet, + ); + return [field, getter, setter]; + } + + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression, + ): arkts.MethodDefinition { + return createGetter(originalName, typeAnnotation, returnValue); + } + + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + statement: arkts.AstNode, + ): arkts.MethodDefinition { + return createSetter2(originalName, typeAnnotation, statement); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/types.ts b/arkui-plugins/ui-plugins/property-translators/types.ts new file mode 100644 index 000000000..24fc02bb3 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/types.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" + +export interface GetterSetter { + translateGetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + returnValue: arkts.Expression + ): arkts.MethodDefinition; + translateSetter( + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, + left: arkts.MemberExpression + ): arkts.MethodDefinition; +} + +export interface InitializerConstructor { + cacheTranslatedInitializer( + newName: string, + originalName: string + ): void; + translateWithoutInitializer( + newName: string, + originalName: string + ): arkts.AstNode[]; +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts new file mode 100644 index 000000000..1550eb3d0 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { annotation } from '../../common/arkts-utils'; +import { factory } from './factory'; + +export enum DecoratorNames { + STATE = 'State', + STORAGE_LINK = 'StorageLink', + STORAGE_PROP = 'StorageProp', + LINK = 'Link', + PROP = 'Prop', + PROVIDE = 'Provide', + CONSUME = 'Consume', + OBJECT_LINK = 'ObjectLink', + OBSERVED = 'Observed', + WATCH = 'Watch', + BUILDER_PARAM = 'BuilderParam', + BUILDER = 'Builder', + CUSTOM_DIALOG = 'CustomDialog', + LOCAL_STORAGE_PROP = 'LocalStorageProp', + LOCAL_STORAGE_LINK = 'LocalStorageLink', + REUSABLE = 'Reusable', +} + +export function collectPropertyDecorators(property: arkts.ClassProperty): string[] { + const properties: string[] = []; + property.annotations.forEach((anno) => { + if (!!anno.expr && arkts.isIdentifier(anno.expr)) { + properties.push(anno.expr.name); + } + }); + return properties; +} + +export function isDecoratorAnnotation(anno: arkts.AnnotationUsage, decoratorName: DecoratorNames): boolean { + return !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === decoratorName; +} + +export function hasDecorator( + property: arkts.ClassProperty | arkts.ClassDefinition | arkts.MethodDefinition, + decoratorName: DecoratorNames, +): boolean { + if (arkts.isMethodDefinition(property)) { + return property.scriptFunction.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName)); + } + return property.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName)); +} + +export function getStateManagementType(node: arkts.ClassProperty): string { + if (hasDecorator(node, DecoratorNames.STATE)) { + return 'StateDecoratedVariable'; + } else if (hasDecorator(node, DecoratorNames.LINK)) { + return 'DecoratedMutableVariable'; + } else if (hasDecorator(node, DecoratorNames.PROP)) { + return "PropDecoratedVariable"; + } else if (hasDecorator(node, DecoratorNames.STORAGE_LINK)) { + return "StorageLinkDecoratedVariable" + } else if (hasDecorator(node, DecoratorNames.STORAGE_PROP)) { + return "StoragePropDecoratedVariable" + } else if (hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP) || hasDecorator(node, DecoratorNames.OBJECT_LINK)) { + return 'SyncedProperty'; + } + return 'MutableState'; +} + +export function createGetter( + name: string, + type: arkts.TypeNode | undefined, + returns: arkts.Expression, +): arkts.MethodDefinition { + const body = arkts.factory.createBlock([arkts.factory.createReturnStatement(returns)]); + + const scriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature(undefined, [], type?.clone(), false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_GETTER, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + ); + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, + arkts.factory.createIdentifier(name), + arkts.factory.createFunctionExpression(scriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false, + ); +} + +export function createSetter( + name: string, + type: arkts.TypeNode | undefined, + left: arkts.Expression, + right: arkts.AstNode, + needMemo: boolean = false, +): arkts.MethodDefinition { + const body = arkts.factory.createBlock([ + arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + left, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + right, + ), + ), + ]); + const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('value', type?.clone()), + undefined, + ); + if (needMemo) { + param.annotations = [annotation('memo')]; + } + const scriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature(undefined, [param], undefined, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_SETTER, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + ); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, + arkts.factory.createIdentifier(name), + arkts.factory.createFunctionExpression(scriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false, + ); +} + +export function createSetter2( + name: string, + type: arkts.TypeNode | undefined, + statement: arkts.AstNode, +): arkts.MethodDefinition { + const body = arkts.factory.createBlock([statement]); + const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('value', type?.clone()), + undefined, + ); + const scriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature(undefined, [param], undefined, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_SETTER, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + ); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, + arkts.factory.createIdentifier(name), + arkts.factory.createFunctionExpression(scriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false, + ); +} + +export function generateThisBackingValue( + name: string, + optional: boolean = false, + nonNull: boolean = false, +): arkts.MemberExpression { + const member: arkts.Expression = generateThisBacking(name, optional, nonNull); + return arkts.factory.createMemberExpression( + member, + arkts.factory.createIdentifier('value'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ); +} + +export function generateThisBacking( + name: string, + optional: boolean = false, + nonNull: boolean = false, +): arkts.Expression { + const member: arkts.Expression = arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(`${name}`), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + optional, + ); + return nonNull ? arkts.factory.createTSNonNullExpression(member) : member; +} + +function getValueStr(node: arkts.AstNode): string | undefined { + if (!arkts.isClassProperty(node) || !node.value) return undefined; + return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +} + +function getAnnotationValue(anno: arkts.AnnotationUsage, decoratorName: DecoratorNames): string | undefined { + const isSuitableAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === decoratorName; + if (isSuitableAnnotation && anno.properties.length === 1) { + return getValueStr(anno.properties.at(0)!); + } + return undefined; +} + +export function getValueInAnnotation(node: arkts.ClassProperty, decoratorName: DecoratorNames): string | undefined { + const annotations: readonly arkts.AnnotationUsage[] = node.annotations; + for (let i = 0; i < annotations.length; i++) { + const anno: arkts.AnnotationUsage = annotations[i]; + const str: string | undefined = getAnnotationValue(anno, decoratorName); + if (!!str) { + return str; + } + } + return undefined; +} + +export function generateGetOrSetCall(beforCall: arkts.AstNode, type: string) { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + beforCall, + arkts.factory.createIdentifier(type), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + undefined, + type === 'set' ? [arkts.factory.createIdentifier('value')] : undefined, + undefined, + ); +} + +export function generateToRecord(newName: string, originalName: string): arkts.Property { + return arkts.Property.createProperty( + arkts.factory.createStringLiteral(originalName), + arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + 'get', + true + ), + arkts.ETSNewClassInstanceExpression.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('Object')), + ), + [], + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING, + ), + ); +} + +export function getStageManagementIdent(property: arkts.ClassProperty): string { + const useMutableState: boolean = + hasDecorator(property, DecoratorNames.STATE) || + hasDecorator(property, DecoratorNames.STORAGE_LINK) || + hasDecorator(property, DecoratorNames.PROVIDE) || + hasDecorator(property, DecoratorNames.CONSUME) || + hasDecorator(property, DecoratorNames.LINK) || + hasDecorator(property, DecoratorNames.LOCAL_STORAGE_LINK) || + hasDecorator(property, DecoratorNames.LINK); + const useSyncedProperty: boolean = + hasDecorator(property, DecoratorNames.PROP) || + hasDecorator(property, DecoratorNames.STORAGE_PROP) || + hasDecorator(property, DecoratorNames.LOCAL_STORAGE_PROP) || + hasDecorator(property, DecoratorNames.OBJECT_LINK); + if (useMutableState) { + return 'MutableState'; + } else if (useSyncedProperty) { + return 'SyncedProperty'; + } else { + return ''; + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/watch.ts b/arkui-plugins/ui-plugins/property-translators/watch.ts new file mode 100644 index 000000000..cd097b3a7 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/watch.ts @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +import { backingField, expectName } from '../../common/arkts-utils'; +import { PropertyTranslator } from './base'; +import { InitializerConstructor } from './types'; +import { DecoratorNames } from './utils'; + +export class WatchTranslator extends PropertyTranslator implements InitializerConstructor { + constructor( + protected property: arkts.ClassProperty, + protected structName: string, + protected translator?: PropertyTranslator, + ) { + super(property, structName); + } + + translateMember(): arkts.AstNode[] { + const allNodes = this.translator?.translateMember(); + + if (!allNodes) { + // ONLY @WATCH, THROW ERROR + throw new Error('@Watch decorator must be used with other statemanagement decorators'); + } + + const originalName: string = expectName(this.property.key); + const newName: string = backingField(originalName); + this.cacheTranslatedInitializer(newName, originalName); + + return allNodes; + } + + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const updateStruct: arkts.AstNode = this.generateUpdateStruct(newName, originalName); + currentStructInfo.updateBody.push(updateStruct); + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + throw new Error('Method not implemented.'); + } + + generateUpdateStruct(newName: string, originalName: string): arkts.AstNode { + const first = arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + this.property.key!, + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ); + const body = arkts.factory.createBlock([ + arkts.factory.createReturnStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(getWatchValueInAnnotation(this.property)!), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + undefined, + [arkts.factory.createStringLiteral(originalName)], + ), + ), + ]); + + const params = [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('_', this.property.typeAnnotation), + undefined, + ), + ]; + + const second = arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature(undefined, params, undefined, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + ), + ); + + return arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression(arkts.factory.createIdentifier('OnChange'), undefined, [first, second]), + ); + } +} + +function getWatchValueStr(node: arkts.AstNode): string | undefined { + if (!arkts.isClassProperty(node) || !node.value) return undefined; + return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +} + +function getWatchAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { + const isWatchAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.WATCH; + + if (isWatchAnnotation && anno.properties.length === 1) { + return getWatchValueStr(anno.properties.at(0)!); + } + return undefined; +} + +function getWatchValueInAnnotation(node: arkts.ClassProperty): string | undefined { + const annotations: readonly arkts.AnnotationUsage[] = node.annotations; + + for (let i = 0; i < annotations.length; i++) { + const anno: arkts.AnnotationUsage = annotations[i]; + const str: string | undefined = getWatchAnnotationValue(anno); + if (!!str) { + return str; + } + } + + return undefined; +} diff --git a/arkui-plugins/ui-plugins/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-transformer.ts new file mode 100644 index 000000000..a12b81a9c --- /dev/null +++ b/arkui-plugins/ui-plugins/struct-transformer.ts @@ -0,0 +1,492 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { AbstractVisitor } from "../common/abstract-visitor"; +import { + annotation, + collect, + filterDefined +} from "../common/arkts-utils"; +import { ProjectConfig } from "../common/plugin-context"; +import { + classifyProperty, + PropertyTranslator +} from "./property-translators"; +import { + CustomComponentNames, + getCustomComponentOptionsName, + getTypeNameFromTypeParameter, + getTypeParamsFromClassDecl, + Dollars +} from "./utils"; +import { + factory +} from "./ui-factory"; +import { + isEntryWrapperClass +} from "./entry-translators/utils"; +import { + factory as entryFactory +} from "./entry-translators/factory"; +import { DecoratorNames, hasDecorator } from "./property-translators/utils"; + +function isCustomComponentClass(node: arkts.ClassDeclaration): boolean { + if (!node.definition?.ident?.name) return false; + const name: string = node.definition.ident.name; + const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); + return ( + name === CustomComponentNames.COMPONENT_CLASS_NAME + || structCollection.has(name) + ); +} + +function isKnownMethodDefinition(method: arkts.MethodDefinition, name: string): boolean { + if (!method || !arkts.isMethodDefinition(method)) return false; + + // For now, we only considered matched method name. + const isNameMatched: boolean = method.name?.name === name; + return isNameMatched; +} + +function isEtsGlobalClass(node: arkts.ClassDeclaration): boolean { + if (node.definition?.ident?.name === 'ETSGLOBAL') { + return true; + } + return false; +} + +function isReourceNode(node: arkts.CallExpression): boolean { + if (node.expression.dumpSrc() === Dollars.DOLLAR_RESOURCE || + node.expression.dumpSrc() === Dollars.DOLLAR_RAWFILE) { + return true; + } + return false; +} + +function transformBuildMethod( + method: arkts.MethodDefinition, + typeName: string, + optionsName: string, + isDecl?: boolean +): arkts.MethodDefinition { + const updateKey: arkts.Identifier = arkts.factory.createIdentifier( + CustomComponentNames.COMPONENT_BUILD + ); + + const scriptFunction: arkts.ScriptFunction = method.scriptFunction; + const updateScriptFunction = arkts.factory.createScriptFunction( + scriptFunction.body, + arkts.FunctionSignature.createFunctionSignature( + scriptFunction.typeParams, + [ + factory.createStyleParameter(typeName), + factory.createContentParameter(), + factory.createInitializersOptionsParameter(optionsName) + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + scriptFunction.flags, + scriptFunction.modifiers + ).setAnnotations([annotation("memo")]); + + const modifiers: arkts.Es2pandaModifierFlags = isDecl + ? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT + : arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + updateKey, + arkts.factory.createFunctionExpression(updateScriptFunction), + modifiers, + false + ); +} + +function createInitializeStruct( + structInfo: arkts.StructInfo, + optionsTypeName: string, + isDecl?: boolean +) { + const updateKey: arkts.Identifier = arkts.factory.createIdentifier( + CustomComponentNames.COMPONENT_INITIALIZE_STRUCT + ); + + let body: arkts.BlockStatement | undefined; + let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT; + if (!isDecl) { + body = arkts.factory.createBlock(structInfo.initializeBody); + modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; + } + const scriptFunction: arkts.ScriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [ + factory.createInitializersOptionsParameter(optionsTypeName), + factory.createContentParameter() + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + modifiers + ) + .setIdent(updateKey); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + updateKey, + arkts.factory.createFunctionExpression(scriptFunction), + modifiers, + false + ); +} + +function createUpdateStruct( + structInfo: arkts.StructInfo, + optionsTypeName: string, + isDecl?: boolean +) { + const updateKey: arkts.Identifier = arkts.factory.createIdentifier( + CustomComponentNames.COMPONENT_UPDATE_STRUCT + ); + + let body: arkts.BlockStatement | undefined; + let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT; + if (!isDecl) { + body = arkts.factory.createBlock(structInfo.updateBody); + modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; + } + + const scriptFunction: arkts.ScriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [ + factory.createInitializersOptionsParameter(optionsTypeName) + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + modifiers + ) + .setIdent(updateKey); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + updateKey, + arkts.factory.createFunctionExpression(scriptFunction), + modifiers, + false + ); +} + +function toRecord(optionsTypeName: string, toRecordBody: arkts.Property[]){ + // const paramsCasted = params as ChildOptions + const paramsCasted = arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, + [arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_CONST, + arkts.factory.createIdentifier("paramsCasted"), + arkts.TSAsExpression.createTSAsExpression( + arkts.factory.createIdentifier("params"), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(optionsTypeName) + ) + ), + false + ) + )] + ) + + const returnRecord = arkts.factory.createReturnStatement( + arkts.ObjectExpression.createObjectExpression( + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + toRecordBody, + false + ) + ) + + const body: arkts.BlockStatement = arkts.factory.createBlock([paramsCasted, returnRecord]); + + const params = arkts.ETSParameterExpression.create( + arkts.factory.createIdentifier( + "params", + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier("Object") + ) + ) + ), + undefined + ) + + const typeRecord = arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier("Record"), + arkts.factory.createTSTypeParameterInstantiation( + [ + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier("string"), + ) + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier("Object") + ) + ) + ] + ) + ) + ) + + const toRecordScriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [ params ], + typeRecord, + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ) + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, + arkts.factory.createIdentifier('__toRecord'), + arkts.factory.createFunctionExpression(toRecordScriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE, + false + ); +} + +function tranformPropertyMembers( + className: string, + propertyTranslators: PropertyTranslator[], + optionsTypeName: string, + isDecl?: boolean, + scope?: ScopeInfo +): arkts.AstNode[] { + const propertyMembers = propertyTranslators.map(translator => + translator.translateMember() + ); + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo + .getInfoInstance() + .getStructInfo(className); + const collections = []; + if (!scope?.hasInitializeStruct) { + collections.push(createInitializeStruct(currentStructInfo, optionsTypeName, isDecl)) + } + if (!scope?.hasUpdateStruct) { + collections.push(createUpdateStruct(currentStructInfo, optionsTypeName, isDecl)) + } + if(currentStructInfo.isReusable){ + collections.push(toRecord(optionsTypeName, currentStructInfo.toRecordBody)) + } + return collect(...collections, ...propertyMembers); +} + +function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.ClassDeclaration { + if (!node.definition) { + return node; + } + node.definition.body.map((member: arkts.AstNode) => { + if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { + member.scriptFunction.setAnnotations([annotation("memo")]); + } + return member; + }); + return node; +} + +function tranformClassMembers( + node: arkts.ClassDeclaration, + isDecl?: boolean, + scope?: ScopeInfo +): arkts.ClassDeclaration { + if (!node.definition) { + return node; + } + + let classTypeName: string | undefined; + let classOptionsName: string | undefined; + if (isDecl) { + const [classType, classOptions] = getTypeParamsFromClassDecl(node); + classTypeName = getTypeNameFromTypeParameter(classType); + classOptionsName = getTypeNameFromTypeParameter(classOptions); + } + + const definition: arkts.ClassDefinition = node.definition; + const className: string | undefined = node.definition.ident?.name; + if (!className) { + throw new Error("Non Empty className expected for Component") + } + + const propertyTranslators: PropertyTranslator[] = filterDefined( + definition.body.map(it => classifyProperty(it, className)) + ); + + const translatedMembers: arkts.AstNode[] = tranformPropertyMembers( + className, + propertyTranslators, + classOptionsName ?? getCustomComponentOptionsName(className), + isDecl, + scope + ); + + const updateMembers: arkts.AstNode[] = definition.body + .filter((member)=>!arkts.isClassProperty(member)) + .map((member: arkts.AstNode) => { + if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { + member.scriptFunction.setAnnotations([annotation("memo")]); + return member; + } + if ( + arkts.isMethodDefinition(member) + && isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI) + && !isDecl + ) { + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, + member.name, + arkts.factory.createFunctionExpression(member.scriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, + false + ); + } + if ( + arkts.isMethodDefinition(member) + && isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI) + ) { + const buildMethod = transformBuildMethod( + member, + classTypeName ?? className, + classOptionsName ?? getCustomComponentOptionsName(className), + isDecl + ); + return buildMethod; + } + + return member; + } + ); + + const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( + definition, + definition.ident, + definition.typeParams, + definition.superTypeParams, + definition.implements, + undefined, + definition.super, + [...translatedMembers, ...updateMembers], + definition.modifiers, + arkts.classDefinitionFlags(definition) + ); + + return arkts.factory.updateClassDeclaration(node, updateClassDef); +} + +function transformResource(resourceNode: arkts.CallExpression, projectConfig: ProjectConfig | undefined): arkts.CallExpression { + const newArgs: arkts.AstNode[] = [ + arkts.factory.create1StringLiteral(projectConfig?.bundleName ? projectConfig.bundleName : ""), + arkts.factory.create1StringLiteral(projectConfig?.moduleName ? projectConfig.moduleName : ""), + ...resourceNode.arguments + ]; + const transformedKey: string = + resourceNode.expression.dumpSrc() === Dollars.DOLLAR_RESOURCE ? '_r' : '_rawfile'; + return arkts.factory.updateCallExpression( + resourceNode, + arkts.factory.createIdentifier(transformedKey), + resourceNode.typeArguments, + newArgs, + resourceNode.trailingBlock + ); +} + +type ScopeInfo = { + name: string, + hasInitializeStruct?: boolean, + hasUpdateStruct?: boolean, + hasReusableRebind?: boolean +} + +export class StructTransformer extends AbstractVisitor { + private scopeInfos: ScopeInfo[] = []; + projectConfig: ProjectConfig | undefined; + + constructor(projectConfig: ProjectConfig | undefined) { + super() + this.projectConfig = projectConfig; + } + + reset(): void { + super.reset(); + this.scopeInfos = []; + } + + enter(node: arkts.AstNode) { + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + this.scopeInfos.push({ name: node.definition!.ident!.name }); + } + if (arkts.isMethodDefinition(node) && this.scopeInfos.length > 0) { + const name = node.name.name; + const scopeInfo = this.scopeInfos.pop()!; + scopeInfo.hasInitializeStruct ||= (name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT); + scopeInfo.hasUpdateStruct ||= (name === CustomComponentNames.COMPONENT_UPDATE_STRUCT); + scopeInfo.hasReusableRebind ||= (name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE); + this.scopeInfos.push(scopeInfo); + } + } + + exit(node: arkts.AstNode) { + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + this.scopeInfos.pop(); + } + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + this.enter(beforeChildren); + const node = this.visitEachChild(beforeChildren); + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + let scope: ScopeInfo | undefined; + if (this.scopeInfos.length > 0) { + scope = this.scopeInfos[this.scopeInfos.length - 1]; + } + const newClass: arkts.ClassDeclaration = tranformClassMembers( + node, + arkts.hasModifierFlag(node, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE), + scope + ); + this.exit(beforeChildren); + return newClass; + } else if (isEntryWrapperClass(node)) { + entryFactory.addMemoToEntryWrapperClassMethods(node); + return node; + } else if (arkts.isClassDeclaration(node) && isEtsGlobalClass(node)) { + return transformEtsGlobalClassMembers(node); + } else if (arkts.isCallExpression(node) && isReourceNode(node)) { + return transformResource(node, this.projectConfig); + } + return node; + } +} + diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts new file mode 100644 index 000000000..5cf4028df --- /dev/null +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts" +import { + BuilderLambdaNames, + CustomComponentNames +} from "./utils"; +import { annotation } from "../common/arkts-utils"; + +export class factory { + /** + * create `instance: ` as identifier + */ + static createInstanceIdentifier(typeName: string): arkts.Identifier { + return arkts.factory.createIdentifier( + BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, + factory.createTypeReferenceFromString(typeName) + ) + } + + /** + * create `instance: ` as parameter + */ + static createInstanceParameter(typeName: string): arkts.ETSParameterExpression { + return arkts.factory.createParameterDeclaration( + factory.createInstanceIdentifier(typeName), + undefined + ) + } + + /** + * create `(instance: ) => void` + */ + static createStyleLambdaFunctionType(typeName: string): arkts.ETSFunctionType { + return arkts.factory.createFunctionType( + arkts.FunctionSignature.createFunctionSignature( + undefined, + [ + factory.createInstanceParameter(typeName) + ], + factory.createTypeReferenceFromString(typeName), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + ); + } + + /** + * create `style: ((instance: ) => void) | undefined` as identifier + */ + static createStyleIdentifier(typeName: string): arkts.Identifier { + return arkts.factory.createIdentifier( + BuilderLambdaNames.STYLE_PARAM_NAME, + arkts.factory.createUnionType([ + factory.createStyleLambdaFunctionType(typeName), + arkts.factory.createETSUndefinedType() + ]) + ) + } + + /** + * create `@memo() style: ((instance: ) => void) | undefined` as parameter + */ + static createStyleParameter(typeName: string): arkts.ETSParameterExpression { + const styleParam: arkts.Identifier = factory.createStyleIdentifier(typeName); + const param = arkts.factory.createParameterDeclaration(styleParam, undefined); + param.annotations = [annotation("memo")]; + return param; + } + + /** + * create `initializers: | undefined` as identifier + */ + static createInitializerOptionsIdentifier(optionsName: string): arkts.Identifier { + return arkts.factory.createIdentifier( + CustomComponentNames.COMPONENT_INITIALIZERS_NAME, + arkts.factory.createUnionType([ + factory.createTypeReferenceFromString(optionsName), + arkts.factory.createETSUndefinedType() + ]) + ) + } + + /** + * create `initializers: | undefined` as parameter + */ + static createInitializersOptionsParameter(optionsName: string): arkts.ETSParameterExpression { + return arkts.factory.createParameterDeclaration( + factory.createInitializerOptionsIdentifier( + optionsName + ), + undefined + ) + } + + /** + * create `content: (() => void) | undefined` as identifier + */ + static createContentIdentifier(): arkts.Identifier { + return arkts.factory.createIdentifier( + BuilderLambdaNames.CONTENT_PARAM_NAME, + arkts.factory.createUnionType([ + factory.createLambdaFunctionType(), + arkts.factory.createETSUndefinedType() + ]) + ); + } + + /** + * create `@memo() content: (() => void) | undefined` as parameter + */ + static createContentParameter(): arkts.ETSParameterExpression { + const contentParam: arkts.Identifier = factory.createContentIdentifier(); + const param = arkts.factory.createParameterDeclaration(contentParam, undefined); + param.annotations = [annotation("memo")]; + return param; + } + + /** + * create type from string + */ + static createTypeReferenceFromString(name: string): arkts.TypeNode { + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(name) + ) + ); + } + + /** + * create `() => `. If returnType is not given, then using `void`. + */ + static createLambdaFunctionType( + params?: arkts.Expression[], + returnType?: arkts.TypeNode | undefined + ): arkts.ETSFunctionType { + return arkts.factory.createFunctionType( + arkts.FunctionSignature.createFunctionSignature( + undefined, + params ?? [], + returnType + ?? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + ) + } + + /** + * create and insert `import { as } from ` to the top of script's statements. + */ + static createAndInsertImportDeclaration( + source: arkts.StringLiteral, + imported: arkts.Identifier, + local: arkts.Identifier, + importKind: arkts.Es2pandaImportKinds, + program: arkts.Program + ): void { + const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + source, + [ + arkts.factory.createImportSpecifier( + imported, + local + ) + ], + importKind + ) + arkts.importDeclarationInsert(importDecl, program); + return; + } + + /* + * create `import { as } ...`. + */ + static createAdditionalImportSpecifier( + name1: string, + name2: string + ): arkts.ImportSpecifier { + return arkts.factory.createImportSpecifier( + arkts.factory.createIdentifier(name1), + arkts.factory.createIdentifier(name2), + ); + } +} diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts new file mode 100644 index 000000000..74038ff6f --- /dev/null +++ b/arkui-plugins/ui-plugins/utils.ts @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { isAnnotation } from '../common/arkts-utils'; +import { DecoratorNames, isDecoratorAnnotation } from './property-translators/utils'; + +export enum CustomComponentNames { + ENTRY_ANNOTATION_NAME = 'Entry', + COMPONENT_ANNOTATION_NAME = 'Component', + RESUABLE_ANNOTATION_NAME = 'Reusable', + COMPONENT_BUILD_ORI = 'build', + COMPONENT_CONSTRUCTOR_ORI = 'constructor', + COMPONENT_DEFAULT_IMPORT = '@ohos.arkui.component', + COMPONENT_CLASS_NAME = 'CustomComponent', + COMPONENT_INTERFACE_PREFIX = '__Options_', + COMPONENT_INITIALIZE_STRUCT = '__initializeStruct', + COMPONENT_UPDATE_STRUCT = '__updateStruct', + COMPONENT_BUILD = '_build', + REUSABLE_COMPONENT_REBIND_STATE = '__rebindStates', + COMPONENT_INITIALIZERS_NAME = 'initializers', + BUILDCOMPATIBLENODE = '_buildCompatibleNode', + OPTIONS = 'options' +} + +export enum BuilderLambdaNames { + ANNOTATION_NAME = 'ComponentBuilder', + ORIGIN_METHOD_NAME = '$_instantiate', + TRANSFORM_METHOD_NAME = '_instantiateImpl', + STYLE_PARAM_NAME = 'style', + STYLE_ARROW_PARAM_NAME = 'instance', + CONTENT_PARAM_NAME = 'content', +} + +export enum Dollars { + DOLLAR_RESOURCE = '$r', + DOLLAR_RAWFILE = '$rawfile', + DOLLAR_DOLLAR = '$$', +} + +export function findLocalImport( + node: arkts.ETSImportDeclaration, + sourceName: string, + importedName: string +): arkts.Identifier | undefined { + const isFromSource = ( + !!node.source + && node.source.str === sourceName + ); + if (!isFromSource) return undefined; + + const importSpecifier = node.specifiers.find((spec) => ( + arkts.isImportSpecifier(spec) + && !!spec.imported + && spec.imported.name === importedName + )) as arkts.ImportSpecifier | undefined; + return importSpecifier?.local ?? importSpecifier?.imported; +} + +// TODO: currently, we forcely assume initializerOptions is named in pattern __Options_xxx +export function getCustomComponentNameFromInitializerOptions(name: string): string | undefined { + const prefix: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX; + if (name.startsWith(prefix)) { + return name.substring(prefix.length); + } +} + +export function getCustomComponentOptionsName(className: string): string { + return `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${className}`; +} + +export function isStatic(node: arkts.AstNode): boolean { + return node.isStatic; +} + +export function isBuilderLambdaAnnotation(node: arkts.AnnotationUsage): boolean { + return isAnnotation(node, BuilderLambdaNames.ANNOTATION_NAME); +} + +export function hasBuilderLambdaAnnotation(node: arkts.ScriptFunction | arkts.ETSParameterExpression): boolean { + return node.annotations.some(isBuilderLambdaAnnotation); +} + +export function findBuilderLambdaAnnotation( + node: arkts.ScriptFunction | arkts.ETSParameterExpression, +): arkts.AnnotationUsage | undefined { + return node.annotations.find(isBuilderLambdaAnnotation); +} + +export function isBuilderLambdaMethod(node: arkts.MethodDefinition): boolean { + if (!node || !arkts.isMethodDefinition(node)) return false; + + const result = hasBuilderLambdaAnnotation(node.scriptFunction); + if (result) return true; + if (node.overloads.length > 0) { + return node.overloads.some(isBuilderLambdaMethod); + } + return false; +} + +export function findBuilderLambdaInMethod(node: arkts.MethodDefinition): arkts.AnnotationUsage | undefined { + if (!node || !arkts.isMethodDefinition(node)) return undefined; + + const result = findBuilderLambdaAnnotation(node.scriptFunction); + if (!!result) return result; + node.overloads.forEach((overload) => { + const anno: arkts.AnnotationUsage | undefined = findBuilderLambdaInMethod(overload); + if (!!anno) return anno; + }); + return undefined; +} + +export function isBuilderLambdaFunction(node: arkts.FunctionExpression): boolean { + return hasBuilderLambdaAnnotation(node.scriptFunction); +} + +export function findBuilderLambdaInFunction(node: arkts.FunctionExpression): arkts.AnnotationUsage | undefined { + return findBuilderLambdaAnnotation(node.scriptFunction); +} + +export function isBuilderLambdaCall(node: arkts.CallExpression | arkts.Identifier): boolean { + const expr = arkts.isIdentifier(node) ? node : node.expression; + const decl = arkts.getDecl(expr); + + if (!decl) return false; + + if (arkts.isMethodDefinition(decl)) { + return isBuilderLambdaMethod(decl); + } + if (arkts.isFunctionExpression(decl)) { + return isBuilderLambdaFunction(decl); + } + return false; +} + +export function findBuilderLambdaInCall( + node: arkts.CallExpression | arkts.Identifier, +): arkts.AnnotationUsage | undefined { + const decl = findBuilderLambdaDecl(node); + if (!decl) return undefined; + + if (arkts.isMethodDefinition(decl)) { + return findBuilderLambdaInMethod(decl); + } + if (arkts.isFunctionExpression(decl)) { + return findBuilderLambdaInFunction(decl); + } + return undefined; +} + +export function findBuilderLambdaDecl(node: arkts.CallExpression | arkts.Identifier): arkts.AstNode | undefined { + const expr = arkts.isIdentifier(node) ? node : node.expression; + const decl = arkts.getDecl(expr); + + if (!decl) return undefined; + + return decl; +} + +export function getTypeParamsFromClassDecl(node: arkts.ClassDeclaration | undefined): readonly arkts.TSTypeParameter[] { + return node?.definition?.typeParams?.params ?? []; +} + +export function getTypeNameFromTypeParameter(node: arkts.TSTypeParameter | undefined): string | undefined { + return node?.name?.name; +} + +export function createOptionalClassProperty( + name: string, + property: arkts.ClassProperty, + stageManagementIdent: string, + modifiers: arkts.Es2pandaModifierFlags, +): arkts.ClassProperty { + const newProperty = arkts.factory.createClassProperty( + arkts.factory.createIdentifier(name), + undefined, + stageManagementIdent.length + ? createStageManagementType(stageManagementIdent, property) + : property.typeAnnotation?.clone(), + modifiers, + false, + ); + return arkts.classPropertySetOptional(newProperty, true); +} + +export function createStageManagementType( + stageManagementIdent: string, + property: arkts.ClassProperty, +): arkts.ETSTypeReference { + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(stageManagementIdent), + arkts.factory.createTSTypeParameterInstantiation([ + property.typeAnnotation ? property.typeAnnotation.clone() : arkts.factory.createETSUndefinedType(), + ]), + ), + ); +} diff --git a/compiler/package-lock.json b/compiler/package-lock.json index 3aa764b4f..427d0b5dd 100644 --- a/compiler/package-lock.json +++ b/compiler/package-lock.json @@ -1538,6 +1538,44 @@ "picomatch": "^2.3.1" } }, + "@sinonjs/commons": { + "version": "3.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/commons/-/commons-3.0.1.tgz", + "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", + "requires": { + "type-detect": "4.0.8" + } + }, + "@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "requires": { + "@sinonjs/commons": "^3.0.0" + } + }, + "@sinonjs/samsam": { + "version": "8.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/samsam/-/samsam-8.0.2.tgz", + "integrity": "sha512-v46t/fwnhejRSFTGqbpn9u+LQ9xJDse10gNnPgAcxgdoCDMXj/G2asWAC/8Qs+BAZDicX+MNZouXT1A7c83kVw==", + "requires": { + "@sinonjs/commons": "^3.0.1", + "lodash.get": "^4.4.2", + "type-detect": "^4.1.0" + }, + "dependencies": { + "type-detect": { + "version": "4.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/type-detect/-/type-detect-4.1.0.tgz", + "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==" + } + } + }, + "@sinonjs/text-encoding": { + "version": "0.7.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/text-encoding/-/text-encoding-0.7.3.tgz", + "integrity": "sha512-DE427ROAphMQzU4ENbliGYrBSYPXF+TtLg9S8vzeA+OF4ZKzoDdzfL8sxuMUGS/lgRhM6j1URSk9ghf7Xo1tyA==" + }, "@types/eslint": { "version": "8.40.2", "resolved": "https://repo.huaweicloud.com/repository/npm/@types/eslint/-/eslint-8.40.2.tgz", @@ -3207,6 +3245,11 @@ "graceful-fs": "^4.1.6" } }, + "just-extend": { + "version": "6.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/just-extend/-/just-extend-6.2.0.tgz", + "integrity": "sha512-cYofQu2Xpom82S6qD778jBDpwvvy39s1l/hrYij2u9AMdQcGRpaBu6kY4mVhuno5kJVi1DAz4aiphA2WI1/OAw==" + }, "kind-of": { "version": "6.0.3", "resolved": "https://repo.huaweicloud.com/repository/npm/kind-of/-/kind-of-6.0.3.tgz", @@ -3246,6 +3289,11 @@ "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", "dev": true }, + "lodash.get": { + "version": "4.4.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==" + }, "lodash.merge": { "version": "4.6.2", "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -3523,6 +3571,28 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==" }, + "nise": { + "version": "5.1.9", + "resolved": "https://repo.huaweicloud.com/repository/npm/nise/-/nise-5.1.9.tgz", + "integrity": "sha512-qOnoujW4SV6e40dYxJOb3uvuoPHtmLzIk4TFo+j0jPJoC+5Z9xja5qH5JZobEPsa8+YYphMrOSwnrshEhG2qww==", + "requires": { + "@sinonjs/commons": "^3.0.0", + "@sinonjs/fake-timers": "^11.2.2", + "@sinonjs/text-encoding": "^0.7.2", + "just-extend": "^6.2.0", + "path-to-regexp": "^6.2.1" + }, + "dependencies": { + "@sinonjs/fake-timers": { + "version": "11.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/fake-timers/-/fake-timers-11.3.1.tgz", + "integrity": "sha512-EVJO7nW5M/F5Tur0Rf2z/QoMo+1Ia963RiMtapiQrEWvY0iBUvADo8Beegwjpnle5BHkyHuoxSTW3jF43H1XRA==", + "requires": { + "@sinonjs/commons": "^3.0.1" + } + } + } + }, "node-releases": { "version": "2.0.12", "resolved": "https://repo.huaweicloud.com/repository/npm/node-releases/-/node-releases-2.0.12.tgz", @@ -3631,6 +3701,11 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" }, + "path-to-regexp": { + "version": "6.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==" + }, "path-type": { "version": "4.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/path-type/-/path-type-4.0.0.tgz", @@ -3930,6 +4005,26 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" }, + "sinon": { + "version": "15.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/sinon/-/sinon-15.2.0.tgz", + "integrity": "sha512-nPS85arNqwBXaIsFCkolHjGIkFo+Oxu9vbgmBJizLAhqe6P2o3Qmj3KCUoRkfhHtvgDhZdWD3risLHAUJ8npjw==", + "requires": { + "@sinonjs/commons": "^3.0.0", + "@sinonjs/fake-timers": "^10.3.0", + "@sinonjs/samsam": "^8.0.0", + "diff": "^5.1.0", + "nise": "^5.1.4", + "supports-color": "^7.2.0" + }, + "dependencies": { + "diff": { + "version": "5.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/diff/-/diff-5.2.0.tgz", + "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==" + } + } + }, "slash": { "version": "3.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/slash/-/slash-3.0.0.tgz", @@ -4096,8 +4191,7 @@ "type-detect": { "version": "4.0.8", "resolved": "https://repo.huaweicloud.com/repository/npm/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==" }, "type-fest": { "version": "0.20.2", diff --git a/koala-wrapper/.gitignore b/koala-wrapper/.gitignore new file mode 100644 index 000000000..63c762360 --- /dev/null +++ b/koala-wrapper/.gitignore @@ -0,0 +1,5 @@ +build/ +**/*/build/ +node_modules/ + +package-lock.json diff --git a/koala-wrapper/.gitlab-ci.yml b/koala-wrapper/.gitlab-ci.yml new file mode 100644 index 000000000..b2c7957b2 --- /dev/null +++ b/koala-wrapper/.gitlab-ci.yml @@ -0,0 +1,96 @@ +# Copyright (c) 2022-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. + +regenerate plugin-api: + interruptible: true + stage: build + extends: .linux-vm-shell-task + before_script: + - !reference [ .setup, script ] + - cd arkoala-arkts/libarkts + - npm run panda:sdk:install + script: + - npm run regenerate + needs: + - install node modules (arkoala-arkts) + - install node modules (incremental) + - install node modules (interop) + +build plugin-api: + interruptible: true + stage: build + extends: .linux-vm-shell-task + before_script: + - !reference [ .setup, script ] + - cd arkoala-arkts/libarkts + - npm run panda:sdk:install + - npm run regenerate + script: + - npm run compile + needs: + - install node modules (arkoala-arkts) + - install node modules (incremental) + - install node modules (interop) + - regenerate plugin-api + +test plugin-api: + interruptible: true + stage: test + extends: .linux-vm-shell-task + before_script: + - !reference [ .setup, script ] + - cd arkoala-arkts/libarkts + - npm run panda:sdk:install + - npm run regenerate + script: + - npm run test + needs: + - install node modules (arkoala-arkts) + - install node modules (incremental) + - install node modules (interop) + - regenerate plugin-api + +test example arkts-plugin: + interruptible: true + stage: test + extends: .linux-vm-shell-task + before_script: + - !reference [ .setup, script ] + - cd arkoala-arkts/libarkts + - npm run panda:sdk:install + - npm run regenerate + script: + - npm run run + needs: + - install node modules (arkoala-arkts) + - install node modules (incremental) + - install node modules (interop) + +test libarkts playground: + interruptible: true + stage: test + extends: .linux-vm-shell-task + before_script: + - !reference [ .setup, script ] + - cd arkoala-arkts/libarkts + - npm run panda:sdk:install + - npm run regenerate + script: + - npm run run:playground + needs: + - install node modules (arkoala-arkts) + - install node modules (incremental) + - install node modules (interop) + - regenerate plugin-api + + diff --git a/koala-wrapper/.mocharc.json b/koala-wrapper/.mocharc.json new file mode 100644 index 000000000..62699a6cd --- /dev/null +++ b/koala-wrapper/.mocharc.json @@ -0,0 +1,11 @@ +{ + "ui": "tdd", + "spec": "./test/arkts-api/**/*.test.ts", + "extension": [ + "ts" + ], + "require": [ + "../../incremental/test-utils/scripts/register" + ], + "timeout": 10000 +} diff --git a/koala-wrapper/BUILD.gn b/koala-wrapper/BUILD.gn new file mode 100644 index 000000000..d9ad69899 --- /dev/null +++ b/koala-wrapper/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +npm_path = "//prebuilts/build-tools/common/nodejs/current/bin/npm" + +action("gen_sdk_ts_wrapper") { + script = "build_ts_wrapper.py" + deps = [ "./native:es2panda" ] + args = [ + "--source_path", + rebase_path(get_path_info(".", "abspath")), + "--output_path", + rebase_path("$target_gen_dir"), + "--npm", + rebase_path(npm_path), + "--current_os", + "$current_os", + "--root_out_dir", + rebase_path(root_out_dir), + ] + + outputs = [ "$target_gen_dir" ] +} + +ohos_copy("ets2panda_koala_wrapper") { + deps = [ ":gen_sdk_ts_wrapper" ] + sources = [ rebase_path("$target_gen_dir") ] + outputs = [ target_out_dir + "/$target_name" ] + module_source_dir = target_out_dir + "/$target_name" + module_install_name = "" + subsystem_name = "developtools" + part_name = "ace_ets2bundle" +} diff --git a/koala-wrapper/arktsconfig-memo.json b/koala-wrapper/arktsconfig-memo.json new file mode 100644 index 000000000..d3645627b --- /dev/null +++ b/koala-wrapper/arktsconfig-memo.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "package0": "@koalaui/example", + "outDir": "./abc", + "baseUrl": ".", + "paths": { + "@koalaui/runtime": [ + "../memo-plugin/runtime-api" + ] + }, + "plugins": [ + { + "transform": "@koalaui/memo-plugin", + "stage": "checked" + } + ] + } +} diff --git a/koala-wrapper/arktsconfig-print-only.json b/koala-wrapper/arktsconfig-print-only.json new file mode 100644 index 000000000..2a4e2059c --- /dev/null +++ b/koala-wrapper/arktsconfig-print-only.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "outDir": "./abc", + "baseUrl": ".", + "comment": "This is a simplest config to run visitors on both stages", + "plugins": [ + { + "transform": "./plugins/build/src/printer-plugin.js", + "stage": "parsed" + }, + { + "transform": "./plugins/build/src/parsed-stage-plugin.js", + "stage": "parsed" + }, + { + "transform": "./plugins/build/src/checked-stage-plugin.js", + "stage": "checked" + } + ] + } +} diff --git a/koala-wrapper/arktsconfig.json b/koala-wrapper/arktsconfig.json new file mode 100644 index 000000000..85e9e51f6 --- /dev/null +++ b/koala-wrapper/arktsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "outDir": "./abc", + "baseUrl": ".", + "plugins": [ + { + "transform": "./plugins/build/src/printer-plugin.js", + "stage": "parsed" + }, + { + "transform": "./plugins/build/src/parsed-stage-plugin.js", + "stage": "parsed", + "arkui": "../../../arkui/src/sts" + + }, + { + "transform": "./plugins/build/src/checked-stage-plugin.js", + "stage": "checked" + } + ] + } +} diff --git a/koala-wrapper/babel.config.js b/koala-wrapper/babel.config.js new file mode 100644 index 000000000..9d68286e3 --- /dev/null +++ b/koala-wrapper/babel.config.js @@ -0,0 +1,37 @@ +/* + * 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. + */ + +module.exports = function(api) { + api.cache(true); + + const presets = ['@babel/typescript']; + const plugins = [ + '@babel/plugin-transform-modules-commonjs', + '@babel/plugin-proposal-class-properties', + [ + '@babel/plugin-transform-arrow-functions', + { + spec: true + } + ], + './koalaui-transform' + ]; + + return { + presets, + plugins + }; + }; + \ No newline at end of file diff --git a/koala-wrapper/build_ts_wrapper.py b/koala-wrapper/build_ts_wrapper.py new file mode 100755 index 000000000..f83ab26a1 --- /dev/null +++ b/koala-wrapper/build_ts_wrapper.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import shutil +import subprocess +import sys +import tarfile + + +def copy_files(source_path, dest_path, is_file=False): + try: + if is_file: + os.makedirs(os.path.dirname(dest_path), exist_ok=True) + shutil.copy(source_path, dest_path) + else: + shutil.copytree(source_path, dest_path, dirs_exist_ok=True, + symlinks=True) + except Exception as err: + raise Exception("Copy files failed. Error: " + str(err)) from err + + +def run_cmd(cmd, execution_path=None): + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=execution_path) + stdout, stderr = proc.communicate(timeout=1000) + if proc.returncode != 0: + raise Exception(stdout.decode() + stderr.decode()) + + +def build(options): + build_cmd = [options.npm, 'run', 'compile:tsc'] + run_cmd(build_cmd, options.source_path) + + +def copy_output(options): + run_cmd(['rm', '-rf', options.output_path]) + copy_files(os.path.join(options.source_path, 'build/lib'), + os.path.join(options.output_path, 'build/lib')) + + copy_files(os.path.join(options.source_path, 'koalaui'), + os.path.join(options.output_path, 'koalaui')) + + copy_files(os.path.join(options.source_path, 'package.json'), + os.path.join(options.output_path, 'package.json'), True) + + if options.current_os == "mingw" : + copy_files(os.path.join(options.root_out_dir, 'libes2panda.dll'), + os.path.join(options.output_path, 'build/native/es2panda.node'), True) + copy_files(os.path.join(options.root_out_dir, 'libes2panda.dll'), + os.path.join(options.source_path, 'build/native/es2panda.node'), True) + + if options.current_os == "linux" : + copy_files(os.path.join(options.root_out_dir, 'libes2panda.node'), + os.path.join(options.output_path, 'build/native/es2panda.node'), True) + copy_files(os.path.join(options.root_out_dir, 'libes2panda.node'), + os.path.join(options.source_path, 'build/native/es2panda.node'), True) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--npm', help='path to a npm exetuable') + parser.add_argument('--source_path', help='path to build system source') + parser.add_argument('--output_path', help='path to output') + parser.add_argument('--root_out_dir', help='path to root out') + parser.add_argument('--current_os', help='current_os') + + options = parser.parse_args() + return options + + +def main(): + options = parse_args() + + build(options) + copy_output(options) + + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/koala-wrapper/koalaui-transform.js b/koala-wrapper/koalaui-transform.js new file mode 100644 index 000000000..6fdfc2a03 --- /dev/null +++ b/koala-wrapper/koalaui-transform.js @@ -0,0 +1,46 @@ +/* + * 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. + */ + + +module.exports = function (babel) { + const { types: t } = babel; + + function replacePath(source) { + if (source) { + const sourceValue = source.value; + const prefix = '@koalaui/'; + if (sourceValue.startsWith(prefix)) { + source.value = '#koalaui/' + sourceValue.slice(prefix.length); + } + } + } + + return { + visitor: { + ImportDeclaration(path) { + const source = path.node.source; + replacePath(source); + }, + ExportNamedDeclaration(path) { + const source = path.node.source; + replacePath(source); + }, + ExportAllDeclaration(path) { + const source = path.node.source; + replacePath(source); + } + } + }; +}; \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/bridges/ohos/chai/index.d.ts b/koala-wrapper/koalaui/common/dist/bridges/ohos/chai/index.d.ts new file mode 100644 index 000000000..05dac46d7 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/bridges/ohos/chai/index.d.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022-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. + */ + +export interface Assert { + (expression: any, message?: string): asserts expression; + /** + * Asserts non-strict equality (==) of actual and expected. + */ + equal(actual: T, expected: T, message?: string): void; + /** + * Asserts non-strict inequality (!=) of actual and expected. + */ + notEqual(actual: T, expected: T, message?: string): void; + /** + * Asserts strict equality (===) of actual and expected. + */ + strictEqual(actual: T, expected: T, message?: string): void; + /** + * Asserts strict inequality (!==) of actual and expected. + */ + notStrictEqual(actual: T, expected: T, message?: string): void; + deepEqual(actual: any, expected: any, message?: string): void; + notDeepEqual(actual: any, expected: any, message?: string): void; + isTrue(value: any, message?: string): void; + isFalse(value: any, message?: string): void; + closeTo(actual: number, expected: number, delta: number, message?: string): void; + fail(message?: string): void; + isNull(value: any, message?: string): void; + isNotNull(value: any, message?: string): void; + instanceOf(value: any, constructor: Function, message?: string): void; + isAtLeast(valueToCheck: number, valueToBeAtLeast: number, message?: string): void; + exists(value: any, message?: string): void; + throw(fn: () => void, message?: string): void; + throws(fn: () => void, message?: string): void; + isAbove(valueToCheck: number, valueToBeAbove: number, message?: string): void; + isBelow(valueToCheck: number, valueToBeBelow: number, message?: string): void; + match(value: string, regexp: RegExp, message?: string): void; + isDefined(value: any, message?: string): void; + isUndefined(value: any, message?: string): void; + isEmpty(object: any, message?: string): void; + isNotEmpty(object: any, message?: string): void; +} +export declare var assert: Assert; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/bridges/ohos/chai/index.js b/koala-wrapper/koalaui/common/dist/bridges/ohos/chai/index.js new file mode 100644 index 000000000..d1716b7f8 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/bridges/ohos/chai/index.js @@ -0,0 +1,124 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assert = void 0; +const hypium_1 = require("@ohos/hypium"); +// todo: the 'message' arg is ignored +exports.assert = ((expression, message) => { + (0, hypium_1.expect)(Boolean(expression)).assertTrue(); +}); +exports.assert.equal = (actual, expected, message) => { + (0, hypium_1.expect)(actual).assertEqual(expected); +}; +exports.assert.notEqual = (actual, expected, message) => { + // todo: not accurate impl, because compared values are not printed + (0, hypium_1.expect)(actual != expected).assertTrue(); +}; +exports.assert.strictEqual = (actual, expected, message) => { + // todo: not accurate impl, because compared values are not printed + (0, hypium_1.expect)(actual === expected).assertTrue(); +}; +exports.assert.notStrictEqual = (actual, expected, message) => { + // todo: not accurate impl, because compared values are not printed + (0, hypium_1.expect)(actual !== expected).assertTrue(); +}; +exports.assert.deepEqual = (actual, expected, message) => { + // todo: implement + (0, hypium_1.expect)(actual).assertEqual(actual /*expected*/); +}; +exports.assert.notDeepEqual = (actual, expected, message) => { + // todo: implement + (0, hypium_1.expect)(actual).assertEqual(actual /*expected*/); +}; +exports.assert.isTrue = (value, message) => { + (0, hypium_1.expect)(value).assertTrue(); +}; +exports.assert.isFalse = (value, message) => { + (0, hypium_1.expect)(value).assertFalse(); +}; +exports.assert.closeTo = (actual, expected, delta, message) => { + // implementation of 'assertClose' does not fit: + // expect(actual).assertClose(expected, delta) + const diff = Math.abs(actual - expected); + if (diff == delta) + (0, hypium_1.expect)(diff).assertEqual(delta); + else + (0, hypium_1.expect)(diff).assertLess(delta); +}; +exports.assert.fail = (message) => { + (0, hypium_1.expect)().assertFail(); +}; +exports.assert.isNull = (value, message) => { + (0, hypium_1.expect)(value).assertNull(); +}; +exports.assert.isNotNull = (value, message) => { + (0, hypium_1.expect)(value ? null : value).assertNull(); +}; +exports.assert.instanceOf = (value, constructor, message) => { + // todo: not accurate impl + // expect(value).assertInstanceOf(constructor.name) + (0, hypium_1.expect)(value instanceof constructor).assertTrue(); +}; +exports.assert.isAtLeast = (valueToCheck, valueToBeAtLeast, message) => { + if (valueToCheck == valueToBeAtLeast) + (0, hypium_1.expect)(valueToCheck).assertEqual(valueToBeAtLeast); + else + (0, hypium_1.expect)(valueToCheck).assertLarger(valueToBeAtLeast); +}; +exports.assert.exists = (value, message) => { + // todo: not accurate impl + (0, hypium_1.expect)(value == null).assertFalse(); +}; +exports.assert.throw = (fn, message) => { + let fnWrapper = () => { + try { + fn(); + } + catch (e) { + throw new Error("fn thrown exception"); + } + }; + (0, hypium_1.expect)(fnWrapper).assertThrowError("fn thrown exception"); +}; +exports.assert.throws = (fn, message) => { + exports.assert.throw(fn, message); +}; +exports.assert.isAbove = (valueToCheck, valueToBeAbove, message) => { + (0, hypium_1.expect)(valueToCheck).assertLarger(valueToBeAbove); +}; +exports.assert.isBelow = (valueToCheck, valueToBeBelow, message) => { + (0, hypium_1.expect)(valueToCheck).assertLess(valueToBeBelow); +}; +exports.assert.match = (value, regexp, message) => { + // todo: not accurate impl + (0, hypium_1.expect)(regexp.test(value)).assertTrue(); +}; +exports.assert.isDefined = (value, message) => { + // todo: not accurate impl + (0, hypium_1.expect)(value === undefined).assertFalse(); +}; +exports.assert.isUndefined = (value, message) => { + (0, hypium_1.expect)(value).assertUndefined(); +}; +exports.assert.isEmpty = (object, message) => { + // todo: implement + (0, hypium_1.expect)(object !== undefined).assertTrue(); +}; +exports.assert.isNotEmpty = (object, message) => { + // todo: implement + (0, hypium_1.expect)(object !== undefined).assertTrue(); +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/bridges/ohos/index.d.ts b/koala-wrapper/koalaui/common/dist/bridges/ohos/index.d.ts new file mode 100644 index 000000000..46a1ecc14 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/bridges/ohos/index.d.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2022-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. + */ + +export { startTests } from "./mocha"; +export * from "./chai"; +import "./mocha"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/bridges/ohos/index.js b/koala-wrapper/koalaui/common/dist/bridges/ohos/index.js new file mode 100644 index 000000000..2fcb7de3e --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/bridges/ohos/index.js @@ -0,0 +1,36 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.startTests = void 0; +var mocha_1 = require("./mocha"); +Object.defineProperty(exports, "startTests", { enumerable: true, get: function () { return mocha_1.startTests; } }); +__exportStar(require("./chai"), exports); +require("./mocha"); // globals +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/bridges/ohos/mocha/index.d.ts b/koala-wrapper/koalaui/common/dist/bridges/ohos/mocha/index.d.ts new file mode 100644 index 000000000..99c5ebee5 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/bridges/ohos/mocha/index.d.ts @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare function startTests(generateGolden?: boolean): void; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/bridges/ohos/mocha/index.js b/koala-wrapper/koalaui/common/dist/bridges/ohos/mocha/index.js new file mode 100644 index 000000000..b95b9f3ee --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/bridges/ohos/mocha/index.js @@ -0,0 +1,47 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.startTests = void 0; +const hypium_1 = require("@ohos/hypium"); +globalThis.__OpenHarmony = true; +const suiteMap = new Map(); +suite = (title, fn) => { + suiteMap.set(title, fn); +}; +suiteSetup = (title, fn) => { + (0, hypium_1.beforeEach)(fn); +}; +test = ((title, fn) => { + (0, hypium_1.it)(fn ? title : `[SKIP] ${title}`, hypium_1.Size.MEDIUMTEST, fn ? fn : () => { }); +}); +test.skip = (title, fn) => { + (0, hypium_1.it)(`[SKIP] ${title}`, hypium_1.Size.MEDIUMTEST, () => { }); +}; +performance = { + now: () => { + return Date.now(); + } +}; +function startTests(generateGolden = false) { + globalThis.__generateGolden = generateGolden; + suiteMap.forEach((fn, title) => { + (0, hypium_1.describe)(title, function () { + fn(); + }); + }); +} +exports.startTests = startTests; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Errors.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/Errors.d.ts new file mode 100644 index 000000000..e367bc336 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Errors.d.ts @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare function assertion(condition: boolean, message: string): void; +export declare function ensure(value: T | undefined, message: string): T; +//# sourceMappingURL=Errors.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Errors.js b/koala-wrapper/koalaui/common/dist/lib/src/Errors.js new file mode 100644 index 000000000..4f05c8cef --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Errors.js @@ -0,0 +1,36 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ensure = exports.assertion = void 0; +// "assert" is a reserved keyword in ArkTS :-( +function assertion(condition, message) { + if (!condition) + throw new Error(message); +} +exports.assertion = assertion; +// The unknonwn type support in ArkTS compiler is not ready yet. +// When it is ready move from +// ensure(value, message) +// to +// value ?? error(message) +// which is much more readable +function ensure(value, message) { + if (value == undefined) + throw new Error(message); + return value; +} +exports.ensure = ensure; +//# sourceMappingURL=Errors.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Finalization.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/Finalization.d.ts new file mode 100644 index 000000000..5fc9fef68 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Finalization.d.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Thunk } from "#koalaui/compat"; +export { Thunk } from "#koalaui/compat"; +export declare function finalizerRegister(target: object, thunk: Thunk): void; +export declare function finalizerRegisterWithCleaner(target: object, cleaner: () => void): void; +export declare function finalizerUnregister(target: object): void; +//# sourceMappingURL=Finalization.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Finalization.js b/koala-wrapper/koalaui/common/dist/lib/src/Finalization.js new file mode 100644 index 000000000..8b8f9e9b1 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Finalization.js @@ -0,0 +1,39 @@ +"use strict"; +/* + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.finalizerUnregister = exports.finalizerRegisterWithCleaner = exports.finalizerRegister = void 0; +const compat_1 = require("#koalaui/compat"); +function finalizerRegister(target, thunk) { + (0, compat_1.finalizerRegister)(target, thunk); +} +exports.finalizerRegister = finalizerRegister; +function finalizerRegisterWithCleaner(target, cleaner) { + (0, compat_1.finalizerRegister)(target, new CleanerThunk(cleaner)); +} +exports.finalizerRegisterWithCleaner = finalizerRegisterWithCleaner; +function finalizerUnregister(target) { + (0, compat_1.finalizerUnregister)(target); +} +exports.finalizerUnregister = finalizerUnregister; +class CleanerThunk { + constructor(cleaner) { + this.cleaner = cleaner; + } + clean() { + this.cleaner(); + } +} +//# sourceMappingURL=Finalization.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/KoalaProfiler.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/KoalaProfiler.d.ts new file mode 100644 index 000000000..a78eaad53 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/KoalaProfiler.d.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/compat"; +export declare class KoalaProfiler { + private static readonly map; + static nodeCreated(nodeType: int32, node: Object): void; + static nodeDisposed(nodeType: int32, node: Object): void; + static counters: KoalaProfiler | undefined; + private invalidations; + private computes; + private builds; + private nodes; + private realDraws; + private cachedDraws; + private measures; + private layouts; + private frames; + private lastTime; + private lastFPS; + private updateEnterTime; + private updateExitTime; + private updateTime; + private buildEnterTime; + private buildExitTime; + private buildTime; + private layoutEnterTime; + private layoutExitTime; + private layoutTime; + private drawEnterTime; + private drawExitTime; + private drawTime; + private updatableStates; + private mutableStates; + private computableValues; + static enable(): void; + static disable(): void; + static enabled(): boolean; + reset(): void; + report(): void; + getReport(): string; + invalidation(): void; + compute(): void; + build(): void; + node(): void; + realDraw(): void; + cachedDraw(): void; + layout(): void; + measure(): void; + frame(ms: number): void; + buildRootEnter(): void; + buildRootExit(): void; + layoutEnter(): void; + layoutExit(): void; + drawEnter(): void; + drawExit(): void; + updateSnapshotEnter(): void; + updateSnapshotExit(): void; + updateSnapshot(modified: int32, all?: int32): void; +} +//# sourceMappingURL=KoalaProfiler.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/KoalaProfiler.js b/koala-wrapper/koalaui/common/dist/lib/src/KoalaProfiler.js new file mode 100644 index 000000000..664840fdd --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/KoalaProfiler.js @@ -0,0 +1,177 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.KoalaProfiler = void 0; +/** + * Adds statistics for constructing/disposing of the TreeNode instances. + * It is disabled by default because collecting such data affects performance. + */ +const DEBUG_WITH_NODE_STATS = false; +class KoalaProfiler { + constructor() { + this.invalidations = 0; + this.computes = 0; + this.builds = 0; + this.nodes = 0; + this.realDraws = 0; + this.cachedDraws = 0; + this.measures = 0; + this.layouts = 0; + this.frames = 0; + this.lastTime = 0.0; + this.lastFPS = 0; + this.updateEnterTime = 0.0; + this.updateExitTime = 0.0; + this.updateTime = 0.0; + this.buildEnterTime = 0.0; + this.buildExitTime = 0.0; + this.buildTime = 0.0; + this.layoutEnterTime = 0.0; + this.layoutExitTime = 0.0; + this.layoutTime = 0.0; + this.drawEnterTime = 0.0; + this.drawExitTime = 0.0; + this.drawTime = 0.0; + this.updatableStates = 0; + this.mutableStates = 0; + this.computableValues = 0; + } + static nodeCreated(nodeType, node) { + if (KoalaProfiler.map === undefined) + return; + let set = KoalaProfiler.map.get(nodeType); + if (set === undefined) { + set = new Set(); + KoalaProfiler.map.set(nodeType, set); + } + set.add(node); + } + static nodeDisposed(nodeType, node) { + if (KoalaProfiler.map === undefined) + return; + let set = KoalaProfiler.map.get(nodeType); + if (set === undefined) + throw new Error("node never existed"); + if (!set.delete(node)) + console.log("node is already disposed"); + } + static enable() { + KoalaProfiler.counters = new KoalaProfiler(); + } + static disable() { + KoalaProfiler.counters = undefined; + } + static enabled() { + return KoalaProfiler.counters != undefined; + } + reset() { + this.invalidations = 0; + this.computes = 0; + this.builds = 0; + this.nodes = 0; + this.realDraws = 0; + this.cachedDraws = 0; + this.layouts = 0; + this.measures = 0; + this.updateEnterTime = 0; + this.updateExitTime = 0; + this.updatableStates = 0; + this.mutableStates = 0; + this.computableValues = 0; + } + report() { + console.log(this.getReport()); + } + getReport() { + var _a; + const updateTime = Math.round(1000 * (this.updateExitTime - this.updateEnterTime)); + const buildTime = Math.round(1000 * (this.buildExitTime - this.buildEnterTime)); + const layoutTime = Math.round(1000 * (this.layoutExitTime - this.layoutEnterTime)); + const drawTime = Math.round(1000 * (this.drawExitTime - this.drawEnterTime)); + if (this.updateTime < updateTime) + this.updateTime = updateTime; + if (this.buildTime < buildTime) + this.buildTime = buildTime; + if (this.layoutTime < layoutTime) + this.layoutTime = layoutTime; + if (this.drawTime < drawTime) + this.drawTime = drawTime; + // TODO: OHOS does not properly handle \n in template literals + const array = Array.of(`invalidations: ${this.invalidations}`, `modified states: ${this.mutableStates}/${this.updatableStates} + ${this.computableValues}`, `update states (mks): ${this.updateTime} / ${updateTime}`, `build root node (mks): ${this.buildTime} / ${buildTime}`, `layout view (mks): ${this.layoutTime} / ${layoutTime}`, `draw view (mks): ${this.drawTime} / ${drawTime}`, `computes: ${this.computes}`, `builds: ${this.builds}`, `nodes: ${this.nodes}`, `realDraws: ${this.realDraws}`, `cachedDraws: ${this.cachedDraws}`, `measures: ${this.measures}`, `layouts: ${this.layouts}`, `FPS: ${this.lastFPS}`); + (_a = KoalaProfiler.map) === null || _a === void 0 ? void 0 : _a.forEach((set, kind) => { + if (set.size > 0) + array.push(kind + ":" + set.size); + }); + return array.join("\n"); + } + invalidation() { this.invalidations++; } + compute() { this.computes++; } + build() { this.builds++; } + node() { this.nodes++; } + realDraw() { this.realDraws++; } + cachedDraw() { this.cachedDraws++; } + layout() { this.layouts++; } + measure() { this.measures++; } + frame(ms) { + if (ms - this.lastTime <= 1000) { + this.frames++; + } + else { + this.lastFPS = Math.round(this.frames * 1000 / (ms - this.lastTime)); + this.frames = 1; + this.lastTime = ms; + } + } + buildRootEnter() { + this.buildEnterTime = Date.now(); + } + buildRootExit() { + this.buildExitTime = Date.now(); + } + layoutEnter() { + this.layoutEnterTime = Date.now(); + } + layoutExit() { + this.layoutExitTime = Date.now(); + } + drawEnter() { + this.drawEnterTime = Date.now(); + } + drawExit() { + this.drawExitTime = Date.now(); + } + updateSnapshotEnter() { + this.updateEnterTime = Date.now(); + } + updateSnapshotExit() { + this.updateExitTime = Date.now(); + } + updateSnapshot(modified, all) { + if (all === undefined) { + this.computableValues = modified - this.mutableStates; + } + else { + this.mutableStates = modified; + this.updatableStates = all; + } + } +} +exports.KoalaProfiler = KoalaProfiler; +KoalaProfiler.map = DEBUG_WITH_NODE_STATS + ? new Map() + : undefined; +KoalaProfiler.counters = undefined; +//# sourceMappingURL=KoalaProfiler.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/LifecycleEvent.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/LifecycleEvent.d.ts new file mode 100644 index 000000000..e72ef9fae --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/LifecycleEvent.d.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare enum LifecycleEventKind { + SHOW_FRAME = 0, + HIDE_FRAME = 1, + CLOSE_FRAME = 2, + ON_APPEAR = 3, + ON_DISAPPEAR = 4, + SHOW_COMPONENT = 5, + HIDE_COMPONENT = 6, + BACK = 7, + FOCUS_FRAME = 8, + UNFOCUS_FRAME = 9 +} +export declare class LifecycleEvent { + kind: LifecycleEventKind; + constructor(kind: LifecycleEventKind); +} +//# sourceMappingURL=LifecycleEvent.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/LifecycleEvent.js b/koala-wrapper/koalaui/common/dist/lib/src/LifecycleEvent.js new file mode 100644 index 000000000..2b1f275d8 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/LifecycleEvent.js @@ -0,0 +1,37 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LifecycleEvent = exports.LifecycleEventKind = void 0; +var LifecycleEventKind; +(function (LifecycleEventKind) { + LifecycleEventKind[LifecycleEventKind["SHOW_FRAME"] = 0] = "SHOW_FRAME"; + LifecycleEventKind[LifecycleEventKind["HIDE_FRAME"] = 1] = "HIDE_FRAME"; + LifecycleEventKind[LifecycleEventKind["CLOSE_FRAME"] = 2] = "CLOSE_FRAME"; + LifecycleEventKind[LifecycleEventKind["ON_APPEAR"] = 3] = "ON_APPEAR"; + LifecycleEventKind[LifecycleEventKind["ON_DISAPPEAR"] = 4] = "ON_DISAPPEAR"; + LifecycleEventKind[LifecycleEventKind["SHOW_COMPONENT"] = 5] = "SHOW_COMPONENT"; + LifecycleEventKind[LifecycleEventKind["HIDE_COMPONENT"] = 6] = "HIDE_COMPONENT"; + LifecycleEventKind[LifecycleEventKind["BACK"] = 7] = "BACK"; + LifecycleEventKind[LifecycleEventKind["FOCUS_FRAME"] = 8] = "FOCUS_FRAME"; + LifecycleEventKind[LifecycleEventKind["UNFOCUS_FRAME"] = 9] = "UNFOCUS_FRAME"; +})(LifecycleEventKind = exports.LifecycleEventKind || (exports.LifecycleEventKind = {})); +class LifecycleEvent { + constructor(kind) { + this.kind = kind; + } +} +exports.LifecycleEvent = LifecycleEvent; +//# sourceMappingURL=LifecycleEvent.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/MarkableQueue.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/MarkableQueue.d.ts new file mode 100644 index 000000000..075ed627f --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/MarkableQueue.d.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022-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. + */ + +export interface MarkableQueue { + /** Sets the new marker to the queue. */ + setMarker(): void; + /** Adds the given callback to the queue. */ + addCallback(callback: () => void): void; + /** Calls all accumulated callbacks to the latest set marker. */ + callCallbacks(): void; + /** Clears the queue. */ + clear(): void; +} +/** + * Creates a new markable queue to safely process callbacks across several threads or tasks. + * @param reversed - `true` changes the order of calling callbacks + */ +export declare function markableQueue(reversed?: boolean): MarkableQueue; +//# sourceMappingURL=MarkableQueue.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/MarkableQueue.js b/koala-wrapper/koalaui/common/dist/lib/src/MarkableQueue.js new file mode 100644 index 000000000..a956f4620 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/MarkableQueue.js @@ -0,0 +1,94 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.markableQueue = void 0; +const compat_1 = require("#koalaui/compat"); +/** + * Creates a new markable queue to safely process callbacks across several threads or tasks. + * @param reversed - `true` changes the order of calling callbacks + */ +function markableQueue(reversed = false) { + return reversed ? new ReversedQueue() : new DefaultQueue(); +} +exports.markableQueue = markableQueue; +class DefaultQueue { + constructor() { + this.last = new compat_1.AtomicRef(new Block()); + this.first = new compat_1.AtomicRef(this.last.value); + this.marker = new compat_1.AtomicRef(undefined); + } + setMarker() { + const marker = new Block(); + this.last.getAndSet(marker).next.value = marker; + this.marker.value = marker; + } + addCallback(callback) { + const block = new Block(callback); + this.last.getAndSet(block).next.value = block; + } + callCallbacks() { + var _a; + const marker = this.marker.getAndSet(undefined); + if (marker) { + let block = this.first.getAndSet(marker); + while (block !== marker) { + (_a = block.callback) === null || _a === void 0 ? void 0 : _a.call(block); + block = block.next.value; + } + } + } + clear() { + this.last.value = this.first.value; + this.marker.value = undefined; + } +} +class ReversedQueue { + constructor() { + this.last = new compat_1.AtomicRef(undefined); + this.marker = new compat_1.AtomicRef(undefined); + } + setMarker() { + const marker = new Block(); + marker.next.value = this.last.getAndSet(marker); + this.marker.value = marker; + } + addCallback(callback) { + const block = new Block(callback); + block.next.value = this.last.getAndSet(block); + } + callCallbacks() { + var _a, _b; + const marker = this.marker.getAndSet(undefined); + if (marker) { + let block = marker.next.getAndSet(undefined); + while (block) { + (_b = (_a = block).callback) === null || _b === void 0 ? void 0 : _b.call(_a); + block = block.next.value; + } + } + } + clear() { + this.last.value = undefined; + this.marker.value = undefined; + } +} +class Block { + constructor(callback) { + this.next = new compat_1.AtomicRef(undefined); + this.callback = callback; + } +} +//# sourceMappingURL=MarkableQueue.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Matrix33.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/Matrix33.d.ts new file mode 100644 index 000000000..8fff5dd79 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Matrix33.d.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32 } from "#koalaui/compat"; +export declare function mat33(array?: Float32Array): Matrix33; +export declare class Matrix33 { + readonly array: Float32Array; + constructor(array?: Float32Array); + static zero(): Matrix33; + static makeTranslate(dx: float32, dy: float32): Matrix33; + static makeScale(dx: float32, dy?: float32): Matrix33; + static makeRotate(degrees: float32, pivotX?: float32, pivotY?: float32): Matrix33; + static makeSkew(sx: float32, sy: float32): Matrix33; + makeConcat(rhs: Matrix33): Matrix33; + makeTranspose(): Matrix33; +} +//# sourceMappingURL=Matrix33.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Matrix33.js b/koala-wrapper/koalaui/common/dist/lib/src/Matrix33.js new file mode 100644 index 000000000..0c68024b3 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Matrix33.js @@ -0,0 +1,83 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Matrix33 = exports.mat33 = void 0; +const compat_1 = require("#koalaui/compat"); +function mat33(array) { + return (array == undefined) ? new Matrix33() : new Matrix33(array); +} +exports.mat33 = mat33; +const tolerance = (1.0 / (1 << 12)); +class Matrix33 { + constructor(array = new Float32Array((0, compat_1.Array_from_number)([ + 1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0 + ]))) { + this.array = array.slice(); + } + static zero() { + return new Matrix33(new Float32Array((0, compat_1.Array_from_number)([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]))); + } + static makeTranslate(dx, dy) { + return new Matrix33(new Float32Array((0, compat_1.Array_from_number)([1.0, 0.0, dx, 0.0, 1.0, dy, 0.0, 0.0, 1.0]))); + } + static makeScale(dx, dy = dx) { + return new Matrix33(new Float32Array((0, compat_1.Array_from_number)([dx, 0.0, 0.0, 0.0, dy, 0.0, 0.0, 0.0, 1.0]))); + } + static makeRotate(degrees, pivotX, pivotY) { + let rads = degrees * Math.PI / 180; + let cos = Math.cos(rads); + let sin = Math.sin(rads); + if (Math.abs(sin) <= tolerance) + sin = 0.0; + if (Math.abs(cos) <= tolerance) + cos = 0.0; + if (pivotX !== undefined && pivotY != undefined) { + let dx = pivotX - pivotX * cos + pivotY * sin; + let dy = pivotY - pivotY * cos - pivotX * sin; + return new Matrix33(new Float32Array((0, compat_1.Array_from_number)([cos, -sin, dx, sin, cos, dy, 0.0, 0.0, 1.0]))); + } + else { + return new Matrix33(new Float32Array((0, compat_1.Array_from_number)([cos, -sin, 0.0, sin, cos, 0.0, 0.0, 0.0, 1.0]))); + } + } + static makeSkew(sx, sy) { + return new Matrix33(new Float32Array((0, compat_1.Array_from_number)([1.0, sx, 0.0, sy, 1.0, 0.0, 0.0, 0.0, 1.0]))); + } + makeConcat(rhs) { + return new Matrix33(new Float32Array((0, compat_1.Array_from_number)([ + this.array[0] * rhs.array[0] + this.array[1] * rhs.array[3] + this.array[2] * rhs.array[6], + this.array[0] * rhs.array[1] + this.array[1] * rhs.array[4] + this.array[2] * rhs.array[7], + this.array[0] * rhs.array[2] + this.array[1] * rhs.array[5] + this.array[2] * rhs.array[8], + this.array[3] * rhs.array[0] + this.array[4] * rhs.array[3] + this.array[5] * rhs.array[6], + this.array[3] * rhs.array[1] + this.array[4] * rhs.array[4] + this.array[5] * rhs.array[7], + this.array[3] * rhs.array[2] + this.array[4] * rhs.array[5] + this.array[5] * rhs.array[8], + this.array[6] * rhs.array[0] + this.array[7] * rhs.array[3] + this.array[8] * rhs.array[6], + this.array[6] * rhs.array[1] + this.array[7] * rhs.array[4] + this.array[8] * rhs.array[7], + this.array[6] * rhs.array[2] + this.array[7] * rhs.array[5] + this.array[8] * rhs.array[8], + ]))); + } + makeTranspose() { + return new Matrix33(new Float32Array((0, compat_1.Array_from_number)([ + this.array[0], this.array[3], this.array[6], + this.array[1], this.array[4], this.array[7], + this.array[2], this.array[5], this.array[8] + ]))); + } +} +exports.Matrix33 = Matrix33; +//# sourceMappingURL=Matrix33.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Matrix44.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/Matrix44.d.ts new file mode 100644 index 000000000..0524b6b5a --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Matrix44.d.ts @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32 } from "#koalaui/compat"; +import { Matrix33 } from "./Matrix33"; +import { Point3 } from "./Point3"; +export interface RotateOptions { + angle?: float32; + x?: float32; + y?: float32; + z?: float32; + pivotX?: float32; + pivotY?: float32; + pivotZ?: float32; +} +export interface ScaleOptions { + x?: float32; + y?: float32; + z?: float32; + pivotX?: float32; + pivotY?: float32; + pivotZ?: float32; +} +export interface TranslateOptions { + x?: float32; + y?: float32; + z?: float32; +} +export declare function mat44(array?: Float32Array): Matrix44; +/** + * 4x4 matrix with right-handed coordinate system: + * +x goes to the right + * +y goes down + * +z goes into the screen (away from the viewer) + */ +export declare class Matrix44 { + readonly array: Float32Array; + constructor(array?: Float32Array); + static identity(): Matrix44; + static zero(): Matrix44; + static lookAt(eye: Point3, center: Point3, up: Point3): Matrix44; + static perspective(depth: float32): Matrix44; + static perspectiveFov(fov: float32, near: float32, far: float32): Matrix44; + /** + * Returns new matrix, made from Matrix33. + * + * @param matrix - 3x3 matrix + * @returns the new instance of Matrix44 + * + */ + static makeFromMatrix33(matrix: Matrix33): Matrix44; + /** + * Returns new 3x3 matrix, made from this matrix by dropping the third row and the third column. + * + * @returns the new instance of Matrix33 + * + */ + asMatrix33(): Matrix33; + copy(): Matrix44; + concat(matrix: Matrix44): Matrix44; + scale(options: ScaleOptions): Matrix44; + rotate(options: RotateOptions): Matrix44; + translate(options: TranslateOptions): Matrix44; + invert(): Matrix44; + transpose(): Matrix44; + skew(x?: float32, y?: float32): Matrix44; +} +//# sourceMappingURL=Matrix44.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Matrix44.js b/koala-wrapper/koalaui/common/dist/lib/src/Matrix44.js new file mode 100644 index 000000000..4f727e450 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Matrix44.js @@ -0,0 +1,311 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Matrix44 = exports.mat44 = void 0; +const compat_1 = require("#koalaui/compat"); +const Matrix33_1 = require("./Matrix33"); +const Point3_1 = require("./Point3"); +// TODO: this is because ArkTS doesn allow interface literal instances. +class TranslateOptionsImpl { + get x() { return this._x; } + get y() { return this._y; } + get z() { return this._z; } + set x(x) { this._x = x; } + set y(y) { this._y = y; } + set z(z) { this._z = z; } + constructor(x, y, z) { + this._x = x; + this._y = y; + this._z = z; + } +} +function mat44(array) { + return (array == undefined) ? new Matrix44() : new Matrix44(array); +} +exports.mat44 = mat44; +/** + * 4x4 matrix with right-handed coordinate system: + * +x goes to the right + * +y goes down + * +z goes into the screen (away from the viewer) + */ +class Matrix44 { + constructor(array = new Float32Array((0, compat_1.Array_from_number)([ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + ]))) { + this.array = array.slice(); + } + static identity() { + return mat44(); + } + static zero() { + return mat44(new Float32Array((0, compat_1.Array_from_number)([ + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + ]))); + } + static lookAt(eye, center, up) { + const f = center.subtract(eye).normalize(); + const u = up.normalize(); + const s = f.cross(u).normalize(); + const sf = s.cross(f); + return new Matrix44(new Float32Array((0, compat_1.Array_from_number)([ + s.x, sf.x, -f.x, eye.x, + s.y, sf.y, -f.y, eye.y, + s.z, sf.z, -f.z, eye.z, + 0, 0, 0, 1, + ]))).invert(); + } + static perspective(depth) { + return new Matrix44(new Float32Array((0, compat_1.Array_from_number)([ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, -1.0 / depth, 1.0, + ]))); + } + static perspectiveFov(fov, near, far) { + const denomInv = (far - near); + const halfAngle = fov * 0.5; + const cot = Math.cos(halfAngle) / Math.sin(halfAngle); + return new Matrix44(new Float32Array((0, compat_1.Array_from_number)([ + cot, 0.0, 0.0, 0.0, + 0.0, cot, 0.0, 0.0, + 0.0, 0.0, (far + near) * denomInv, 2 * far * near * denomInv, + 0.0, 0.0, -1.0, 0.0, + ]))); + } + /** + * Returns new matrix, made from Matrix33. + * + * @param matrix - 3x3 matrix + * @returns the new instance of Matrix44 + * + */ + static makeFromMatrix33(matrix) { + return new Matrix44(new Float32Array((0, compat_1.Array_from_number)([ + matrix.array[0], matrix.array[1], 0.0, matrix.array[2], + matrix.array[3], matrix.array[4], 0.0, matrix.array[5], + 0.0, 0.0, 1.0, 0.0, + matrix.array[6], matrix.array[7], 0.0, matrix.array[8] + ]))); + } + /** + * Returns new 3x3 matrix, made from this matrix by dropping the third row and the third column. + * + * @returns the new instance of Matrix33 + * + */ + asMatrix33() { + return new Matrix33_1.Matrix33(new Float32Array((0, compat_1.Array_from_number)([ + this.array[0], this.array[1], this.array[3], + this.array[4], this.array[5], this.array[7], + this.array[12], this.array[13], this.array[15] + ]))); + } + copy() { + return new Matrix44(new Float32Array((0, compat_1.Array_from_number)([ + this.array[0], this.array[1], this.array[2], this.array[3], + this.array[4], this.array[5], this.array[6], this.array[7], + this.array[8], this.array[9], this.array[10], this.array[11], + this.array[12], this.array[13], this.array[14], this.array[15] + ]))); + } + concat(matrix) { + const result = new Float32Array((0, compat_1.Array_from_number)([ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ])); + for (let row = 0; row < 4; row++) { + for (let col = 0; col < 4; col++) { + let num = 0; + for (let k = 0; k < 4; k++) { + num += this.array[row * 4 + k] * matrix.array[col + 4 * k]; + } + result[row * 4 + col] = num; + } + } + for (let i = 0; i < this.array.length; i++) { + this.array[i] = result[i]; + } + return this; + } + scale(options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + const scaled = new Matrix44(); + scaled.array[0] = (_a = options.x) !== null && _a !== void 0 ? _a : 1.0; + scaled.array[5] = (_b = options.y) !== null && _b !== void 0 ? _b : 1.0; + scaled.array[10] = (_c = options.z) !== null && _c !== void 0 ? _c : 1.0; + this.translate(new TranslateOptionsImpl(-((_d = options.pivotX) !== null && _d !== void 0 ? _d : 0.0) * ((_e = options.x) !== null && _e !== void 0 ? _e : 1.0) + ((_f = options.pivotX) !== null && _f !== void 0 ? _f : 0.0), -((_g = options.pivotY) !== null && _g !== void 0 ? _g : 0.0) * ((_h = options.y) !== null && _h !== void 0 ? _h : 1.0) + ((_j = options.pivotY) !== null && _j !== void 0 ? _j : 0.0), undefined)).concat(scaled); + return this; + } + rotate(options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + const translationToPivot = mat44().translate(new TranslateOptionsImpl(((_a = options.pivotX) !== null && _a !== void 0 ? _a : 0.0), ((_b = options.pivotY) !== null && _b !== void 0 ? _b : 0.0), ((_c = options.pivotZ) !== null && _c !== void 0 ? _c : 0.0))); + const translationToBack = mat44().translate(new TranslateOptionsImpl(-((_d = options.pivotX) !== null && _d !== void 0 ? _d : 0.0), -((_e = options.pivotY) !== null && _e !== void 0 ? _e : 0.0), -((_f = options.pivotZ) !== null && _f !== void 0 ? _f : 0.0))); + const vec = new Point3_1.Point3((_g = options.x) !== null && _g !== void 0 ? _g : 0.0, (_h = options.y) !== null && _h !== void 0 ? _h : 0.0, (_j = options.z) !== null && _j !== void 0 ? _j : 0.0).normalize(); + const rads = ((_k = options.angle) !== null && _k !== void 0 ? _k : 0.0) * Math.PI / 180; + let c = Math.cos(rads); + let s = Math.sin(rads); + const tolerance = (1.0 / (1 << 12)); + if (Math.abs(s) <= tolerance) + s = 0.0; + if (Math.abs(c) <= tolerance) + c = 0.0; + let t = 1 - c; + const x = vec.x; + const y = vec.y; + const z = vec.z; + const rotation = mat44(); + rotation.array[0] = t * x * x + c; + rotation.array[1] = t * x * y - s * z; + rotation.array[2] = t * x * z + s * y; + rotation.array[3] = 0; + rotation.array[4] = t * x * y + s * z; + rotation.array[5] = t * y * y + c; + rotation.array[6] = t * y * z - s * x; + rotation.array[7] = 0; + rotation.array[8] = t * x * z - s * y; + rotation.array[9] = t * y * z + s * x; + rotation.array[10] = t * z * z + c; + rotation.array[11] = 0; + rotation.array[12] = 0; + rotation.array[13] = 0; + rotation.array[14] = 0; + rotation.array[15] = 1; + this.concat(translationToPivot).concat(rotation).concat(translationToBack); + return this; + } + translate(options) { + var _a, _b, _c; + this.array[3] = (_a = options.x) !== null && _a !== void 0 ? _a : 0.0; + this.array[7] = (_b = options.y) !== null && _b !== void 0 ? _b : 0.0; + this.array[11] = (_c = options.z) !== null && _c !== void 0 ? _c : 0.0; + return this; + } + invert() { + const result = new Float32Array(16); + let a00 = this.array[0]; + let a01 = this.array[1]; + let a02 = this.array[2]; + let a03 = this.array[3]; + let a10 = this.array[4]; + let a11 = this.array[5]; + let a12 = this.array[6]; + let a13 = this.array[7]; + let a20 = this.array[8]; + let a21 = this.array[9]; + let a22 = this.array[10]; + let a23 = this.array[11]; + let a30 = this.array[12]; + let a31 = this.array[13]; + let a32 = this.array[14]; + let a33 = this.array[15]; + let b00 = a00 * a11 - a01 * a10; + let b01 = a00 * a12 - a02 * a10; + let b02 = a00 * a13 - a03 * a10; + let b03 = a01 * a12 - a02 * a11; + let b04 = a01 * a13 - a03 * a11; + let b05 = a02 * a13 - a03 * a12; + let b06 = a20 * a31 - a21 * a30; + let b07 = a20 * a32 - a22 * a30; + let b08 = a20 * a33 - a23 * a30; + let b09 = a21 * a32 - a22 * a31; + let b10 = a21 * a33 - a23 * a31; + let b11 = a22 * a33 - a23 * a32; + let determinant = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + let invdet = 1.0 / determinant; + b00 *= invdet; + b01 *= invdet; + b02 *= invdet; + b03 *= invdet; + b04 *= invdet; + b05 *= invdet; + b06 *= invdet; + b07 *= invdet; + b08 *= invdet; + b09 *= invdet; + b10 *= invdet; + b11 *= invdet; + result[0] = a11 * b11 - a12 * b10 + a13 * b09; + result[1] = a02 * b10 - a01 * b11 - a03 * b09; + result[2] = a31 * b05 - a32 * b04 + a33 * b03; + result[3] = a22 * b04 - a21 * b05 - a23 * b03; + result[4] = a12 * b08 - a10 * b11 - a13 * b07; + result[5] = a00 * b11 - a02 * b08 + a03 * b07; + result[6] = a32 * b02 - a30 * b05 - a33 * b01; + result[7] = a20 * b05 - a22 * b02 + a23 * b01; + result[8] = a10 * b10 - a11 * b08 + a13 * b06; + result[9] = a01 * b08 - a00 * b10 - a03 * b06; + result[10] = a30 * b04 - a31 * b02 + a33 * b00; + result[11] = a21 * b02 - a20 * b04 - a23 * b00; + result[12] = a11 * b07 - a10 * b09 - a12 * b06; + result[13] = a00 * b09 - a01 * b07 + a02 * b06; + result[14] = a31 * b01 - a30 * b03 - a32 * b00; + result[15] = a20 * b03 - a21 * b01 + a22 * b00; + // If 1/det overflows to infinity (i.e. det is denormalized) or any of the inverted matrix + // values is non-finite, return zero to indicate a non-invertible matrix. + let prod = 0; + for (let i = 0; i < result.length; ++i) { + prod *= result[i]; + } + // At this point, prod will either be NaN or 0 + // if prod is NaN, this check will return false + if (prod == 0) { + for (let i = 0; i < this.array.length; i++) { + this.array[i] = result[i]; + } + } + return this; + } + transpose() { + const result = new Float32Array(16); + result[0] = this.array[0]; + result[1] = this.array[4]; + result[2] = this.array[8]; + result[3] = this.array[12]; + result[4] = this.array[1]; + result[5] = this.array[5]; + result[6] = this.array[9]; + result[7] = this.array[13]; + result[8] = this.array[2]; + result[9] = this.array[6]; + result[10] = this.array[10]; + result[11] = this.array[14]; + result[12] = this.array[3]; + result[13] = this.array[7]; + result[14] = this.array[11]; + result[15] = this.array[15]; + for (let i = 0; i < this.array.length; i++) { + this.array[i] = result[i]; + } + return this; + } + skew(x, y) { + this.array[1] += x !== null && x !== void 0 ? x : 0.0; + this.array[4] += y !== null && y !== void 0 ? y : 0.0; + return this; + } +} +exports.Matrix44 = Matrix44; +//# sourceMappingURL=Matrix44.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/PerfProbe.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/PerfProbe.d.ts new file mode 100644 index 000000000..7d860cc4c --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/PerfProbe.d.ts @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022-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. + */ + +export interface PerfProbe { + /** + * The name of the probe. + */ + readonly name: string; + /** + * Whether this is a dummy probe which does not measure (a noop). + * + * @see MainPerfProbe.getProbe + */ + readonly dummy: boolean; + /** + * Exists the probe. + * + * @param log log the gathered statistics. + * @see MainPerfProbe.enterProbe + */ + exit(log: boolean | undefined): void; + /** + * Cancels measuring the probe and its children probes. + */ + cancel(): void; + /** + * User-defined data associated with the probe. + */ + userData: string | undefined; + /** + * Whether the probe was canceled. + */ + readonly canceled: boolean; +} +/** + * The main (root) {@link PerfProbe}. + * + * This probe is used to enter the main activity. + * + * Calling {@link PerfProbe.cancel} removes the main probe and disposes all its resources. + * + * Calling {@link PerfProbe.exit} exits the main probe, cancels it and when the log option is provided + * logs the gathered statistics. + * + * @see enterMainPerfProbe + * @see getMainPerfProbe + */ +export interface MainPerfProbe extends PerfProbe { + /** + * Enters a child probe referenced by the {@link name} and measures it. + * If the probe does not exist, returns a dummy instance. + * + * If the probe already performs a recursive call is counted. + * + * @see PerfProbe.exit + * @see exitProbe + */ + enterProbe(name: string): PerfProbe; + /** + * Exits a child probe referenced by the {@link name}. + * If the probe does not exist, returns a dummy instance. + * + * This is an equivalent of calling {@link getProbe} and then {@link PerfProbe.exit}. + */ + exitProbe(name: string): PerfProbe; + /** + * Returns the child probe referenced by the {@link name} if it exists, + * otherwise a dummy instance. + * + * @see PerfProbe.dummy + */ + getProbe(name: string): PerfProbe; + /** + * Performs the {@link func} of a child probe referenced by the {@link name} and measures it. + * + * This is an equivalent of calling {@link enterProbe} and then {@link exitProbe}. + * + * If the probe already performs a recursive call is counted. + */ + performProbe(name: string, func: () => T): T; + /** + * Returns true if the probe referenced by the {@link name} has been performed + * (entered and exited all the recursive calls). + */ + probePerformed(name: string): boolean; +} +/** + * Creates a {@link MainPerfProbe} instance with the {@link name} and enters its main probe. + * + * If a {@link MainPerfProbe} with this {@link name} already exists then it is canceled and the new one is created. + * + * Exit it with {@link MainPerfProbe.exit}. + */ +export declare function enterMainPerfProbe(name: string): MainPerfProbe; +/** + * Returns {@link MainPerfProbe} instance with the {@link name} if it exists, + * otherwise a dummy instance. + * + * @see MainPerfProbe.dummy + */ +export declare function getMainPerfProbe(name: string): MainPerfProbe; +//# sourceMappingURL=PerfProbe.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/PerfProbe.js b/koala-wrapper/koalaui/common/dist/lib/src/PerfProbe.js new file mode 100644 index 000000000..06e957f97 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/PerfProbe.js @@ -0,0 +1,279 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMainPerfProbe = exports.enterMainPerfProbe = void 0; +const compat_1 = require("#koalaui/compat"); +/** + * Creates a {@link MainPerfProbe} instance with the {@link name} and enters its main probe. + * + * If a {@link MainPerfProbe} with this {@link name} already exists then it is canceled and the new one is created. + * + * Exit it with {@link MainPerfProbe.exit}. + */ +function enterMainPerfProbe(name) { + return new MainPerfProbeImpl(name); +} +exports.enterMainPerfProbe = enterMainPerfProbe; +/** + * Returns {@link MainPerfProbe} instance with the {@link name} if it exists, + * otherwise a dummy instance. + * + * @see MainPerfProbe.dummy + */ +function getMainPerfProbe(name) { + const instance = MainPerfProbeImpl.mainProbes.get(name); + return instance ? instance : MainPerfProbeImpl.DUMMY; +} +exports.getMainPerfProbe = getMainPerfProbe; +class DummyPerfProbe { + get name() { return "dummy"; } + get dummy() { return true; } + exit(log) { } + cancel() { } + get canceled() { return false; } + enterProbe(name) { return PerfProbeImpl.DUMMY; } + exitProbe(name) { return PerfProbeImpl.DUMMY; } + getProbe(name) { return PerfProbeImpl.DUMMY; } + //performProbe: (_: string, func: () => T) => func(), + performProbe(name, func) { return func(); } + probePerformed(_) { return false; } + get userData() { + return undefined; + } + set userData(_) { } +} +class PerfProbeImpl { + constructor(name, main, parent, remainder = false) { + this.children = new Array(); + this.childrenSorted = false; + this.index = 0; + this.startTime = 0.0; + this.totalTime = 0.0; + this.callCount = 0; + this.currentRecursionDepth = 0; + this.recursiveCallCount = 0; + this._canceled = false; + this._name = name; + this._main = main; + this.parent = parent; + this.remainder = remainder; + } + get name() { + return this._name; + } + get dummy() { + return false; + } + get main() { + return this._main; + } + get performing() { + return this.startTime > 0; + } + get userData() { + return this._userData; + } + set userData(value) { + this._userData = value; + } + exit(log) { + if (this.canceled) + return; + if (this.currentRecursionDepth == 0) { + this.totalTime += (0, compat_1.timeNow)() - this.startTime; + this.startTime = 0; + } + else { + this.currentRecursionDepth--; + } + if (!this.performing) { + this.main.pop(this); + } + if (log) + this.log(); + } + cancel(cancelChildren = true) { + this._canceled = true; + if (cancelChildren) + this.maybeCancelChildren(); + } + maybeCancelChildren() { + MainPerfProbeImpl.visit(this, false, (probe, depth) => { + if (probe.performing) + probe.cancel(false); + }); + } + get canceled() { + return this._canceled; + } + toString() { + if (this.canceled) { + return `[${this.name}] canceled`; + } + if (this.performing) { + return `[${this.name}] still performing...`; + } + const mainProbe = this.main.probes.get(this.main.name); + const percentage = mainProbe.totalTime > 0 ? Math.round((100 / mainProbe.totalTime) * this.totalTime) : 0; + let result = `[${this.name}] call count: ${this.callCount}` + + ` | recursive call count: ${this.recursiveCallCount}` + + ` | time: ${this.totalTime}ms ${percentage}%`; + if (this.userData) { + result += ` | user data: ${this.userData}`; + } + return result; + } + log(prefix) { + console.log(prefix ? `${prefix}${this.toString()}` : this.toString()); + } +} +PerfProbeImpl.DUMMY = new DummyPerfProbe(); +class MainPerfProbeImpl extends PerfProbeImpl { + constructor(name) { + super(name); + this.probes = new Map(); + const prev = MainPerfProbeImpl.mainProbes.get(name); + if (prev) + prev.cancel(); + MainPerfProbeImpl.mainProbes.set(name, this); + this.currentProbe = this.enterProbe(name); + } + createProbe(name) { + const probes = name == this.name ? this : new PerfProbeImpl(name, this); + this.push(probes); + return probes; + } + get main() { + return this; + } + push(probe) { + probe.parent = this.currentProbe; + probe.index = probe.parent ? probe.parent.children.length : 0; + if (probe.parent) + probe.parent.children.push(probe); + this.currentProbe = probe; + } + pop(probe) { + if (probe.parent) { + this.currentProbe = probe.parent; + } + } + performProbe(name, func) { + const probe = this.enterProbe(name); + try { + return func(); + } + finally { + probe.exit(); + } + } + enterProbe(name) { + let probe = this.probes.get(name); + if (!probe) { + probe = this.createProbe(name); + this.probes.set(name, probe); + } + probe._canceled = false; + if (probe.performing) { + probe.recursiveCallCount++; + probe.currentRecursionDepth++; + } + else { + probe.startTime = (0, compat_1.timeNow)(); + probe.callCount++; + } + return probe; + } + exitProbe(name) { + const probe = this.getProbe(name); + probe.exit(undefined); + return probe; + } + getProbe(name) { + const probe = this.probes.get(name); + return probe !== undefined ? probe : PerfProbeImpl.DUMMY; + } + probePerformed(name) { + const probe = this.probes.get(name); + return probe != undefined && !probe.performing && !probe.canceled; + } + exit(log) { + super.exit(); + if (log) + this.log(); + this.cancel(); + } + cancel() { + MainPerfProbeImpl.mainProbes.delete(this.name); + } + static visit(root, logging, apply) { + let current = root; + let index = 0; + let depth = 0; + let visiting = true; + while (true) { + if (visiting) { + current.index = 0; + apply(current, depth); + } + if (index >= current.children.length) { + if (!current.parent) { + break; + } + current = current.parent; + index = ++current.index; + depth--; + visiting = false; + continue; + } + visiting = true; + if (logging && !current.childrenSorted) { + current.childrenSorted = true; + current.children = current.children.sort((p1, p2) => p2.totalTime - p1.totalTime); + if (depth == 0) { + // a special probe to log the time remained + current.children.push(new PerfProbeImpl("", root.main, current, true)); + } + } + current = current.children[index]; + index = 0; + depth++; + } + } + log(prefix) { + prefix = prefix !== undefined ? `${prefix}: ` : ""; + console.log(`${prefix}perf probes:`); + MainPerfProbeImpl.visit(this.main, true, (probe, depth) => { + let indent = "\t"; + for (let i = 0; i < depth; i++) + indent += "\t"; + if (probe.remainder) { + const parentTime = probe.parent.totalTime; + let childrenTime = 0; + probe.parent.children.forEach((a) => { childrenTime += a.totalTime; }); + probe.totalTime = Math.max(0, parentTime - childrenTime); + const percentage = parentTime > 0 ? Math.round((100 / parentTime) * probe.totalTime) : 0; + console.log(`${prefix}${indent}[${probe.name}] time: ${(0, compat_1.numberToFixed)(probe.totalTime, 2)}ms ${percentage}%`); + } + else { + console.log(`${prefix}${indent}${probe.toString()}`); + } + }); + } +} +MainPerfProbeImpl.mainProbes = new Map(); +MainPerfProbeImpl.DUMMY = new DummyPerfProbe(); +//# sourceMappingURL=PerfProbe.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Point.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/Point.d.ts new file mode 100644 index 000000000..f35d2561b --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Point.d.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32 } from "#koalaui/compat"; +export declare class Point { + coordinates: Float32Array; + constructor(x: float32, y: float32); + get x(): float32; + get y(): float32; + offsetXY(dx: float32, dy: float32): Point; + offset(vec: Point): Point; + scale(scale: float32): Point; + scaleXY(sx: float32, sy: float32): Point; + static ZERO: Point; + toArray(): Float32Array; + static flattenArray(points: Array): Float32Array; + static fromArray(points: Float32Array): Array; +} +//# sourceMappingURL=Point.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Point.js b/koala-wrapper/koalaui/common/dist/lib/src/Point.js new file mode 100644 index 000000000..1b5080bfa --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Point.js @@ -0,0 +1,65 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Point = void 0; +class Point { + constructor(x, y) { + this.coordinates = new Float32Array(2); + this.coordinates[0] = x; + this.coordinates[1] = y; + } + get x() { + return this.coordinates[0]; + } + get y() { + return this.coordinates[1]; + } + offsetXY(dx, dy) { + return new Point(this.x + dx, this.y + dy); + } + offset(vec) { + return this.offsetXY(vec.x, vec.y); + } + scale(scale) { + return this.scaleXY(scale, scale); + } + scaleXY(sx, sy) { + return new Point(this.x * sx, this.y * sy); + } + toArray() { + return this.coordinates; + } + static flattenArray(points) { + let array = new Float32Array(points.length * 2); + for (let i = 0; i < points.length; i++) { + array[i * 2] = points[i].x; + array[i * 2 + 1] = points[i].y; + } + return array; + } + static fromArray(points) { + if (points.length % 2 != 0) + throw new Error("Expected " + points.length + " % 2 == 0"); + let array = new Array(points.length / 2); + for (let i = 0; i < points.length / 2; i++) { + array[i] = new Point(points[i * 2], points[i * 2 + 1]); + } + return array; + } +} +exports.Point = Point; +Point.ZERO = new Point(0.0, 0.0); +//# sourceMappingURL=Point.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Point3.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/Point3.d.ts new file mode 100644 index 000000000..d6121d56d --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Point3.d.ts @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32 } from "#koalaui/compat"; +export declare class Point3 { + x: float32; + y: float32; + z: float32; + constructor(x: float32, y: float32, z: float32); + subtract(value: Point3): Point3; + cross(value: Point3): Point3; + normalize(): Point3; +} +//# sourceMappingURL=Point3.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/Point3.js b/koala-wrapper/koalaui/common/dist/lib/src/Point3.js new file mode 100644 index 000000000..de748e8e1 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/Point3.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Point3 = void 0; +class Point3 { + constructor(x, y, z) { + this.x = x; + this.y = y; + this.z = z; + } + subtract(value) { + return new Point3(this.x - value.x, this.y - value.y, this.z - value.z); + } + cross(value) { + return new Point3(this.y * value.z - this.z * value.y, this.z * value.x - this.x * value.z, this.x * value.y - this.y * value.x); + } + normalize() { + const mag = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + const tolerance = (1.0 / (1 << 12)); + if (mag < tolerance) { + // This semicolon after return this is a workaround for ArkTS bug + return this; + } + return new Point3(this.x / mag, this.y / mag, this.z / mag); + } +} +exports.Point3 = Point3; +//# sourceMappingURL=Point3.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/index.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/index.d.ts new file mode 100644 index 000000000..8b816b3c4 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/index.d.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022-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. + */ + +export { int8, uint8, int32, uint32, int64, uint64, float32, float64, asArray, asFloat64, float32FromBits, int32BitsFromFloat, Array_from_set, AtomicRef, CustomTextDecoder, CustomTextEncoder, className, lcClassName, functionOverValue, Observed, Observable, ObservableHandler, observableProxy, observableProxyArray, isFunction, propDeepCopy, refEqual, int8Array, unsafeCast } from "#koalaui/compat"; +export { clamp, lerp, modulo, parseNumber, isFiniteNumber, getDistancePx } from "./math"; +export { hashCodeFromString } from "./stringUtils"; +export { KoalaProfiler } from "./KoalaProfiler"; +export * from "./PerfProbe"; +export * from "./Errors"; +export * from "./LifecycleEvent"; +export * from "./Finalization"; +export * from "./MarkableQueue"; +export * from "./Matrix33"; +export * from "./Matrix44"; +export * from "./Point3"; +export * from "./Point"; +export { SHA1Hash, createSha1 } from "./sha1"; +export { UniqueId } from "./uniqueId"; +export * from "./koalaKey"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/index.js b/koala-wrapper/koalaui/common/dist/lib/src/index.js new file mode 100644 index 000000000..e50e6f07a --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/index.js @@ -0,0 +1,79 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UniqueId = exports.createSha1 = exports.SHA1Hash = exports.KoalaProfiler = exports.hashCodeFromString = exports.getDistancePx = exports.isFiniteNumber = exports.parseNumber = exports.modulo = exports.lerp = exports.clamp = exports.unsafeCast = exports.int8Array = exports.refEqual = exports.propDeepCopy = exports.isFunction = exports.observableProxyArray = exports.observableProxy = exports.ObservableHandler = exports.Observed = exports.functionOverValue = exports.lcClassName = exports.className = exports.CustomTextEncoder = exports.CustomTextDecoder = exports.AtomicRef = exports.Array_from_set = exports.int32BitsFromFloat = exports.float32FromBits = exports.asFloat64 = exports.asArray = void 0; +var compat_1 = require("#koalaui/compat"); +Object.defineProperty(exports, "asArray", { enumerable: true, get: function () { return compat_1.asArray; } }); +Object.defineProperty(exports, "asFloat64", { enumerable: true, get: function () { return compat_1.asFloat64; } }); +Object.defineProperty(exports, "float32FromBits", { enumerable: true, get: function () { return compat_1.float32FromBits; } }); +Object.defineProperty(exports, "int32BitsFromFloat", { enumerable: true, get: function () { return compat_1.int32BitsFromFloat; } }); +Object.defineProperty(exports, "Array_from_set", { enumerable: true, get: function () { return compat_1.Array_from_set; } }); +Object.defineProperty(exports, "AtomicRef", { enumerable: true, get: function () { return compat_1.AtomicRef; } }); +Object.defineProperty(exports, "CustomTextDecoder", { enumerable: true, get: function () { return compat_1.CustomTextDecoder; } }); +Object.defineProperty(exports, "CustomTextEncoder", { enumerable: true, get: function () { return compat_1.CustomTextEncoder; } }); +Object.defineProperty(exports, "className", { enumerable: true, get: function () { return compat_1.className; } }); +Object.defineProperty(exports, "lcClassName", { enumerable: true, get: function () { return compat_1.lcClassName; } }); +Object.defineProperty(exports, "functionOverValue", { enumerable: true, get: function () { return compat_1.functionOverValue; } }); +Object.defineProperty(exports, "Observed", { enumerable: true, get: function () { return compat_1.Observed; } }); +Object.defineProperty(exports, "ObservableHandler", { enumerable: true, get: function () { return compat_1.ObservableHandler; } }); +Object.defineProperty(exports, "observableProxy", { enumerable: true, get: function () { return compat_1.observableProxy; } }); +Object.defineProperty(exports, "observableProxyArray", { enumerable: true, get: function () { return compat_1.observableProxyArray; } }); +Object.defineProperty(exports, "isFunction", { enumerable: true, get: function () { return compat_1.isFunction; } }); +Object.defineProperty(exports, "propDeepCopy", { enumerable: true, get: function () { return compat_1.propDeepCopy; } }); +Object.defineProperty(exports, "refEqual", { enumerable: true, get: function () { return compat_1.refEqual; } }); +Object.defineProperty(exports, "int8Array", { enumerable: true, get: function () { return compat_1.int8Array; } }); +Object.defineProperty(exports, "unsafeCast", { enumerable: true, get: function () { return compat_1.unsafeCast; } }); +var math_1 = require("./math"); +Object.defineProperty(exports, "clamp", { enumerable: true, get: function () { return math_1.clamp; } }); +Object.defineProperty(exports, "lerp", { enumerable: true, get: function () { return math_1.lerp; } }); +Object.defineProperty(exports, "modulo", { enumerable: true, get: function () { return math_1.modulo; } }); +Object.defineProperty(exports, "parseNumber", { enumerable: true, get: function () { return math_1.parseNumber; } }); +Object.defineProperty(exports, "isFiniteNumber", { enumerable: true, get: function () { return math_1.isFiniteNumber; } }); +Object.defineProperty(exports, "getDistancePx", { enumerable: true, get: function () { return math_1.getDistancePx; } }); +var stringUtils_1 = require("./stringUtils"); +Object.defineProperty(exports, "hashCodeFromString", { enumerable: true, get: function () { return stringUtils_1.hashCodeFromString; } }); +var KoalaProfiler_1 = require("./KoalaProfiler"); +Object.defineProperty(exports, "KoalaProfiler", { enumerable: true, get: function () { return KoalaProfiler_1.KoalaProfiler; } }); +__exportStar(require("./PerfProbe"), exports); +__exportStar(require("./Errors"), exports); +__exportStar(require("./LifecycleEvent"), exports); +__exportStar(require("./Finalization"), exports); +__exportStar(require("./MarkableQueue"), exports); +__exportStar(require("./Matrix33"), exports); +__exportStar(require("./Matrix44"), exports); +__exportStar(require("./Point3"), exports); +__exportStar(require("./Point"), exports); +var sha1_1 = require("./sha1"); +Object.defineProperty(exports, "SHA1Hash", { enumerable: true, get: function () { return sha1_1.SHA1Hash; } }); +Object.defineProperty(exports, "createSha1", { enumerable: true, get: function () { return sha1_1.createSha1; } }); +var uniqueId_1 = require("./uniqueId"); +Object.defineProperty(exports, "UniqueId", { enumerable: true, get: function () { return uniqueId_1.UniqueId; } }); +__exportStar(require("./koalaKey"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/koalaKey.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/koalaKey.d.ts new file mode 100644 index 000000000..1b2e1e4ed --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/koalaKey.d.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import { int32 } from "#koalaui/compat"; +export type KoalaCallsiteKey = int32; +export declare class KoalaCallsiteKeys { + static readonly empty: KoalaCallsiteKey; + static combine(key1: KoalaCallsiteKey, key2: KoalaCallsiteKey): KoalaCallsiteKey; + static asString(key: KoalaCallsiteKey): string; +} +//# sourceMappingURL=koalaKey.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/koalaKey.js b/koala-wrapper/koalaui/common/dist/lib/src/koalaKey.js new file mode 100644 index 000000000..458a2c260 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/koalaKey.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.KoalaCallsiteKeys = void 0; +class KoalaCallsiteKeys { + static combine(key1, key2) { + return key1 + key2; + } + static asString(key) { + return new Number(key).toString(16); + } +} +exports.KoalaCallsiteKeys = KoalaCallsiteKeys; +KoalaCallsiteKeys.empty = 0; +//# sourceMappingURL=koalaKey.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/math.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/math.d.ts new file mode 100644 index 000000000..f114cb459 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/math.d.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float64 } from "#koalaui/compat"; +/** + * Computes the linear interpolation between `source` and `target` based on `weight`. + * + * @param weight - interpolation factor in the range [0..1] + * @param source - a value corresponding to weight 0 + * @param target - a value corresponding to weight 1 + * @returns interpolated value + */ +export declare function lerp(weight: float64, source: float64, target: float64): float64; +/** + * Clamps a {@link value} within the specified range. + * + * @param value - a value to clamp + * @param min - the lower boundary of the range + * @param max - the upper boundary of the range + * @returns `min` if `value` is less than `min`, + * `max` if `value` is greater than `max`, + * `value` otherwise + */ +export declare function clamp(value: float64, min: float64, max: float64): float64; +/** + * Calculates the difference between the argument and + * the largest (closest to positive infinity) integer value + * that is less than or equal to the argument. + * + * @param value a floating-point value to process + * @returns a floor modulus of the given value in the range [0..1) + */ +export declare function modulo(value: float64): float64; +/** + * @param str a string to parse + * @param name a name for error message + * @param verify whether to verify parsing validity + * @returns a floating-point number + * @throws Error if `str` cannot be parsed + */ +export declare function parseNumber(str: string, name?: string, verify?: boolean): float64; +/** + * An ArkTS-compliant replacement for {@link isFinite}. + */ +export declare function isFiniteNumber(number: float64): boolean; +export declare function getDistancePx(startX: float64, startY: float64, endX: float64, endY: float64): float64; +//# sourceMappingURL=math.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/math.js b/koala-wrapper/koalaui/common/dist/lib/src/math.js new file mode 100644 index 000000000..474003ae9 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/math.js @@ -0,0 +1,100 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDistancePx = exports.isFiniteNumber = exports.parseNumber = exports.modulo = exports.clamp = exports.lerp = void 0; +const compat_1 = require("#koalaui/compat"); +/** + * Computes the linear interpolation between `source` and `target` based on `weight`. + * + * @param weight - interpolation factor in the range [0..1] + * @param source - a value corresponding to weight 0 + * @param target - a value corresponding to weight 1 + * @returns interpolated value + */ +function lerp(weight, source, target) { + return source * (1.0 - weight) + target * weight; +} +exports.lerp = lerp; +/** + * Clamps a {@link value} within the specified range. + * + * @param value - a value to clamp + * @param min - the lower boundary of the range + * @param max - the upper boundary of the range + * @returns `min` if `value` is less than `min`, + * `max` if `value` is greater than `max`, + * `value` otherwise + */ +function clamp(value, min, max) { + return value <= min ? min : value >= max ? max : value; +} +exports.clamp = clamp; +/** + * Calculates the difference between the argument and + * the largest (closest to positive infinity) integer value + * that is less than or equal to the argument. + * + * @param value a floating-point value to process + * @returns a floor modulus of the given value in the range [0..1) + */ +function modulo(value) { + // The casts below are needed since floor returns double in ArkTS + const modulo = value - Math.floor(value); + return (modulo < 1.0) ? modulo : 0.0; +} +exports.modulo = modulo; +/** + * @param str a string to parse + * @param name a name for error message + * @param verify whether to verify parsing validity + * @returns a floating-point number + * @throws Error if `str` cannot be parsed + */ +function parseNumber(str, name = "number", verify = false) { + if (str != "") { // do not parse empty string to 0 + // ArkTS does not support NaN, isNaN, parseFloat + const value = (0, compat_1.asFloat64)(str); + if (verify) { + const reverseStr = (0, compat_1.asString)(value); + if (reverseStr !== undefined && (reverseStr === null || reverseStr === void 0 ? void 0 : reverseStr.length) == str.length && reverseStr == str) { + return value; + } + } + else { + return value; + } + } + throw new Error(`cannot parse ${name}: "${str}"`); +} +exports.parseNumber = parseNumber; +/** + * An ArkTS-compliant replacement for {@link isFinite}. + */ +function isFiniteNumber(number) { + // With Node.js: + // isFiniteNumber(Number.NEGATIVE_INFINITY) == false + // isFiniteNumber(Number.POSITIVE_INFINITY) == false + // isFiniteNumber(NaN) == false + return number >= Number.MIN_SAFE_INTEGER && number <= Number.MAX_SAFE_INTEGER; +} +exports.isFiniteNumber = isFiniteNumber; +function getDistancePx(startX, startY, endX, endY) { + const cathetA = Math.abs(endX - startX); + const cathetB = Math.abs(endY - startY); + return Math.sqrt(cathetA * cathetA + cathetB * cathetB); +} +exports.getDistancePx = getDistancePx; +//# sourceMappingURL=math.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/sha1.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/sha1.d.ts new file mode 100644 index 000000000..7efad4ed5 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/sha1.d.ts @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/compat"; +export declare function createSha1(): SHA1Hash; +export declare class SHA1Hash { + private A; + private B; + private C; + private D; + private E; + private readonly _byte; + private readonly _word; + private _size; + private _sp; + constructor(); + updateString(data: string, encoding?: string): SHA1Hash; + updateInt32(data: int32): SHA1Hash; + update(data: Int32Array | Float32Array | Uint32Array | Uint8Array): SHA1Hash; + private _uint8; + private _utf8; + private _int32; + digest(encoding?: string): Uint8Array | string; + private _hex; + private _bin; +} +//# sourceMappingURL=sha1.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/sha1.js b/koala-wrapper/koalaui/common/dist/lib/src/sha1.js new file mode 100644 index 000000000..597c33707 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/sha1.js @@ -0,0 +1,311 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SHA1Hash = exports.createSha1 = void 0; +const compat_1 = require("#koalaui/compat"); +const K = [ + (0x5a827999 | 0), + (0x6ed9eba1 | 0), + (0x8f1bbcdc | 0), + (0xca62c1d6 | 0), +]; +const inputBytes = 64; +const inputWords = inputBytes / 4; +const highIndex = inputWords - 2; +const lowIndex = inputWords - 1; +const workWords = 80; +const allocBytes = 80; +const allocWords = allocBytes / 4; +const allocTotal = allocBytes * 100; +function createSha1() { + return new SHA1Hash(); +} +exports.createSha1 = createSha1; +class SHA1Hash { + constructor() { + this.A = (0x67452301 | 0); + this.B = (0xefcdab89 | 0); + this.C = (0x98badcfe | 0); + this.D = (0x10325476 | 0); + this.E = (0xc3d2e1f0 | 0); + this._size = 0; + this._sp = 0; // surrogate pair + if (!sharedBuffer || sharedOffset >= allocTotal) { + sharedBuffer = new ArrayBuffer(allocTotal); + sharedOffset = 0; + } + this._byte = new Uint8Array(sharedBuffer, sharedOffset, allocBytes); + this._word = new Int32Array(sharedBuffer, sharedOffset, allocWords); + sharedOffset += allocBytes; + } + updateString(data, encoding) { + return this._utf8(data); + } + updateInt32(data) { + const buffer = new Int32Array(1); + buffer[0] = data; + return this.update(buffer); + } + update(data) { + if (data == null) { + throw new TypeError("SHA1Hash expected non-null data: "); + } + let byteOffset = 0; + let length = 0; + let buffer = undefined; + // TODO: an attempt to wrie this in a generic form causes + // es2panda to segfault. + if (data instanceof Int32Array) { + byteOffset = data.byteOffset; + length = data.byteLength; + buffer = data.buffer; + } + else if (data instanceof Uint32Array) { + byteOffset = data.byteOffset; + length = data.byteLength; + buffer = data.buffer; + } + else if (data instanceof Float32Array) { + byteOffset = data.byteOffset; + length = data.byteLength; + buffer = data.buffer; + } + else if (data instanceof Uint8Array) { + byteOffset = data.byteOffset; + length = data.byteLength; + buffer = data.buffer; + } + let blocks = ((length / inputBytes) | 0); + let offset = 0; + // longer than 1 block + if ((blocks != 0) && !(byteOffset & 3) && !(this._size % inputBytes)) { + const block = new Int32Array(buffer, byteOffset, blocks * inputWords); + while (blocks--) { + this._int32(block, offset >> 2); + offset += inputBytes; + } + this._size += offset; + } + // data: TypedArray | DataView + const BYTES_PER_ELEMENT = data.BYTES_PER_ELEMENT; + if ((BYTES_PER_ELEMENT != 1) && buffer != undefined) { + const rest = new Uint8Array(buffer, byteOffset + offset, length - offset); + return this._uint8(rest); + } + // no more bytes + if (offset == length) + return this; + return this._uint8(new Uint8Array(buffer), offset); + } + _uint8(data, offset) { + const _byte = this._byte; + const _word = this._word; + const length = data.length; + offset = ((offset !== null && offset !== void 0 ? offset : 0) | 0); + while (offset < length) { + const start = this._size % inputBytes; + let index = start; + while (offset < length && index < inputBytes) { + _byte[index++] = data[offset++]; + } + if (index >= inputBytes) { + this._int32(_word); + } + this._size += index - start; + } + return this; + } + _utf8(text) { + const _byte = this._byte; + const _word = this._word; + const length = text.length; + let surrogate = this._sp; + for (let offset = 0; offset < length;) { + const start = this._size % inputBytes; + let index = start; + while (offset < length && index < inputBytes) { + let code = text.charCodeAt(offset++) | 0; + if (code < 0x80) { + // ASCII characters + _byte[index++] = code; + } + else if (code < 0x800) { + // 2 bytes + _byte[index++] = 0xC0 | (code >>> 6); + _byte[index++] = 0x80 | (code & 0x3F); + } + else if (code < 0xD800 || code > 0xDFFF) { + // 3 bytes + _byte[index++] = 0xE0 | (code >>> 12); + _byte[index++] = 0x80 | ((code >>> 6) & 0x3F); + _byte[index++] = 0x80 | (code & 0x3F); + } + else if (surrogate) { + // 4 bytes - surrogate pair + code = ((surrogate & 0x3FF) << 10) + (code & 0x3FF) + 0x10000; + _byte[index++] = 0xF0 | (code >>> 18); + _byte[index++] = 0x80 | ((code >>> 12) & 0x3F); + _byte[index++] = 0x80 | ((code >>> 6) & 0x3F); + _byte[index++] = 0x80 | (code & 0x3F); + surrogate = 0; + } + else { + surrogate = code; + } + } + if (index >= inputBytes) { + this._int32(_word); + _word[0] = _word[inputWords]; + } + this._size += index - start; + } + this._sp = surrogate; + return this; + } + _int32(data, offset) { + let A = this.A; + let B = this.B; + let C = this.C; + let D = this.D; + let E = this.E; + let i = 0; + offset = ((offset !== null && offset !== void 0 ? offset : 0) | 0); + while (i < inputWords) { + W[i++] = swap32(data[offset++]); + } + for (i = inputWords; i < workWords; i++) { + W[i] = rotate1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + } + for (i = 0; i < workWords; i++) { + const S = (i / 20) | 0; + const T = (rotate5(A) + ft(S, B, C, D) + E + W[i] + K[S]) | 0; + E = D; + D = C; + C = rotate30(B); + B = A; + A = T; + } + this.A = (A + this.A) | 0; + this.B = (B + this.B) | 0; + this.C = (C + this.C) | 0; + this.D = (D + this.D) | 0; + this.E = (E + this.E) | 0; + } + // digest(): Uint8Array + // digest(encoding: string): string + digest(encoding) { + const _byte = this._byte; + const _word = this._word; + let i = (this._size % inputBytes) | 0; + _byte[i++] = 0x80; + // pad 0 for current word + while (i & 3) { + _byte[i++] = 0; + } + i >>= 2; + if (i > highIndex) { + while (i < inputWords) { + _word[i++] = 0; + } + i = 0; + this._int32(_word); + } + // pad 0 for rest words + while (i < inputWords) { + _word[i++] = 0; + } + // input size + const bits64 = this._size * 8; + const low32 = ((bits64 & 0xffffffff) >>> 0); + const high32 = ((bits64 - low32) / 0x100000000); + if (high32) + _word[highIndex] = swap32(high32); + if (low32) + _word[lowIndex] = swap32(low32); + this._int32(_word); + return (encoding === "hex") ? this._hex() : this._bin(); + } + _hex() { + let A = this.A; + let B = this.B; + let C = this.C; + let D = this.D; + let E = this.E; + return hex32Str(A, B, C, D, E); + } + _bin() { + let A = this.A; + let B = this.B; + let C = this.C; + let D = this.D; + let E = this.E; + const _byte = this._byte; + const _word = this._word; + _word[0] = swap32(A); + _word[1] = swap32(B); + _word[2] = swap32(C); + _word[3] = swap32(D); + _word[4] = swap32(E); + return _byte.slice(0, 20); + } +} +exports.SHA1Hash = SHA1Hash; +const W = new Int32Array(workWords); +let sharedBuffer; +let sharedOffset = 0; +const swapLE = ((c) => (((c << 24) & 0xff000000) | ((c << 8) & 0xff0000) | ((c >> 8) & 0xff00) | ((c >> 24) & 0xff))); +const swapBE = ((c) => c); +const swap32 = isBE() ? swapBE : swapLE; +const rotate1 = (num) => (num << 1) | (num >>> 31); +const rotate5 = (num) => (num << 5) | (num >>> 27); +const rotate30 = (num) => (num << 30) | (num >>> 2); +function isBE() { + let a16 = new Uint16Array(1); + a16[0] = 0xFEFF; + let a8 = new Uint8Array(a16.buffer); + return a8[0] == 0xFE; // BOM +} +function ft(s, b, c, d) { + if (s == 0) + return (b & c) | ((~b) & d); + if (s == 2) + return (b & c) | (b & d) | (c & d); + return b ^ c ^ d; +} +const hex32Decoder = new compat_1.CustomTextDecoder(); +const hex32DecodeBuffer = new Uint8Array(40); +function hex32Str(A, B, C, D, E) { + writeIntAsHexUTF8(A, hex32DecodeBuffer, 0); + writeIntAsHexUTF8(B, hex32DecodeBuffer, 8); + writeIntAsHexUTF8(C, hex32DecodeBuffer, 16); + writeIntAsHexUTF8(D, hex32DecodeBuffer, 24); + writeIntAsHexUTF8(E, hex32DecodeBuffer, 32); + return hex32Decoder.decode(hex32DecodeBuffer); +} +function writeIntAsHexUTF8(value, buffer, byteOffset) { + buffer[byteOffset++] = nibbleToHexCode((value >> 28) & 0xF); + buffer[byteOffset++] = nibbleToHexCode((value >> 24) & 0xF); + buffer[byteOffset++] = nibbleToHexCode((value >> 20) & 0xF); + buffer[byteOffset++] = nibbleToHexCode((value >> 16) & 0xF); + buffer[byteOffset++] = nibbleToHexCode((value >> 12) & 0xF); + buffer[byteOffset++] = nibbleToHexCode((value >> 8) & 0xF); + buffer[byteOffset++] = nibbleToHexCode((value >> 4) & 0xF); + buffer[byteOffset++] = nibbleToHexCode((value >> 0) & 0xF); +} +function nibbleToHexCode(nibble) { + return nibble > 9 ? nibble + 87 : nibble + 48; +} +//# sourceMappingURL=sha1.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/stringUtils.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/stringUtils.d.ts new file mode 100644 index 000000000..d8101efbf --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/stringUtils.d.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/compat"; +/** + * Computes a hash code from the string {@link value}. + */ +export declare function hashCodeFromString(value: string): int32; +//# sourceMappingURL=stringUtils.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/stringUtils.js b/koala-wrapper/koalaui/common/dist/lib/src/stringUtils.js new file mode 100644 index 000000000..06850d000 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/stringUtils.js @@ -0,0 +1,30 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hashCodeFromString = void 0; +/** + * Computes a hash code from the string {@link value}. + */ +function hashCodeFromString(value) { + let hash = 5381; + for (let i = 0; i < value.length; i++) { + hash = (hash * 33) ^ value.charCodeAt(i); + hash |= 0; + } + return hash; +} +exports.hashCodeFromString = hashCodeFromString; +//# sourceMappingURL=stringUtils.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/uniqueId.d.ts b/koala-wrapper/koalaui/common/dist/lib/src/uniqueId.d.ts new file mode 100644 index 000000000..0d00f1dd1 --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/uniqueId.d.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/compat"; +export declare class UniqueId { + private sha; + addString(data: string): UniqueId; + addI32(data: int32): UniqueId; + addF32Array(data: Float32Array): UniqueId; + addI32Array(data: Int32Array): UniqueId; + addU32Array(data: Uint32Array): UniqueId; + addU8Array(data: Uint8Array): UniqueId; + addPtr(data: Uint32Array | number): UniqueId; + compute(): string; +} +//# sourceMappingURL=uniqueId.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/dist/lib/src/uniqueId.js b/koala-wrapper/koalaui/common/dist/lib/src/uniqueId.js new file mode 100644 index 000000000..6269d042c --- /dev/null +++ b/koala-wrapper/koalaui/common/dist/lib/src/uniqueId.js @@ -0,0 +1,58 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UniqueId = void 0; +const sha1_1 = require("./sha1"); +class UniqueId { + constructor() { + this.sha = (0, sha1_1.createSha1)(); + } + addString(data) { + this.sha.updateString(data); + return this; + } + addI32(data) { + this.sha.updateInt32(data); + return this; + } + addF32Array(data) { + this.sha.update(data); + return this; + } + addI32Array(data) { + this.sha.update(data); + return this; + } + addU32Array(data) { + this.sha.update(data); + return this; + } + addU8Array(data) { + this.sha.update(data); + return this; + } + addPtr(data) { + if (data instanceof Uint32Array) { + return this.addU32Array(data); + } + return this.addI32(data); + } + compute() { + return this.sha.digest("hex"); + } +} +exports.UniqueId = UniqueId; +//# sourceMappingURL=uniqueId.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/oh-package.json5 b/koala-wrapper/koalaui/common/oh-package.json5 new file mode 100644 index 000000000..a1d31c737 --- /dev/null +++ b/koala-wrapper/koalaui/common/oh-package.json5 @@ -0,0 +1,50 @@ +{ + "name": "@koalaui/common", + "version": "1.4.1+devel", + "description": "", + "main": "build/lib/src/index.js", + "types": "./index.d.ts", + "files": [ + "build/lib/**/*.js", + "build/lib/**/*.d.ts", + "build/bridges/ohos/**/*.js", + "build/bridges/ohos/**/*.d.ts" + ], + "exports": { + ".": "./build/lib/src/index.js", + "./golden": "./test/golden.js", + "./bridges": { + "ark": "./build/bridges/ohos/index.js", + "default": null + } + }, + "typesVersions": { + "*": { + "bridges": ["build/bridges/ohos/index.d.ts"], + "*": ["build/lib/src/*", "build/lib/typescript/*"] + } + }, + "scripts": { + "compile": "tsc -b .", + "clean": "rimraf build dist", + "test": "mocha", + "test:coverage": "nyc mocha", + "compile:arkts": "bash ../tools/panda/arkts/arktsc --arktsconfig arktsconfig.json --ets-module" + }, + "keywords": [], + "dependencies": { + "@koalaui/compat": "../compat" + }, + "devDependencies": { + "@ohos/hypium": "^1.0.5", + "@types/chai": "^4.3.1", + "@types/mocha": "^9.1.0", + "@typescript-eslint/eslint-plugin": "^5.20.0", + "@typescript-eslint/parser": "^5.20.0", + "chai": "^4.3.6", + "eslint": "^8.13.0", + "eslint-plugin-unused-imports": "^2.0.0", + "mocha": "^9.2.2", + "source-map-support": "^0.5.21" + } +} diff --git a/koala-wrapper/koalaui/common/src/Errors.ts b/koala-wrapper/koalaui/common/src/Errors.ts new file mode 100644 index 000000000..d57ea750a --- /dev/null +++ b/koala-wrapper/koalaui/common/src/Errors.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022-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. + */ + + +// "assert" is a reserved keyword in ArkTS :-( +export function assertion(condition: boolean, message: string) { + if (!condition) throw new Error(message) +} + +// The unknonwn type support in ArkTS compiler is not ready yet. +// When it is ready move from +// ensure(value, message) +// to +// value ?? error(message) +// which is much more readable +export function ensure(value: T|undefined, message: string): T { + if (value == undefined) throw new Error(message) + return value as T +} diff --git a/koala-wrapper/koalaui/common/src/Finalization.ts b/koala-wrapper/koalaui/common/src/Finalization.ts new file mode 100644 index 000000000..30be27994 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/Finalization.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { finalizerRegister as finalizerRegisterCompat, finalizerUnregister as finalizerUnregisterCompat, Thunk } from "@koalaui/compat" + +export { Thunk } from "@koalaui/compat" + +export function finalizerRegister(target: object, thunk: Thunk) { + finalizerRegisterCompat(target, thunk) +} + +export function finalizerRegisterWithCleaner(target: object, cleaner: () => void) { + finalizerRegisterCompat(target, new CleanerThunk(cleaner)) +} + +export function finalizerUnregister(target: object) { + finalizerUnregisterCompat(target) +} + +class CleanerThunk implements Thunk { + private cleaner: () => void + constructor(cleaner: () => void) { + this.cleaner = cleaner + } + clean() { + this.cleaner() + } +} diff --git a/koala-wrapper/koalaui/common/src/KoalaProfiler.ts b/koala-wrapper/koalaui/common/src/KoalaProfiler.ts new file mode 100644 index 000000000..0e8f704f0 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/KoalaProfiler.ts @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/compat" + +/** + * Adds statistics for constructing/disposing of the TreeNode instances. + * It is disabled by default because collecting such data affects performance. + */ +const DEBUG_WITH_NODE_STATS = false + +export class KoalaProfiler { + private static readonly map = DEBUG_WITH_NODE_STATS + ? new Map>() + : undefined + + static nodeCreated(nodeType: int32, node: Object) { + if (KoalaProfiler.map === undefined) return + let set = KoalaProfiler.map!.get(nodeType) + if (set === undefined) { + set = new Set() + KoalaProfiler.map!.set(nodeType, set) + } + set.add(node) + } + + static nodeDisposed(nodeType: int32, node: Object) { + if (KoalaProfiler.map === undefined) return + let set = KoalaProfiler.map!.get(nodeType) + if (set === undefined) throw new Error("node never existed") + if (!set.delete(node)) console.log("node is already disposed") + } + + public static counters: KoalaProfiler | undefined = undefined + + private invalidations = 0 + private computes = 0 + private builds = 0 + private nodes = 0 + private realDraws = 0 + private cachedDraws = 0 + private measures = 0 + private layouts = 0 + private frames = 0 + private lastTime = 0.0 + private lastFPS = 0 + private updateEnterTime = 0.0 + private updateExitTime = 0.0 + private updateTime = 0.0 + private buildEnterTime = 0.0 + private buildExitTime = 0.0 + private buildTime = 0.0 + private layoutEnterTime = 0.0 + private layoutExitTime = 0.0 + private layoutTime = 0.0 + private drawEnterTime = 0.0 + private drawExitTime = 0.0 + private drawTime = 0.0 + private updatableStates = 0 + private mutableStates = 0 + private computableValues = 0 + + static enable() { + KoalaProfiler.counters = new KoalaProfiler() + } + + static disable() { + KoalaProfiler.counters = undefined + } + + static enabled(): boolean { + return KoalaProfiler.counters != undefined + } + + reset() { + this.invalidations = 0 + this.computes = 0 + this.builds = 0 + this.nodes = 0 + this.realDraws = 0 + this.cachedDraws = 0 + this.layouts = 0 + this.measures = 0 + this.updateEnterTime = 0 + this.updateExitTime = 0 + this.updatableStates = 0 + this.mutableStates = 0 + this.computableValues = 0 + } + + report() { + console.log(this.getReport()) + } + + getReport(): string { + const updateTime = Math.round(1000 * (this.updateExitTime - this.updateEnterTime)) + const buildTime = Math.round(1000 * (this.buildExitTime - this.buildEnterTime)) + const layoutTime = Math.round(1000 * (this.layoutExitTime - this.layoutEnterTime)) + const drawTime = Math.round(1000 * (this.drawExitTime - this.drawEnterTime)) + if (this.updateTime < updateTime) this.updateTime = updateTime + if (this.buildTime < buildTime) this.buildTime = buildTime + if (this.layoutTime < layoutTime) this.layoutTime = layoutTime + if (this.drawTime < drawTime) this.drawTime = drawTime + + // TODO: OHOS does not properly handle \n in template literals + const array = Array.of( + `invalidations: ${this.invalidations}`, + `modified states: ${this.mutableStates}/${this.updatableStates} + ${this.computableValues}`, + `update states (mks): ${this.updateTime} / ${updateTime}`, + `build root node (mks): ${this.buildTime} / ${buildTime}`, + `layout view (mks): ${this.layoutTime} / ${layoutTime}`, + `draw view (mks): ${this.drawTime} / ${drawTime}`, + `computes: ${this.computes}`, + `builds: ${this.builds}`, + `nodes: ${this.nodes}`, + `realDraws: ${this.realDraws}`, + `cachedDraws: ${this.cachedDraws}`, + `measures: ${this.measures}`, + `layouts: ${this.layouts}`, + `FPS: ${this.lastFPS}`, + ) + KoalaProfiler.map?.forEach((set:Set, kind:int32) => { + if (set.size > 0) array.push(kind + ":" + set.size) + }) + return array.join("\n") + } + + invalidation() { this.invalidations++ } + compute() { this.computes++ } + build() { this.builds++ } + node() { this.nodes++ } + realDraw() { this.realDraws++ } + cachedDraw() { this.cachedDraws++ } + layout() { this.layouts++ } + measure() { this.measures++ } + frame(ms: number) { + if (ms - this.lastTime <= 1000) { + this.frames++ + } else { + this.lastFPS = Math.round(this.frames * 1000 / (ms - this.lastTime)) as int32 + this.frames = 1 + this.lastTime = ms + } + } + buildRootEnter() { + this.buildEnterTime = Date.now() + } + buildRootExit() { + this.buildExitTime = Date.now() + } + layoutEnter() { + this.layoutEnterTime = Date.now() + } + layoutExit() { + this.layoutExitTime = Date.now() + } + drawEnter() { + this.drawEnterTime = Date.now() + } + drawExit() { + this.drawExitTime = Date.now() + } + updateSnapshotEnter() { + this.updateEnterTime = Date.now() + } + updateSnapshotExit() { + this.updateExitTime = Date.now() + } + updateSnapshot(modified: int32, all?: int32) { + if (all === undefined) { + this.computableValues = modified - this.mutableStates + + } else { + this.mutableStates = modified + this.updatableStates = all + } + } +} diff --git a/koala-wrapper/koalaui/common/src/LifecycleEvent.ts b/koala-wrapper/koalaui/common/src/LifecycleEvent.ts new file mode 100644 index 000000000..aa67f2312 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/LifecycleEvent.ts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022-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. + */ + +export enum LifecycleEventKind { + SHOW_FRAME, + HIDE_FRAME, + CLOSE_FRAME, + ON_APPEAR, + ON_DISAPPEAR, + SHOW_COMPONENT, + HIDE_COMPONENT, + BACK, + FOCUS_FRAME, + UNFOCUS_FRAME +} + +export class LifecycleEvent { + kind: LifecycleEventKind + constructor(kind: LifecycleEventKind) { + this.kind = kind + } +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/src/MarkableQueue.ts b/koala-wrapper/koalaui/common/src/MarkableQueue.ts new file mode 100644 index 000000000..6d6efa518 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/MarkableQueue.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AtomicRef } from "@koalaui/compat" + +/** + * A markable queue that allows to accumulate callbacks and to call them to the latest set marker. + */ +export interface MarkableQueue { + /** Sets the new marker to the queue. */ + setMarker(): void + /** Adds the given callback to the queue. */ + addCallback(callback: () => void): void + /** Calls all accumulated callbacks to the latest set marker. */ + callCallbacks(): void + /** Clears the queue. */ + clear(): void +} + +/** + * Creates a new markable queue to safely process callbacks across several threads or tasks. + * @param reversed - `true` changes the order of calling callbacks + */ +export function markableQueue(reversed: boolean = false): MarkableQueue { + return reversed ? new ReversedQueue() : new DefaultQueue() +} + +class DefaultQueue implements MarkableQueue { + private readonly last = new AtomicRef(new Block()) + private readonly first = new AtomicRef(this.last.value) + private readonly marker = new AtomicRef(undefined) + + setMarker(): void { + const marker = new Block() + this.last.getAndSet(marker).next.value = marker + this.marker.value = marker + } + + addCallback(callback: () => void): void { + const block = new Block(callback) + this.last.getAndSet(block).next.value = block + } + + callCallbacks(): void { + const marker = this.marker.getAndSet(undefined) + if (marker) { + let block = this.first.getAndSet(marker) + while (block !== marker) { + block.callback?.() + block = block.next.value! + } + } + } + + clear(): void { + this.last.value = this.first.value + this.marker.value = undefined + } +} + +class ReversedQueue implements MarkableQueue { + private readonly last = new AtomicRef(undefined) + private readonly marker = new AtomicRef(undefined) + + setMarker(): void { + const marker = new Block() + marker.next.value = this.last.getAndSet(marker) + this.marker.value = marker + } + + addCallback(callback: () => void): void { + const block = new Block(callback) + block.next.value = this.last.getAndSet(block) + } + + callCallbacks(): void { + const marker = this.marker.getAndSet(undefined) + if (marker) { + let block = marker.next.getAndSet(undefined) + while (block) { + block!.callback?.() + block = block!.next.value + } + } + } + + clear(): void { + this.last.value = undefined + this.marker.value = undefined + } +} + +class Block { + readonly next = new AtomicRef(undefined) + readonly callback: (() => void) | undefined + + constructor(callback?: () => void) { + this.callback = callback + } +} diff --git a/koala-wrapper/koalaui/common/src/Matrix33.ts b/koala-wrapper/koalaui/common/src/Matrix33.ts new file mode 100644 index 000000000..978e3a907 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/Matrix33.ts @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Array_from_number, float32, float64 } from "@koalaui/compat" + +export function mat33(array?: Float32Array): Matrix33 { + return (array == undefined) ? new Matrix33 () : new Matrix33(array) +} + +const tolerance: float32 = (1.0 / (1 << 12)) + +export class Matrix33 { + public readonly array: Float32Array + constructor (array: Float32Array = new Float32Array(Array_from_number([ + 1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0 + ]))) { + this.array = array.slice() + } + + static zero(): Matrix33 { + return new Matrix33(new Float32Array(Array_from_number([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]))) + } + + static makeTranslate(dx: float32, dy: float32): Matrix33 { + return new Matrix33(new Float32Array(Array_from_number([1.0, 0.0, dx as float64, 0.0, 1.0, dy as float64, 0.0, 0.0, 1.0]))) + } + + static makeScale(dx: float32, dy: float32 = dx): Matrix33 { + return new Matrix33(new Float32Array(Array_from_number([dx as float64, 0.0, 0.0, 0.0, dy as float64, 0.0, 0.0, 0.0, 1.0]))) + } + + static makeRotate(degrees: float32, pivotX?: float32, pivotY?: float32): Matrix33 { + let rads = degrees * Math.PI / 180 + let cos = Math.cos(rads) + let sin = Math.sin(rads) + if (Math.abs(sin) <= tolerance) sin = 0.0 + if (Math.abs(cos) <= tolerance) cos = 0.0 + if (pivotX !== undefined && pivotY != undefined) { + let dx = pivotX - pivotX * cos + pivotY * sin + let dy = pivotY - pivotY * cos - pivotX * sin + return new Matrix33(new Float32Array(Array_from_number([cos, -sin, dx, sin, cos, dy, 0.0, 0.0, 1.0]))) + } else { + return new Matrix33(new Float32Array(Array_from_number([cos, -sin, 0.0, sin, cos, 0.0, 0.0, 0.0, 1.0]))) + } + } + + static makeSkew(sx: float32, sy: float32): Matrix33 { + return new Matrix33(new Float32Array(Array_from_number([1.0, sx, 0.0, sy, 1.0, 0.0, 0.0, 0.0, 1.0]))) + } + + makeConcat(rhs: Matrix33): Matrix33 { + return new Matrix33(new Float32Array(Array_from_number([ + this.array[0] * rhs.array[0] + this.array[1] * rhs.array[3] + this.array[2] * rhs.array[6], + this.array[0] * rhs.array[1] + this.array[1] * rhs.array[4] + this.array[2] * rhs.array[7], + this.array[0] * rhs.array[2] + this.array[1] * rhs.array[5] + this.array[2] * rhs.array[8], + this.array[3] * rhs.array[0] + this.array[4] * rhs.array[3] + this.array[5] * rhs.array[6], + this.array[3] * rhs.array[1] + this.array[4] * rhs.array[4] + this.array[5] * rhs.array[7], + this.array[3] * rhs.array[2] + this.array[4] * rhs.array[5] + this.array[5] * rhs.array[8], + this.array[6] * rhs.array[0] + this.array[7] * rhs.array[3] + this.array[8] * rhs.array[6], + this.array[6] * rhs.array[1] + this.array[7] * rhs.array[4] + this.array[8] * rhs.array[7], + this.array[6] * rhs.array[2] + this.array[7] * rhs.array[5] + this.array[8] * rhs.array[8], + ]))) + } + + makeTranspose(): Matrix33{ + return new Matrix33(new Float32Array(Array_from_number([ + this.array[0], this.array[3], this.array[6], + this.array[1], this.array[4], this.array[7], + this.array[2], this.array[5], this.array[8] + ]))) + } +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/src/Matrix44.ts b/koala-wrapper/koalaui/common/src/Matrix44.ts new file mode 100644 index 000000000..163b53949 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/Matrix44.ts @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Array_from_number, float32 } from "@koalaui/compat" +import { Matrix33 } from "./Matrix33" +import { Point3 } from "./Point3" + + +export interface RotateOptions { + angle?: float32 + x?: float32 + y?: float32 + z?: float32 + pivotX?: float32 + pivotY?: float32 + pivotZ?: float32 +} + +export interface ScaleOptions { + x?: float32 + y?: float32 + z?: float32 + pivotX?: float32 + pivotY?: float32 + pivotZ?: float32 +} + +export interface TranslateOptions { + x?: float32 + y?: float32 + z?: float32 +} + +// TODO: this is because ArkTS doesn allow interface literal instances. +class TranslateOptionsImpl implements TranslateOptions { + _x: float32 | undefined + _y: float32 | undefined + _z: float32 | undefined + + get x(): float32 | undefined { return this._x } + get y(): float32 | undefined { return this._y } + get z(): float32 | undefined { return this._z } + + set x(x: float32 | undefined) { this._x = x } + set y(y: float32 | undefined) { this._y = y } + set z(z: float32 | undefined) { this._z = z } + + constructor( + x: float32 | undefined, + y: float32 | undefined, + z: float32 | undefined + ) { + this._x = x + this._y = y + this._z = z + } +} + +export function mat44(array?: Float32Array): Matrix44 { + return (array == undefined)? new Matrix44() : new Matrix44(array) +} +/** + * 4x4 matrix with right-handed coordinate system: + * +x goes to the right + * +y goes down + * +z goes into the screen (away from the viewer) + */ +export class Matrix44 { + public readonly array: Float32Array + constructor (array: Float32Array = new Float32Array(Array_from_number([ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + ]))) { + this.array = array.slice() + } + + public static identity(): Matrix44 { + return mat44() + } + + static zero(): Matrix44 { + return mat44(new Float32Array(Array_from_number([ + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + ]))) + } + + public static lookAt(eye: Point3, center: Point3, up: Point3): Matrix44 { + const f = center.subtract(eye).normalize() + const u = up.normalize() + const s = f.cross(u).normalize() + const sf = s.cross(f) + return new Matrix44(new Float32Array(Array_from_number([ + s.x, sf.x, -f.x, eye.x, + s.y, sf.y, -f.y, eye.y, + s.z, sf.z, -f.z, eye.z, + 0, 0, 0, 1, + ]))).invert() + } + + public static perspective(depth: float32): Matrix44 { + return new Matrix44(new Float32Array(Array_from_number([ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, -1.0 / depth, 1.0, + ]))) + } + + public static perspectiveFov(fov: float32, near: float32, far: float32): Matrix44 { + const denomInv = (far - near) + const halfAngle = fov * 0.5; + const cot = Math.cos(halfAngle) / Math.sin(halfAngle) + return new Matrix44(new Float32Array(Array_from_number([ + cot, 0.0, 0.0, 0.0, + 0.0, cot, 0.0, 0.0, + 0.0, 0.0, (far + near) * denomInv, 2 * far * near * denomInv, + 0.0, 0.0, -1.0, 0.0, + ]))) + } + + /** + * Returns new matrix, made from Matrix33. + * + * @param matrix - 3x3 matrix + * @returns the new instance of Matrix44 + * + */ + public static makeFromMatrix33(matrix: Matrix33): Matrix44{ + return new Matrix44(new Float32Array(Array_from_number([ + matrix.array[0], matrix.array[1], 0.0, matrix.array[2], + matrix.array[3], matrix.array[4], 0.0, matrix.array[5], + 0.0, 0.0, 1.0, 0.0, + matrix.array[6], matrix.array[7], 0.0, matrix.array[8] + ]))) + } + + /** + * Returns new 3x3 matrix, made from this matrix by dropping the third row and the third column. + * + * @returns the new instance of Matrix33 + * + */ + public asMatrix33(): Matrix33{ + return new Matrix33(new Float32Array(Array_from_number([ + this.array[0], this.array[1], this.array[3], + this.array[4], this.array[5], this.array[7], + this.array[12], this.array[13], this.array[15] + ]))) + } + + public copy(): Matrix44 { + return new Matrix44(new Float32Array(Array_from_number([ + this.array[0], this.array[1], this.array[2], this.array[3], + this.array[4], this.array[5], this.array[6], this.array[7], + this.array[8], this.array[9], this.array[10], this.array[11], + this.array[12], this.array[13], this.array[14], this.array[15] + ]))) + } + + concat(matrix: Matrix44): Matrix44 { + const result: Float32Array = new Float32Array(Array_from_number([ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ])) + for (let row = 0; row < 4; row++) { + for (let col = 0; col < 4; col++) { + let num: float32 = 0 + for (let k = 0; k < 4; k++) { + num += this.array[row * 4 + k] * matrix.array[col + 4 * k] + } + result[row * 4 + col] = num + } + } + for (let i = 0; i < this.array.length; i++) { + this.array[i] = result[i] + } + return this + } + + public scale(options: ScaleOptions): Matrix44 { + const scaled = new Matrix44() + scaled.array[0] = options.x ?? 1.0 as float32 + scaled.array[5] = options.y ?? 1.0 as float32 + scaled.array[10] = options.z ?? 1.0 as float32 + + this.translate(new TranslateOptionsImpl( + -(options.pivotX ?? 0.0 as float32) * (options.x ?? 1.0 as float32) + (options.pivotX ?? 0.0 as float32), + -(options.pivotY ?? 0.0 as float32) * (options.y ?? 1.0 as float32) + (options.pivotY ?? 0.0 as float32), + undefined + )).concat(scaled) + + return this + } + + public rotate(options: RotateOptions): Matrix44 { + const translationToPivot = mat44().translate(new TranslateOptionsImpl( + (options.pivotX ?? 0.0 as float32), + (options.pivotY ?? 0.0 as float32), + (options.pivotZ ?? 0.0 as float32), + )) + const translationToBack = mat44().translate(new TranslateOptionsImpl( + -(options.pivotX ?? 0.0 as float32), + -(options.pivotY ?? 0.0 as float32), + -(options.pivotZ ?? 0.0 as float32), + )) + + const vec = new Point3(options.x ?? 0.0 as float32, options.y ?? 0.0 as float32, options.z ?? 0.0 as float32).normalize() + const rads = (options.angle ?? 0.0 as float32) * Math.PI / 180 + let c = Math.cos(rads) + let s = Math.sin(rads) + const tolerance = (1.0 / (1 << 12)) + if (Math.abs(s) <= tolerance) s = 0.0 + if (Math.abs(c) <= tolerance) c = 0.0 + let t = 1 - c + const x = vec.x + const y = vec.y + const z = vec.z + + const rotation = mat44() + rotation.array[0] = t * x * x + c + rotation.array[1] = t * x * y - s * z + rotation.array[2] = t * x * z + s * y + rotation.array[3] = 0 + rotation.array[4] = t * x * y + s * z + rotation.array[5] = t * y * y + c + rotation.array[6] = t * y * z - s * x + rotation.array[7] = 0 + rotation.array[8] = t * x * z - s * y + rotation.array[9] = t * y * z + s * x + rotation.array[10] = t * z * z + c + rotation.array[11] = 0 + rotation.array[12] = 0 + rotation.array[13] = 0 + rotation.array[14] = 0 + rotation.array[15] = 1 + + this.concat(translationToPivot).concat(rotation).concat(translationToBack) + + return this + } + + public translate(options: TranslateOptions): Matrix44 { + this.array[3] = options.x ?? 0.0 as float32 + this.array[7] = options.y ?? 0.0 as float32 + this.array[11] = options.z ?? 0.0 as float32 + return this + } + + public invert(): Matrix44 { + const result: Float32Array = new Float32Array(16) + + let a00 = this.array[0] + let a01 = this.array[1] + let a02 = this.array[2] + let a03 = this.array[3] + let a10 = this.array[4] + let a11 = this.array[5] + let a12 = this.array[6] + let a13 = this.array[7] + let a20 = this.array[8] + let a21 = this.array[9] + let a22 = this.array[10] + let a23 = this.array[11] + let a30 = this.array[12] + let a31 = this.array[13] + let a32 = this.array[14] + let a33 = this.array[15] + + let b00 = a00 * a11 - a01 * a10 + let b01 = a00 * a12 - a02 * a10 + let b02 = a00 * a13 - a03 * a10 + let b03 = a01 * a12 - a02 * a11 + let b04 = a01 * a13 - a03 * a11 + let b05 = a02 * a13 - a03 * a12 + let b06 = a20 * a31 - a21 * a30 + let b07 = a20 * a32 - a22 * a30 + let b08 = a20 * a33 - a23 * a30 + let b09 = a21 * a32 - a22 * a31 + let b10 = a21 * a33 - a23 * a31 + let b11 = a22 * a33 - a23 * a32 + + let determinant = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06 + let invdet = 1.0 / determinant + b00 *= invdet + b01 *= invdet + b02 *= invdet + b03 *= invdet + b04 *= invdet + b05 *= invdet + b06 *= invdet + b07 *= invdet + b08 *= invdet + b09 *= invdet + b10 *= invdet + b11 *= invdet + + result[0] = a11 * b11 - a12 * b10 + a13 * b09 + result[1] = a02 * b10 - a01 * b11 - a03 * b09 + result[2] = a31 * b05 - a32 * b04 + a33 * b03 + result[3] = a22 * b04 - a21 * b05 - a23 * b03 + result[4] = a12 * b08 - a10 * b11 - a13 * b07 + result[5] = a00 * b11 - a02 * b08 + a03 * b07 + result[6] = a32 * b02 - a30 * b05 - a33 * b01 + result[7] = a20 * b05 - a22 * b02 + a23 * b01 + result[8] = a10 * b10 - a11 * b08 + a13 * b06 + result[9] = a01 * b08 - a00 * b10 - a03 * b06 + result[10] = a30 * b04 - a31 * b02 + a33 * b00 + result[11] = a21 * b02 - a20 * b04 - a23 * b00 + result[12] = a11 * b07 - a10 * b09 - a12 * b06 + result[13] = a00 * b09 - a01 * b07 + a02 * b06 + result[14] = a31 * b01 - a30 * b03 - a32 * b00 + result[15] = a20 * b03 - a21 * b01 + a22 * b00 + + // If 1/det overflows to infinity (i.e. det is denormalized) or any of the inverted matrix + // values is non-finite, return zero to indicate a non-invertible matrix. + let prod = 0 + for (let i = 0; i < result.length; ++i) { + prod *= result[i] + } + // At this point, prod will either be NaN or 0 + // if prod is NaN, this check will return false + if (prod == 0) { + for (let i = 0; i < this.array.length; i++) { + this.array[i] = result[i] + } + } + return this + } + + public transpose(): Matrix44 { + const result: Float32Array = new Float32Array(16) + + result[0] = this.array[0] + result[1] = this.array[4] + result[2] = this.array[8] + result[3] = this.array[12] + result[4] = this.array[1] + result[5] = this.array[5] + result[6] = this.array[9] + result[7] = this.array[13] + result[8] = this.array[2] + result[9] = this.array[6] + result[10] = this.array[10] + result[11] = this.array[14] + result[12] = this.array[3] + result[13] = this.array[7] + result[14] = this.array[11] + result[15] = this.array[15] + + for (let i = 0; i < this.array.length; i++) { + this.array[i] = result[i] + } + + return this + } + + public skew(x?: float32, y?: float32): Matrix44 { + this.array[1] += x ?? 0.0 as float32 + this.array[4] += y ?? 0.0 as float32 + return this + } +} diff --git a/koala-wrapper/koalaui/common/src/PerfProbe.ts b/koala-wrapper/koalaui/common/src/PerfProbe.ts new file mode 100644 index 000000000..063d4d590 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/PerfProbe.ts @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float64, int32, timeNow, numberToFixed } from "@koalaui/compat" + +/** + * A probe to measure performance. + * + * A probe can measure performance of any activity which has an entry and an exit points. + * Such activity can be a method call, or a sequence of actions, possibly asynchronous. + * + * A probe which has been entered and exited is considered a performed probe (see {@link MainPerfProbe.probePerformed}). + * A probe can be entered recursively. When all the recursive calls exits the probe becomes a performed probe. + * + * All performing probes form a hierarchy which is rooted at the main probe (see {@link enterMainPerfProbe}). + * A last started probe (see {@link MainPerfProbe.enterProbe}) which has not yet performed becomes a parent + * for the next started probe. It's the responsibility of the API caller to keep this parent-child relationship valid, + * that is: a child probe should exit before its parent probe exits. + * + * Statistics gathered by a probe: + * - call count + * - recursive call count + * - total time and percentage relative to the main (root) probe + */ +export interface PerfProbe { + /** + * The name of the probe. + */ + readonly name: string + + /** + * Whether this is a dummy probe which does not measure (a noop). + * + * @see MainPerfProbe.getProbe + */ + readonly dummy: boolean + + /** + * Exists the probe. + * + * @param log log the gathered statistics. + * @see MainPerfProbe.enterProbe + */ + exit(log: boolean|undefined): void + + /** + * Cancels measuring the probe and its children probes. + */ + cancel(): void + + /** + * User-defined data associated with the probe. + */ + userData: string | undefined + + /** + * Whether the probe was canceled. + */ + readonly canceled: boolean +} + +/** + * The main (root) {@link PerfProbe}. + * + * This probe is used to enter the main activity. + * + * Calling {@link PerfProbe.cancel} removes the main probe and disposes all its resources. + * + * Calling {@link PerfProbe.exit} exits the main probe, cancels it and when the log option is provided + * logs the gathered statistics. + * + * @see enterMainPerfProbe + * @see getMainPerfProbe + */ +export interface MainPerfProbe extends PerfProbe { + /** + * Enters a child probe referenced by the {@link name} and measures it. + * If the probe does not exist, returns a dummy instance. + * + * If the probe already performs a recursive call is counted. + * + * @see PerfProbe.exit + * @see exitProbe + */ + enterProbe(name: string): PerfProbe + + /** + * Exits a child probe referenced by the {@link name}. + * If the probe does not exist, returns a dummy instance. + * + * This is an equivalent of calling {@link getProbe} and then {@link PerfProbe.exit}. + */ + exitProbe(name: string): PerfProbe + + /** + * Returns the child probe referenced by the {@link name} if it exists, + * otherwise a dummy instance. + * + * @see PerfProbe.dummy + */ + getProbe(name: string): PerfProbe + + /** + * Performs the {@link func} of a child probe referenced by the {@link name} and measures it. + * + * This is an equivalent of calling {@link enterProbe} and then {@link exitProbe}. + * + * If the probe already performs a recursive call is counted. + */ + performProbe(name: string, func: () => T): T + + /** + * Returns true if the probe referenced by the {@link name} has been performed + * (entered and exited all the recursive calls). + */ + probePerformed(name: string): boolean +} + +/** + * Creates a {@link MainPerfProbe} instance with the {@link name} and enters its main probe. + * + * If a {@link MainPerfProbe} with this {@link name} already exists then it is canceled and the new one is created. + * + * Exit it with {@link MainPerfProbe.exit}. + */ +export function enterMainPerfProbe(name: string): MainPerfProbe { + return new MainPerfProbeImpl(name) +} + +/** + * Returns {@link MainPerfProbe} instance with the {@link name} if it exists, + * otherwise a dummy instance. + * + * @see MainPerfProbe.dummy + */ +export function getMainPerfProbe(name: string): MainPerfProbe { + const instance = MainPerfProbeImpl.mainProbes.get(name) + return instance ? instance : MainPerfProbeImpl.DUMMY +} + +class DummyPerfProbe implements MainPerfProbe { + get name(): string { return "dummy" } + get dummy(): boolean { return true } + exit(log: boolean|undefined): void {} + cancel () {} + get canceled(): boolean { return false } + enterProbe(name: string): PerfProbe { return PerfProbeImpl.DUMMY } + exitProbe (name: string): PerfProbe { return PerfProbeImpl.DUMMY } + getProbe(name: string): PerfProbe { return PerfProbeImpl.DUMMY } + //performProbe: (_: string, func: () => T) => func(), + performProbe(name: string, func: () => T): T { return func() } + probePerformed(_: string): boolean { return false } + + get userData(): string | undefined { + return undefined + } + set userData(_: string | undefined) {} +} + +class PerfProbeImpl implements PerfProbe { + constructor( + name: string, + main?: MainPerfProbeImpl, + parent?: PerfProbeImpl, + remainder: boolean = false + ) { + this._name = name + this._main = main + this.parent = parent + this.remainder = remainder + } + + private readonly _name: string + private readonly _main: MainPerfProbeImpl|undefined + public parent: PerfProbeImpl|undefined + public readonly remainder: boolean + + children: Array = new Array() + childrenSorted: boolean = false + index: int32 = 0 + startTime: float64 = 0.0 + totalTime: float64 = 0.0 + callCount: int32 = 0 + currentRecursionDepth: int32 = 0 + recursiveCallCount: int32 = 0 + _canceled: boolean = false + private _userData?: string + + get name(): string { + return this._name + } + + get dummy(): boolean { + return false + } + + get main(): MainPerfProbeImpl { + return this._main! + } + + get performing(): boolean { + return this.startTime > 0 + } + + get userData(): string | undefined { + return this._userData + } + + set userData(value: string | undefined) { + this._userData = value + } + + exit(log?: boolean): void { + if (this.canceled) return + + if (this.currentRecursionDepth == 0) { + this.totalTime += timeNow() - this.startTime + this.startTime = 0 + } else { + this.currentRecursionDepth-- + } + if (!this.performing) { + this.main.pop(this) + } + if (log) this.log() + } + + cancel(cancelChildren: boolean = true) { + this._canceled = true + if (cancelChildren) this.maybeCancelChildren() + } + + private maybeCancelChildren() { + MainPerfProbeImpl.visit(this, false, (probe: PerfProbeImpl, depth: int32) => { + if (probe.performing) probe.cancel(false) + }) + } + + get canceled(): boolean { + return this._canceled + } + + toString(): string { + if (this.canceled) { + return `[${this.name}] canceled` + } + if (this.performing) { + return `[${this.name}] still performing...` + } + const mainProbe = this.main.probes.get(this.main.name)! + const percentage = mainProbe.totalTime > 0 ? Math.round((100 / mainProbe.totalTime) * this.totalTime) : 0 + + let result = `[${this.name}] call count: ${this.callCount}` + + ` | recursive call count: ${this.recursiveCallCount}` + + ` | time: ${this.totalTime}ms ${percentage}%` + + if (this.userData) { + result += ` | user data: ${this.userData}` + } + + return result + } + + protected log(prefix?: string) { + console.log(prefix ? `${prefix}${this.toString()}` : this.toString()) + } + + static readonly DUMMY: PerfProbe = new DummyPerfProbe() +} + +class MainPerfProbeImpl extends PerfProbeImpl implements MainPerfProbe { + constructor( + name: string + ) { + super(name) + const prev = MainPerfProbeImpl.mainProbes.get(name) + if (prev) prev.cancel() + MainPerfProbeImpl.mainProbes.set(name, this) + this.currentProbe = this.enterProbe(name) + } + + static readonly mainProbes: Map = new Map() + + currentProbe: PerfProbeImpl + probes: Map = new Map() + + private createProbe(name: string): PerfProbeImpl { + const probes = name == this.name ? this : new PerfProbeImpl(name, this) + this.push(probes) + return probes + } + + get main(): MainPerfProbeImpl { + return this + } + + push(probe: PerfProbeImpl) { + probe.parent = this.currentProbe + probe.index = probe.parent ? probe.parent!.children.length as int32 : 0 + if (probe.parent) probe.parent!.children.push(probe) + this.currentProbe = probe + } + + pop(probe: PerfProbeImpl) { + if (probe.parent) { + this.currentProbe = probe.parent! + } + } + + performProbe(name: string, func: () => T): T { + const probe = this.enterProbe(name) + try { + return func() + } finally { + probe.exit() + } + } + + enterProbe(name: string): PerfProbeImpl { + let probe = this.probes.get(name) + if (!probe) { + probe = this.createProbe(name) + this.probes.set(name, probe) + } + probe._canceled = false + + if (probe.performing) { + probe.recursiveCallCount++ + probe.currentRecursionDepth++ + } else { + probe.startTime = timeNow() + probe.callCount++ + } + return probe + } + + exitProbe(name: string): PerfProbe { + const probe = this.getProbe(name) + probe.exit(undefined) + return probe + } + + getProbe(name: string): PerfProbe { + const probe = this.probes.get(name) + return probe !== undefined ? probe : PerfProbeImpl.DUMMY + } + + probePerformed(name: string): boolean { + const probe = this.probes.get(name) + return probe != undefined && !probe!.performing && !probe!.canceled + } + + exit(log?: boolean) { + super.exit() + if (log) this.log() + this.cancel() + } + + cancel() { + MainPerfProbeImpl.mainProbes.delete(this.name) + } + + static visit(root: PerfProbeImpl, logging: boolean, apply: (probe: PerfProbeImpl, depth: int32) => void) { + let current: PerfProbeImpl = root + let index = 0 + let depth = 0 + let visiting = true + while (true) { + if (visiting) { + current.index = 0 + apply(current, depth) + } + if (index >= current.children.length) { + if (!current.parent) { + break + } + current = current.parent! + index = ++current.index + depth-- + visiting = false + continue + } + visiting = true + if (logging && !current.childrenSorted) { + current.childrenSorted = true + current.children = current.children.sort((p1: PerfProbeImpl, p2: PerfProbeImpl):number => p2.totalTime - p1.totalTime) + if (depth == 0) { + // a special probe to log the time remained + current.children.push(new PerfProbeImpl("", root.main, current, true)) + } + } + current = current.children[index] + index = 0 + depth++ + } + } + + protected log(prefix?: string) { + prefix = prefix !== undefined ? `${prefix}: ` : "" + console.log(`${prefix}perf probes:`) + + MainPerfProbeImpl.visit(this.main, true, (probe, depth):void => { + let indent = "\t" + for (let i = 0; i < depth; i++) indent += "\t" + if (probe.remainder) { + const parentTime = probe.parent!.totalTime + let childrenTime = 0 + probe.parent!.children.forEach((a: PerfProbeImpl):void => { childrenTime += a.totalTime }) + probe.totalTime = Math.max(0, parentTime - childrenTime) as int32 + const percentage = parentTime > 0 ? Math.round((100 / parentTime) * probe.totalTime) : 0 + console.log(`${prefix}${indent}[${probe.name}] time: ${numberToFixed(probe.totalTime, 2)}ms ${percentage}%`) + } else { + console.log(`${prefix}${indent}${probe.toString()}`) + } + }) + } + + static readonly DUMMY: MainPerfProbe = new DummyPerfProbe() +} diff --git a/koala-wrapper/koalaui/common/src/Point.ts b/koala-wrapper/koalaui/common/src/Point.ts new file mode 100644 index 000000000..1a89eadcd --- /dev/null +++ b/koala-wrapper/koalaui/common/src/Point.ts @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32 } from "@koalaui/compat" + +export class Point { + coordinates: Float32Array + + constructor (x: float32, y: float32) { + this.coordinates = new Float32Array(2) + this.coordinates[0] = x + this.coordinates[1] = y + } + + get x(): float32 { + return this.coordinates[0] as float32 + } + + get y(): float32 { + return this.coordinates[1] as float32 + } + + offsetXY(dx: float32, dy: float32): Point { + return new Point(this.x + dx, this.y + dy) + } + + offset(vec: Point): Point { + return this.offsetXY(vec.x, vec.y) + } + + scale(scale: float32): Point { + return this.scaleXY(scale, scale) + } + + scaleXY(sx: float32, sy: float32): Point { + return new Point(this.x * sx, this.y * sy) + } + + static ZERO = new Point(0.0 as float32, 0.0 as float32) + + toArray(): Float32Array { + return this.coordinates + } + + static flattenArray(points: Array): Float32Array { + let array = new Float32Array(points.length * 2) + for (let i = 0; i < points.length; i++) { + array[i * 2] = points[i].x + array[i * 2 + 1] = points[i].y + } + return array + } + + static fromArray(points: Float32Array): Array { + if (points.length % 2 != 0) + throw new Error("Expected " + points.length + " % 2 == 0") + + let array = new Array(points.length / 2) + for (let i = 0; i < points.length / 2; i++) { + array[i] = new Point(points[i * 2] as float32, points[i * 2 + 1] as float32) + } + return array + } +} diff --git a/koala-wrapper/koalaui/common/src/Point3.ts b/koala-wrapper/koalaui/common/src/Point3.ts new file mode 100644 index 000000000..04e86ee2a --- /dev/null +++ b/koala-wrapper/koalaui/common/src/Point3.ts @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32 } from "@koalaui/compat" + +export class Point3 { + x: float32 + y: float32 + z: float32 + constructor(x: float32, y: float32, z: float32) { + this.x = x + this.y = y + this.z = z + } + + subtract(value: Point3): Point3 { + return new Point3( + this.x - value.x, + this.y - value.y, + this.z - value.z + ) + } + + cross(value: Point3): Point3 { + return new Point3( + this.y * value.z - this.z * value.y, + this.z * value.x - this.x * value.z, + this.x * value.y - this.y * value.x + ) + } + + normalize(): Point3 { + const mag = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z) as float32 + const tolerance = (1.0 / (1 << 12)) + if (mag < tolerance) { + // This semicolon after return this is a workaround for ArkTS bug + return this; + } + return new Point3(this.x / mag, this.y / mag, this.z / mag) + } +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/src/index.ts b/koala-wrapper/koalaui/common/src/index.ts new file mode 100644 index 000000000..471b714b3 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/index.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022-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. + */ + +export { + int8, uint8, + int32, uint32, + int64, uint64, + float32, float64, + asArray, + asFloat64, + float32FromBits, + int32BitsFromFloat, + Array_from_set, + AtomicRef, + CustomTextDecoder, + CustomTextEncoder, + className, lcClassName, + functionOverValue, + Observed, + Observable, + ObservableHandler, + observableProxy, + observableProxyArray, + isFunction, + propDeepCopy, + refEqual, + int8Array, + unsafeCast +} from "@koalaui/compat" +export { clamp, lerp, modulo, parseNumber, isFiniteNumber, getDistancePx } from "./math" +export { hashCodeFromString } from "./stringUtils" +export { KoalaProfiler } from "./KoalaProfiler" +export * from "./PerfProbe" +export * from "./Errors" +export * from "./LifecycleEvent" +export * from "./Finalization" +export * from "./MarkableQueue" +export * from "./Matrix33" +export * from "./Matrix44" +export * from "./Point3" +export * from "./Point" +export { SHA1Hash, createSha1 } from "./sha1" +export { UniqueId } from "./uniqueId" +export * from "./koalaKey" diff --git a/koala-wrapper/koalaui/common/src/koalaKey.ts b/koala-wrapper/koalaui/common/src/koalaKey.ts new file mode 100644 index 000000000..94c00f336 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/koalaKey.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/compat" + +export type KoalaCallsiteKey = int32 + +export class KoalaCallsiteKeys { + static readonly empty: KoalaCallsiteKey = 0 as int32 + + static combine (key1: KoalaCallsiteKey, key2: KoalaCallsiteKey): KoalaCallsiteKey { + return key1 + key2 + } + + static asString(key: KoalaCallsiteKey): string { + return new Number(key).toString(16) + } +} diff --git a/koala-wrapper/koalaui/common/src/math.ts b/koala-wrapper/koalaui/common/src/math.ts new file mode 100644 index 000000000..9b8b15d87 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/math.ts @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { asFloat64, asString, float64 } from "@koalaui/compat" + +/** + * Computes the linear interpolation between `source` and `target` based on `weight`. + * + * @param weight - interpolation factor in the range [0..1] + * @param source - a value corresponding to weight 0 + * @param target - a value corresponding to weight 1 + * @returns interpolated value + */ +export function lerp(weight: float64, source: float64, target: float64): float64 { + return source * (1.0 - weight) + target * weight +} + +/** + * Clamps a {@link value} within the specified range. + * + * @param value - a value to clamp + * @param min - the lower boundary of the range + * @param max - the upper boundary of the range + * @returns `min` if `value` is less than `min`, + * `max` if `value` is greater than `max`, + * `value` otherwise + */ +export function clamp(value: float64, min: float64, max: float64): float64 { + return value <= min ? min : value >= max ? max : value +} + +/** + * Calculates the difference between the argument and + * the largest (closest to positive infinity) integer value + * that is less than or equal to the argument. + * + * @param value a floating-point value to process + * @returns a floor modulus of the given value in the range [0..1) + */ +export function modulo(value: float64): float64 { + // The casts below are needed since floor returns double in ArkTS + const modulo: float64 = value - Math.floor(value) + return (modulo < 1.0) ? modulo : 0.0 +} + +/** + * @param str a string to parse + * @param name a name for error message + * @param verify whether to verify parsing validity + * @returns a floating-point number + * @throws Error if `str` cannot be parsed + */ +export function parseNumber(str: string, name: string = "number", verify: boolean = false): float64 { + if (str != "") { // do not parse empty string to 0 + // ArkTS does not support NaN, isNaN, parseFloat + const value = asFloat64(str) + if (verify) { + const reverseStr = asString(value) + if (reverseStr !== undefined && reverseStr?.length == str.length && reverseStr == str) { + return value + } + } + else { + return value + } + } + throw new Error(`cannot parse ${name}: "${str}"`) +} + +/** + * An ArkTS-compliant replacement for {@link isFinite}. + */ +export function isFiniteNumber(number: float64): boolean { + // With Node.js: + // isFiniteNumber(Number.NEGATIVE_INFINITY) == false + // isFiniteNumber(Number.POSITIVE_INFINITY) == false + // isFiniteNumber(NaN) == false + return number >= Number.MIN_SAFE_INTEGER && number <= Number.MAX_SAFE_INTEGER +} + +export function getDistancePx(startX: float64, startY: float64, endX: float64, endY: float64): float64 { + const cathetA = Math.abs(endX - startX) + const cathetB = Math.abs(endY - startY) + return Math.sqrt(cathetA * cathetA + cathetB * cathetB) as float64 +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/common/src/sha1.ts b/koala-wrapper/koalaui/common/src/sha1.ts new file mode 100644 index 000000000..11af4b187 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/sha1.ts @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CustomTextDecoder } from "@koalaui/compat" +import { int32 } from "@koalaui/compat" + +const K = [ + (0x5a827999 | 0) as int32, + (0x6ed9eba1 | 0) as int32, + (0x8f1bbcdc | 0) as int32, + (0xca62c1d6 | 0) as int32, +] + +const inputBytes = 64 +const inputWords = inputBytes / 4 +const highIndex = inputWords - 2 +const lowIndex = inputWords - 1 +const workWords = 80 +const allocBytes = 80 +const allocWords = allocBytes / 4 +const allocTotal = allocBytes * 100 + +export function createSha1(): SHA1Hash { + return new SHA1Hash() +} + +export class SHA1Hash { + private A = (0x67452301 | 0) as int32 + private B = (0xefcdab89 | 0) as int32 + private C = (0x98badcfe | 0) as int32 + private D = (0x10325476 | 0) as int32 + private E = (0xc3d2e1f0 | 0) as int32 + private readonly _byte: Uint8Array + private readonly _word: Int32Array + private _size = 0 + private _sp = 0 // surrogate pair + + constructor() { + if (!sharedBuffer || sharedOffset >= allocTotal) { + sharedBuffer = new ArrayBuffer(allocTotal) + sharedOffset = 0 + } + + this._byte = new Uint8Array(sharedBuffer, sharedOffset, allocBytes) + this._word = new Int32Array(sharedBuffer, sharedOffset, allocWords) + sharedOffset += allocBytes + } + + updateString(data: string, encoding?: string): SHA1Hash { + return this._utf8(data) + } + updateInt32(data: int32): SHA1Hash { + const buffer = new Int32Array(1) + buffer[0] = data + return this.update(buffer) + } + + update(data: Int32Array | Float32Array | Uint32Array | Uint8Array): SHA1Hash { + if (data == null) { + throw new TypeError("SHA1Hash expected non-null data: ") + } + + let byteOffset: int32 = 0 + let length: int32 = 0 + let buffer: ArrayBufferLike | undefined = undefined + + // TODO: an attempt to wrie this in a generic form causes + // es2panda to segfault. + if (data instanceof Int32Array) { + byteOffset = data.byteOffset as int32 + length = data.byteLength as int32 + buffer = data.buffer + } else if (data instanceof Uint32Array) { + byteOffset = data.byteOffset as int32 + length = data.byteLength as int32 + buffer = data.buffer + } else if (data instanceof Float32Array) { + byteOffset = data.byteOffset as int32 + length = data.byteLength as int32 + buffer = data.buffer + } else if (data instanceof Uint8Array) { + byteOffset = data.byteOffset as int32 + length = data.byteLength as int32 + buffer = data.buffer + } + + let blocks: int32 = ((length / inputBytes) | 0) as int32 + let offset: int32 = 0 + + // longer than 1 block + if ((blocks != 0) && !(byteOffset & 3) && !(this._size % inputBytes)) { + const block = new Int32Array(buffer!, byteOffset, blocks * inputWords) + while (blocks--) { + this._int32(block, offset >> 2) + offset += inputBytes + } + this._size += offset + } + + // data: TypedArray | DataView + const BYTES_PER_ELEMENT = (data as Uint8Array).BYTES_PER_ELEMENT as int32 + if ((BYTES_PER_ELEMENT != 1) && buffer != undefined) { + const rest = new Uint8Array(buffer, byteOffset + offset, length - offset) + return this._uint8(rest) + } + + // no more bytes + if (offset == length) return this + + return this._uint8(new Uint8Array(buffer!), offset) + } + + private _uint8(data: Uint8Array, offset?: int32): SHA1Hash { + const _byte = this._byte + const _word = this._word + const length = data.length + offset = ((offset ?? 0) | 0) as int32 + + while (offset < length) { + const start = this._size % inputBytes + let index = start + + while (offset < length && index < inputBytes) { + _byte[index++] = data[offset++] + } + + if (index >= inputBytes) { + this._int32(_word) + } + + this._size += index - start + } + + return this + } + + private _utf8(text: string): SHA1Hash { + const _byte = this._byte + const _word = this._word + const length = text.length + let surrogate = this._sp + + for (let offset = 0; offset < length; ) { + const start = this._size % inputBytes + let index = start + + while (offset < length && index < inputBytes) { + let code = text.charCodeAt(offset++) | 0 + if (code < 0x80) { + // ASCII characters + _byte[index++] = code + } else if (code < 0x800) { + // 2 bytes + _byte[index++] = 0xC0 | (code >>> 6) + _byte[index++] = 0x80 | (code & 0x3F) + } else if (code < 0xD800 || code > 0xDFFF) { + // 3 bytes + _byte[index++] = 0xE0 | (code >>> 12) + _byte[index++] = 0x80 | ((code >>> 6) & 0x3F) + _byte[index++] = 0x80 | (code & 0x3F) + } else if (surrogate) { + // 4 bytes - surrogate pair + code = ((surrogate & 0x3FF) << 10) + (code & 0x3FF) + 0x10000 + _byte[index++] = 0xF0 | (code >>> 18) + _byte[index++] = 0x80 | ((code >>> 12) & 0x3F) + _byte[index++] = 0x80 | ((code >>> 6) & 0x3F) + _byte[index++] = 0x80 | (code & 0x3F) + surrogate = 0 + } else { + surrogate = code + } + } + + if (index >= inputBytes) { + this._int32(_word) + _word[0] = _word[inputWords] + } + + this._size += index - start + } + + this._sp = surrogate + return this + } + + private _int32(data: Int32Array, offset?: int32): void { + let A = this.A + let B = this.B + let C = this.C + let D = this.D + let E = this.E + let i = 0 + offset = ((offset ?? 0) | 0) as int32 + + while (i < inputWords) { + W[i++] = swap32(data[offset++] as int32) + } + + for (i = inputWords; i < workWords; i++) { + W[i] = rotate1((W[i - 3] as int32) ^ (W[i - 8] as int32) ^ (W[i - 14] as int32) ^ (W[i - 16] as int32)) + } + + for (i = 0; i < workWords; i++) { + const S = (i / 20) | 0 + const T = ((rotate5(A) + ft(S, B, C, D) + E + W[i] + K[S]) as int32) | 0 + E = D + D = C + C = rotate30(B) + B = A + A = T + } + + this.A = (A + this.A) | 0 + this.B = (B + this.B) | 0 + this.C = (C + this.C) | 0 + this.D = (D + this.D) | 0 + this.E = (E + this.E) | 0 + } + + // digest(): Uint8Array + // digest(encoding: string): string + digest(encoding?: string): Uint8Array | string { + const _byte = this._byte + const _word = this._word + let i = (this._size % inputBytes) | 0 + _byte[i++] = 0x80 + + // pad 0 for current word + while (i & 3) { + _byte[i++] = 0 + } + i >>= 2 + + if (i > highIndex) { + while (i < inputWords) { + _word[i++] = 0 + } + i = 0 + this._int32(_word) + } + + // pad 0 for rest words + while (i < inputWords) { + _word[i++] = 0 + } + + // input size + const bits64: int32 = this._size * 8 + const low32: int32 = ((bits64 & 0xffffffff) as int32 >>> 0) as int32 + const high32: int32 = ((bits64 - low32) as int32 / 0x100000000) as int32 + if (high32) _word[highIndex] = swap32(high32) as int32 + if (low32) _word[lowIndex] = swap32(low32) as int32 + + this._int32(_word) + + return (encoding === "hex") ? this._hex() : this._bin() + } + + private _hex(): string { + let A = this.A + let B = this.B + let C = this.C + let D = this.D + let E = this.E + + return hex32Str(A, B, C, D, E) + } + + private _bin(): Uint8Array { + let A = this.A + let B = this.B + let C = this.C + let D = this.D + let E = this.E + const _byte = this._byte + const _word = this._word + + _word[0] = swap32(A) + _word[1] = swap32(B) + _word[2] = swap32(C) + _word[3] = swap32(D) + _word[4] = swap32(E) + + return _byte.slice(0, 20) + } +} + +type NS = (num: int32) => string +type NN = (num: int32) => int32 + +const W = new Int32Array(workWords) + +let sharedBuffer: ArrayBuffer +let sharedOffset: int32 = 0 + +const swapLE: NN = ((c:int32):int32 => (((c << 24) & 0xff000000) | ((c << 8) & 0xff0000) | ((c >> 8) & 0xff00) | ((c >> 24) & 0xff))) +const swapBE: NN = ((c:int32):int32 => c) +const swap32: NN = isBE() ? swapBE : swapLE +const rotate1: NN = (num: int32): int32 => (num << 1) | (num >>> 31) +const rotate5: NN = (num: int32): int32 => (num << 5) | (num >>> 27) +const rotate30: NN = (num: int32): int32 => (num << 30) | (num >>> 2) + +function isBE(): boolean { + let a16 = new Uint16Array(1) + a16[0] = 0xFEFF + let a8 = new Uint8Array(a16.buffer) + return a8[0] == 0xFE // BOM +} + + +function ft(s: int32, b: int32, c: int32, d: int32) { + if (s == 0) return (b & c) | ((~b) & d) + if (s == 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +const hex32Decoder = new CustomTextDecoder() +const hex32DecodeBuffer = new Uint8Array(40) +function hex32Str(A: int32, B: int32, C: int32, D: int32, E: int32): string { + writeIntAsHexUTF8(A, hex32DecodeBuffer, 0) + writeIntAsHexUTF8(B, hex32DecodeBuffer, 8) + writeIntAsHexUTF8(C, hex32DecodeBuffer, 16) + writeIntAsHexUTF8(D, hex32DecodeBuffer, 24) + writeIntAsHexUTF8(E, hex32DecodeBuffer, 32) + return hex32Decoder.decode(hex32DecodeBuffer) +} + +function writeIntAsHexUTF8(value: int32, buffer: Uint8Array, byteOffset: int32) { + buffer[byteOffset++] = nibbleToHexCode((value >> 28) & 0xF) + buffer[byteOffset++] = nibbleToHexCode((value >> 24) & 0xF) + buffer[byteOffset++] = nibbleToHexCode((value >> 20) & 0xF) + buffer[byteOffset++] = nibbleToHexCode((value >> 16) & 0xF) + buffer[byteOffset++] = nibbleToHexCode((value >> 12) & 0xF) + buffer[byteOffset++] = nibbleToHexCode((value >> 8 ) & 0xF) + buffer[byteOffset++] = nibbleToHexCode((value >> 4 ) & 0xF) + buffer[byteOffset++] = nibbleToHexCode((value >> 0 ) & 0xF) +} + +function nibbleToHexCode(nibble: int32) { + return nibble > 9 ? nibble + 87 : nibble + 48 +} diff --git a/koala-wrapper/koalaui/common/src/stringUtils.ts b/koala-wrapper/koalaui/common/src/stringUtils.ts new file mode 100644 index 000000000..e9ec1a790 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/stringUtils.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/compat" + + +/** + * Computes a hash code from the string {@link value}. + */ +export function hashCodeFromString(value: string): int32 { + let hash = 5381 + for(let i = 0; i < value.length; i++) { + hash = (hash * 33) ^ value.charCodeAt(i) + hash |= 0 + } + return hash +} diff --git a/koala-wrapper/koalaui/common/src/uniqueId.ts b/koala-wrapper/koalaui/common/src/uniqueId.ts new file mode 100644 index 000000000..b32441905 --- /dev/null +++ b/koala-wrapper/koalaui/common/src/uniqueId.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/compat" +import { createSha1 } from "./sha1"; + +export class UniqueId { + private sha = createSha1() + + public addString(data: string): UniqueId { + this.sha.updateString(data) + return this + } + + public addI32(data: int32): UniqueId { + this.sha.updateInt32(data) + return this + } + + public addF32Array(data: Float32Array): UniqueId { + this.sha.update(data) + return this + } + + public addI32Array(data: Int32Array): UniqueId { + this.sha.update(data) + return this + } + + public addU32Array(data: Uint32Array): UniqueId { + this.sha.update(data) + return this + } + + public addU8Array(data: Uint8Array): UniqueId { + this.sha.update(data) + return this + } + + public addPtr(data: Uint32Array | number): UniqueId { + if (data instanceof Uint32Array) { + return this.addU32Array(data) + } + return this.addI32(data as int32) + } + + public compute(): string { + return this.sha.digest("hex") as string + } +} diff --git a/koala-wrapper/koalaui/compat/README.md b/koala-wrapper/koalaui/compat/README.md new file mode 100644 index 000000000..5bd0a1951 --- /dev/null +++ b/koala-wrapper/koalaui/compat/README.md @@ -0,0 +1,4 @@ +This is a typescript and ArkTS compatibility library. + +It abstracts out such things as reflection which are quite different in typescript and ArkTS. + diff --git a/koala-wrapper/koalaui/compat/dist/src/index.d.ts b/koala-wrapper/koalaui/compat/dist/src/index.d.ts new file mode 100644 index 000000000..6a50786d6 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/index.d.ts @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2022-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. + */ +export { asArray, Array_from_set, Array_from_int32, Array_from_number, AtomicRef, asFloat64, asString, float32FromBits, int32BitsFromFloat, Thunk, finalizerRegister, finalizerUnregister, timeNow, numberToFixed, Observed, Observable, ObservableHandler, observableProxy, observableProxyArray, propDeepCopy, lcClassName, CustomTextEncoder, CustomTextDecoder, className, isFunction, functionOverValue, refEqual, isNotPrimitive, uint8, int8, int16, int32, uint32, int64, uint64, float32, float64, int8Array, unsafeCast, } from "#platform"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/index.js b/koala-wrapper/koalaui/compat/dist/src/index.js new file mode 100644 index 000000000..cfaa72b41 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/index.js @@ -0,0 +1,47 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unsafeCast = exports.int8Array = exports.isNotPrimitive = exports.refEqual = exports.functionOverValue = exports.isFunction = exports.className = exports.CustomTextDecoder = exports.CustomTextEncoder = exports.lcClassName = exports.propDeepCopy = exports.observableProxyArray = exports.observableProxy = exports.ObservableHandler = exports.Observed = exports.numberToFixed = exports.timeNow = exports.finalizerUnregister = exports.finalizerRegister = exports.int32BitsFromFloat = exports.float32FromBits = exports.asString = exports.asFloat64 = exports.AtomicRef = exports.Array_from_number = exports.Array_from_int32 = exports.Array_from_set = exports.asArray = void 0; +var _platform_1 = require("#platform"); +Object.defineProperty(exports, "asArray", { enumerable: true, get: function () { return _platform_1.asArray; } }); +Object.defineProperty(exports, "Array_from_set", { enumerable: true, get: function () { return _platform_1.Array_from_set; } }); +Object.defineProperty(exports, "Array_from_int32", { enumerable: true, get: function () { return _platform_1.Array_from_int32; } }); +Object.defineProperty(exports, "Array_from_number", { enumerable: true, get: function () { return _platform_1.Array_from_number; } }); +Object.defineProperty(exports, "AtomicRef", { enumerable: true, get: function () { return _platform_1.AtomicRef; } }); +Object.defineProperty(exports, "asFloat64", { enumerable: true, get: function () { return _platform_1.asFloat64; } }); +Object.defineProperty(exports, "asString", { enumerable: true, get: function () { return _platform_1.asString; } }); +Object.defineProperty(exports, "float32FromBits", { enumerable: true, get: function () { return _platform_1.float32FromBits; } }); +Object.defineProperty(exports, "int32BitsFromFloat", { enumerable: true, get: function () { return _platform_1.int32BitsFromFloat; } }); +Object.defineProperty(exports, "finalizerRegister", { enumerable: true, get: function () { return _platform_1.finalizerRegister; } }); +Object.defineProperty(exports, "finalizerUnregister", { enumerable: true, get: function () { return _platform_1.finalizerUnregister; } }); +Object.defineProperty(exports, "timeNow", { enumerable: true, get: function () { return _platform_1.timeNow; } }); +Object.defineProperty(exports, "numberToFixed", { enumerable: true, get: function () { return _platform_1.numberToFixed; } }); +Object.defineProperty(exports, "Observed", { enumerable: true, get: function () { return _platform_1.Observed; } }); +Object.defineProperty(exports, "ObservableHandler", { enumerable: true, get: function () { return _platform_1.ObservableHandler; } }); +Object.defineProperty(exports, "observableProxy", { enumerable: true, get: function () { return _platform_1.observableProxy; } }); +Object.defineProperty(exports, "observableProxyArray", { enumerable: true, get: function () { return _platform_1.observableProxyArray; } }); +Object.defineProperty(exports, "propDeepCopy", { enumerable: true, get: function () { return _platform_1.propDeepCopy; } }); +Object.defineProperty(exports, "lcClassName", { enumerable: true, get: function () { return _platform_1.lcClassName; } }); +Object.defineProperty(exports, "CustomTextEncoder", { enumerable: true, get: function () { return _platform_1.CustomTextEncoder; } }); +Object.defineProperty(exports, "CustomTextDecoder", { enumerable: true, get: function () { return _platform_1.CustomTextDecoder; } }); +Object.defineProperty(exports, "className", { enumerable: true, get: function () { return _platform_1.className; } }); +Object.defineProperty(exports, "isFunction", { enumerable: true, get: function () { return _platform_1.isFunction; } }); +Object.defineProperty(exports, "functionOverValue", { enumerable: true, get: function () { return _platform_1.functionOverValue; } }); +Object.defineProperty(exports, "refEqual", { enumerable: true, get: function () { return _platform_1.refEqual; } }); +Object.defineProperty(exports, "isNotPrimitive", { enumerable: true, get: function () { return _platform_1.isNotPrimitive; } }); +Object.defineProperty(exports, "int8Array", { enumerable: true, get: function () { return _platform_1.int8Array; } }); +Object.defineProperty(exports, "unsafeCast", { enumerable: true, get: function () { return _platform_1.unsafeCast; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/array.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/array.d.ts new file mode 100644 index 000000000..df8d52c6b --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/array.d.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float64, int32, int8 } from "./types"; +export declare function asArray(value: T[]): Array; +export declare function Array_from_set(set: Set): Array; +export declare function Array_from_int32(data: Int32Array): int32[]; +export declare function Array_from_number(data: float64[]): Array; +export declare function int8Array(size: int32): int8[]; +//# sourceMappingURL=array.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/array.js b/koala-wrapper/koalaui/compat/dist/src/typescript/array.js new file mode 100644 index 000000000..c391e6c4f --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/array.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.int8Array = exports.Array_from_number = exports.Array_from_int32 = exports.Array_from_set = exports.asArray = void 0; +function asArray(value) { + return value; +} +exports.asArray = asArray; +function Array_from_set(set) { + return Array.from(set); +} +exports.Array_from_set = Array_from_set; +function Array_from_int32(data) { + return Array.from(data); +} +exports.Array_from_int32 = Array_from_int32; +function Array_from_number(data) { + return data; +} +exports.Array_from_number = Array_from_number; +function int8Array(size) { + return []; +} +exports.int8Array = int8Array; +//# sourceMappingURL=array.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/atomic.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/atomic.d.ts new file mode 100644 index 000000000..d799b95b0 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/atomic.d.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare class AtomicRef { + value: Value; + /** + * Creates a new reference object with the given initial value. + * @param value - the new value + */ + constructor(value: Value); + /** + * Atomically sets the reference value to the given value and returns the previous one. + * @param value - the new value + * @returns the previous value + */ + getAndSet(value: Value): Value; +} +//# sourceMappingURL=atomic.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/atomic.js b/koala-wrapper/koalaui/compat/dist/src/typescript/atomic.js new file mode 100644 index 000000000..2aa1b1ad4 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/atomic.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AtomicRef = void 0; +/** + * A reference that may be updated atomically. + */ +class AtomicRef { + /** + * Creates a new reference object with the given initial value. + * @param value - the new value + */ + constructor(value) { + this.value = value; + } + /** + * Atomically sets the reference value to the given value and returns the previous one. + * @param value - the new value + * @returns the previous value + */ + getAndSet(value) { + const result = this.value; + this.value = value; + return result; + } +} +exports.AtomicRef = AtomicRef; +//# sourceMappingURL=atomic.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/double.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/double.d.ts new file mode 100644 index 000000000..71c40c89b --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/double.d.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float64, int32, float32 } from "./types"; +export declare function asFloat64(value: string): float64; +export declare function asString(value: float64 | undefined): string | undefined; +export declare function float32FromBits(value: int32): float32; +export declare function int32BitsFromFloat(value: float32): int32; +//# sourceMappingURL=double.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/double.js b/koala-wrapper/koalaui/compat/dist/src/typescript/double.js new file mode 100644 index 000000000..ea84b6e5d --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/double.js @@ -0,0 +1,35 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.int32BitsFromFloat = exports.float32FromBits = exports.asString = exports.asFloat64 = void 0; +function asFloat64(value) { + return Number(value); +} +exports.asFloat64 = asFloat64; +function asString(value) { + return value === null || value === void 0 ? void 0 : value.toString(); +} +exports.asString = asString; +function float32FromBits(value) { + return value; +} +exports.float32FromBits = float32FromBits; +function int32BitsFromFloat(value) { + return value; +} +exports.int32BitsFromFloat = int32BitsFromFloat; +//# sourceMappingURL=double.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/finalization.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/finalization.d.ts new file mode 100644 index 000000000..8047a3aec --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/finalization.d.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022-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. + */ + +export interface Thunk { + clean(): void; +} +export declare function finalizerRegister(target: object, thunk: object): void; +export declare function finalizerUnregister(target: object): void; +//# sourceMappingURL=finalization.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/finalization.js b/koala-wrapper/koalaui/compat/dist/src/typescript/finalization.js new file mode 100644 index 000000000..4d605cb72 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/finalization.js @@ -0,0 +1,29 @@ +"use strict"; +/* + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.finalizerUnregister = exports.finalizerRegister = void 0; +const registry = new FinalizationRegistry((thunk) => { + thunk.clean(); +}); +function finalizerRegister(target, thunk) { + registry.register(target, thunk); +} +exports.finalizerRegister = finalizerRegister; +function finalizerUnregister(target) { + registry.unregister(target); +} +exports.finalizerUnregister = finalizerUnregister; +//# sourceMappingURL=finalization.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/index.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/index.d.ts new file mode 100644 index 000000000..11311543c --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/index.d.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022-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. + */ + +export * from "./array"; +export * from "./atomic"; +export * from "./double"; +export * from "./finalization"; +export * from "./observable"; +export * from "./performance"; +export * from "./prop-deep-copy"; +export * from "./reflection"; +export * from "./strings"; +export * from "./ts-reflection"; +export * from "./types"; +export * from "./utils"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/index.js b/koala-wrapper/koalaui/compat/dist/src/typescript/index.js new file mode 100644 index 000000000..17c1bf11d --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/index.js @@ -0,0 +1,43 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./array"), exports); +__exportStar(require("./atomic"), exports); +__exportStar(require("./double"), exports); +__exportStar(require("./finalization"), exports); +__exportStar(require("./observable"), exports); +__exportStar(require("./performance"), exports); +__exportStar(require("./prop-deep-copy"), exports); +__exportStar(require("./reflection"), exports); +__exportStar(require("./strings"), exports); +__exportStar(require("./ts-reflection"), exports); +__exportStar(require("./types"), exports); +__exportStar(require("./utils"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/observable.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/observable.d.ts new file mode 100644 index 000000000..28df03087 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/observable.d.ts @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare function getObservableTarget(proxy: Object): Object; +/** + * Data class decorator that makes all child fields trackable. + */ +export declare function Observed(constructorFunction: Function): void; +/** @internal */ +export interface Observable { + /** It is called when the observable value is accessed. */ + onAccess(): void; + /** It is called when the observable value is modified. */ + onModify(): void; +} +/** @internal */ +export declare class ObservableHandler implements Observable { + private static handlers; + private parents; + private children; + private readonly observables; + private _modified; + readonly observed: boolean; + constructor(parent?: ObservableHandler, observed?: boolean); + onAccess(): void; + onModify(): void; + static dropModified(value: Value): boolean; + /** Adds the specified `observable` to the handler corresponding to the given `value`. */ + static attach(value: Value, observable: Observable): void; + /** Deletes the specified `observable` from the handler corresponding to the given `value`. */ + static detach(value: Value, observable: Observable): void; + /** @returns the handler corresponding to the given `value` if it was installed */ + private static findIfObject; + /** + * @param value - any non-null object including arrays + * @returns an observable handler or `undefined` if it is not installed + */ + static find(value: Object): ObservableHandler | undefined; + /** + * @param value - any non-null object including arrays + * @param observable - a handler to install on this object + * @throws an error if observable handler cannot be installed + */ + static installOn(value: Object, observable?: ObservableHandler): void; + addParent(parent: ObservableHandler): void; + removeParent(parent: ObservableHandler): void; + removeChild(value: Value): void; + private collect; + static contains(observable: ObservableHandler, guards?: Set): boolean; +} +/** @internal */ +export declare function observableProxyArray(...value: Value[]): Array; +/** @internal */ +export declare function observableProxy(value: Value, parent?: ObservableHandler, observed?: boolean, strict?: boolean): Value; +//# sourceMappingURL=observable.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/observable.js b/koala-wrapper/koalaui/compat/dist/src/typescript/observable.js new file mode 100644 index 000000000..5de62790f --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/observable.js @@ -0,0 +1,406 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.observableProxy = exports.observableProxyArray = exports.ObservableHandler = exports.Observed = exports.getObservableTarget = void 0; +const OBSERVABLE_TARGET = "__proxy_observable_target__"; +function getObservableTarget(proxy) { + var _a; + return (_a = getPropertyValue(OBSERVABLE_TARGET, proxy)) !== null && _a !== void 0 ? _a : proxy; +} +exports.getObservableTarget = getObservableTarget; +function getPropertyValue(name, object) { + return object[name]; +} +/** + * Data class decorator that makes all child fields trackable. + */ +function Observed(constructorFunction) { + constructorFunction.prototype[OBSERVED] = true; +} +exports.Observed = Observed; +const OBSERVED = "__ObservedByArkUI__"; +function isObserved(value) { + return value[OBSERVED] === true; +} +/** @internal */ +class ObservableHandler { + constructor(parent, observed = false) { + this.parents = new Set(); + this.children = new Map(); + this.observables = new Set(); + this._modified = false; + this.observed = observed; + if (parent) + this.addParent(parent); + } + onAccess() { + var _a; + if (this.observables.size > 0) { + const it = this.observables.keys(); + while (true) { + const result = it.next(); + if (result.done) + break; + (_a = result.value) === null || _a === void 0 ? void 0 : _a.onAccess(); + } + } + } + onModify() { + const set = new Set(); + this.collect(true, set); + set.forEach((handler) => { + var _a; + handler._modified = true; + if (handler.observables.size > 0) { + const it = handler.observables.keys(); + while (true) { + const result = it.next(); + if (result.done) + break; + (_a = result.value) === null || _a === void 0 ? void 0 : _a.onModify(); + } + } + }); + } + static dropModified(value) { + const handler = ObservableHandler.findIfObject(value); + if (handler === undefined) + return false; + const result = handler._modified; + handler._modified = false; + return result; + } + /** Adds the specified `observable` to the handler corresponding to the given `value`. */ + static attach(value, observable) { + const handler = ObservableHandler.findIfObject(value); + if (handler) + handler.observables.add(observable); + } + /** Deletes the specified `observable` from the handler corresponding to the given `value`. */ + static detach(value, observable) { + const handler = ObservableHandler.findIfObject(value); + if (handler) + handler.observables.delete(observable); + } + /** @returns the handler corresponding to the given `value` if it was installed */ + static findIfObject(value) { + const handlers = ObservableHandler.handlers; + return handlers !== undefined && value instanceof Object ? handlers.get(getObservableTarget(value)) : undefined; + } + /** + * @param value - any non-null object including arrays + * @returns an observable handler or `undefined` if it is not installed + */ + static find(value) { + const handlers = ObservableHandler.handlers; + return handlers ? handlers.get(getObservableTarget(value)) : undefined; + } + /** + * @param value - any non-null object including arrays + * @param observable - a handler to install on this object + * @throws an error if observable handler cannot be installed + */ + static installOn(value, observable) { + let handlers = ObservableHandler.handlers; + if (handlers === undefined) { + handlers = new WeakMap(); + ObservableHandler.handlers = handlers; + } + observable + ? handlers.set(getObservableTarget(value), observable) + : handlers.delete(getObservableTarget(value)); + } + addParent(parent) { + var _a; + const count = (_a = parent.children.get(this)) !== null && _a !== void 0 ? _a : 0; + parent.children.set(this, count + 1); + this.parents.add(parent); + } + removeParent(parent) { + var _a; + const count = (_a = parent.children.get(this)) !== null && _a !== void 0 ? _a : 0; + if (count > 1) { + parent.children.set(this, count - 1); + } + else if (count == 1) { + parent.children.delete(this); + this.parents.delete(parent); + } + } + removeChild(value) { + const child = ObservableHandler.findIfObject(value); + if (child) + child.removeParent(this); + } + collect(all, guards = new Set()) { + if (guards.has(this)) + return guards; // already collected + guards.add(this); // handler is already guarded + this.parents.forEach(handler => handler.collect(all, guards)); + if (all) + this.children.forEach((_count, handler) => handler.collect(all, guards)); + return guards; + } + static contains(observable, guards) { + if (observable.observed) + return true; + if (guards === undefined) + guards = new Set(); // create if needed + else if (guards.has(observable)) + return false; // already checked + guards.add(observable); // handler is already guarded + for (const it of observable.parents.keys()) { + if (ObservableHandler.contains(it, guards)) + return true; + } + return false; + } +} +exports.ObservableHandler = ObservableHandler; +ObservableHandler.handlers = undefined; +/** @internal */ +function observableProxyArray(...value) { + return observableProxy(value); +} +exports.observableProxyArray = observableProxyArray; +/** @internal */ +function observableProxy(value, parent, observed, strict = true) { + if (value instanceof ObservableHandler) + return value; // do not proxy a marker itself + if (value === null || !(value instanceof Object)) + return value; // only non-null object can be observable + const observable = ObservableHandler.find(value); + if (observable) { + if (parent) { + if (strict) + observable.addParent(parent); + if (observed === undefined) + observed = ObservableHandler.contains(parent); + } + if (observed) { + if (Array.isArray(value)) { + for (let index = 0; index < value.length; index++) { + value[index] = observableProxy(value[index], observable, observed, false); + } + } + else { + proxyFields(value, false, observable); + } + } + return value; + } + if (Array.isArray(value)) { + const handler = new ObservableHandler(parent); + const array = proxyChildrenOnly(value, handler, observed); + copyWithinObservable(array); + fillObservable(array); + popObservable(array); + pushObservable(array); + reverseObservable(array); + shiftObservable(array); + sortObservable(array); + spliceObservable(array); + unshiftObservable(array); + return proxyObject(array, handler); + } + if (value instanceof Date) { + const valueAsAny = value; + const handler = new ObservableHandler(parent); + const setMethods = new Set([ + "setFullYear", "setMonth", "setDate", "setHours", "setMinutes", "setSeconds", + "setMilliseconds", "setTime", "setUTCFullYear", "setUTCMonth", "setUTCDate", + "setUTCHours", "setUTCMinutes", "setUTCSeconds", "setUTCMilliseconds" + ]); + setMethods.forEach((method) => { + const originalMethod = method + 'Original'; + if (valueAsAny[originalMethod] !== undefined) { + return; + } + valueAsAny[originalMethod] = valueAsAny[method]; + valueAsAny[method] = function (...args) { + var _a; + (_a = ObservableHandler.find(this)) === null || _a === void 0 ? void 0 : _a.onModify(); + return this[originalMethod](...args); + }; + }); + return proxyObject(value, handler); + } + // TODO: support set/map + const handler = new ObservableHandler(parent, isObserved(value)); + if (handler.observed || observed) + proxyFields(value, true, handler); + return proxyObject(value, handler); +} +exports.observableProxy = observableProxy; +function proxyObject(value, observable) { + ObservableHandler.installOn(value, observable); + return new Proxy(value, { + get(target, property, receiver) { + var _a; + if (property == OBSERVABLE_TARGET) + return target; + const value = Reflect.get(target, property, receiver); + (_a = ObservableHandler.find(target)) === null || _a === void 0 ? void 0 : _a.onAccess(); + return typeof value == "function" + ? value.bind(target) + : value; + }, + set(target, property, value, receiver) { + const old = Reflect.get(target, property, receiver); + if (value === old) + return true; + const observable = ObservableHandler.find(target); + if (observable) { + observable.onModify(); + observable.removeChild(old); + const observed = ObservableHandler.contains(observable); + if (observed || Array.isArray(target)) { + value = observableProxy(value, observable, observed); + } + } + return Reflect.set(target, property, value, receiver); + }, + deleteProperty(target, property) { + var _a; + (_a = ObservableHandler.find(target)) === null || _a === void 0 ? void 0 : _a.onModify(); + delete target[property]; + return true; + }, + }); +} +function proxyFields(value, strict, parent) { + for (const name of Object.getOwnPropertyNames(value)) { + const descriptor = Object.getOwnPropertyDescriptor(value, name); + if (descriptor === null || descriptor === void 0 ? void 0 : descriptor.writable) + value[name] = observableProxy(value[name], parent, true, strict); + } +} +function proxyChildrenOnly(array, parent, observed) { + if (observed === undefined) + observed = ObservableHandler.contains(parent); + return array.map(it => observableProxy(it, parent, observed)); +} +function copyWithinObservable(array) { + if (array.copyWithinOriginal === undefined) { + array.copyWithinOriginal = array.copyWithin; + array.copyWithin = function (target, start, end) { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + return this.copyWithinOriginal(target, start, end); + }; + } +} +function fillObservable(array) { + if (array.fillOriginal === undefined) { + array.fillOriginal = array.fill; + array.fill = function (value, start, end) { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + if (observable) + value = observableProxy(value, observable); + return this.fillOriginal(value, start, end); + }; + } +} +function popObservable(array) { + if (array.popOriginal === undefined) { + array.popOriginal = array.pop; + array.pop = function (...args) { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + const result = this.popOriginal(...args); + if (observable) + observable.removeChild(result); + return result; + }; + } +} +function pushObservable(array) { + if (array.pushOriginal === undefined) { + array.pushOriginal = array.push; + array.push = function (...args) { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + if (observable) + args = proxyChildrenOnly(args, observable); + return this.pushOriginal(...args); + }; + } +} +function reverseObservable(array) { + if (array.reverseOriginal === undefined) { + array.reverseOriginal = array.reverse; + array.reverse = function () { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + return this.reverseOriginal(); + }; + } +} +function shiftObservable(array) { + if (array.shiftOriginal === undefined) { + array.shiftOriginal = array.shift; + array.shift = function (...args) { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + const result = this.shiftOriginal(...args); + if (observable) + observable.removeChild(result); + return result; + }; + } +} +function sortObservable(array) { + if (array.sortOriginal === undefined) { + array.sortOriginal = array.sort; + array.sort = function (compareFn) { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + return this.sortOriginal(compareFn); + }; + } +} +function spliceObservable(array) { + if (array.spliceOriginal === undefined) { + array.spliceOriginal = array.splice; + array.splice = function (start, deleteCount, ...items) { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + if (observable) + items = proxyChildrenOnly(items, observable); + if (deleteCount === undefined) + deleteCount = array.length; + const result = this.spliceOriginal(start, deleteCount, ...items); + if (observable && Array.isArray(result)) { + result.forEach(it => observable.removeChild(it)); + } + return result; + }; + } +} +function unshiftObservable(array) { + if (array.unshiftOriginal === undefined) { + array.unshiftOriginal = array.unshift; + array.unshift = function (...items) { + const observable = ObservableHandler.find(this); + observable === null || observable === void 0 ? void 0 : observable.onModify(); + if (observable) + items = proxyChildrenOnly(items, observable); + return this.unshiftOriginal(...items); + }; + } +} +//# sourceMappingURL=observable.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/performance.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/performance.d.ts new file mode 100644 index 000000000..ffff2ebb8 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/performance.d.ts @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022-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. + */ + +/** + * @returns the number of milliseconds elapsed since midnight, + * January 1, 1970 Universal Coordinated Time (UTC). + */ +export declare function timeNow(): number; +/** + * @param fractionDigits - number of digits after the decimal point [0 - 20] + * @returns a string representing a number in fixed-point notation + */ +export declare function numberToFixed(value: number, fractionDigits: number): string; +//# sourceMappingURL=performance.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/performance.js b/koala-wrapper/koalaui/compat/dist/src/typescript/performance.js new file mode 100644 index 000000000..faf020971 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/performance.js @@ -0,0 +1,34 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.numberToFixed = exports.timeNow = void 0; +/** + * @returns the number of milliseconds elapsed since midnight, + * January 1, 1970 Universal Coordinated Time (UTC). + */ +function timeNow() { + return performance.now(); +} +exports.timeNow = timeNow; +/** + * @param fractionDigits - number of digits after the decimal point [0 - 20] + * @returns a string representing a number in fixed-point notation + */ +function numberToFixed(value, fractionDigits) { + return value.toFixed(fractionDigits); +} +exports.numberToFixed = numberToFixed; +//# sourceMappingURL=performance.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/prop-deep-copy.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/prop-deep-copy.d.ts new file mode 100644 index 000000000..5248eba2d --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/prop-deep-copy.d.ts @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare function propDeepCopy(sourceObject: T): T; +//# sourceMappingURL=prop-deep-copy.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/prop-deep-copy.js b/koala-wrapper/koalaui/compat/dist/src/typescript/prop-deep-copy.js new file mode 100644 index 000000000..157cb42df --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/prop-deep-copy.js @@ -0,0 +1,88 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.propDeepCopy = void 0; +const observable_1 = require("./observable"); +/* + When decorating variables of complex types, + @Prop makes a deep copy, during which all types, + except primitive types, Map, Set, Date, and Array, will be lost. + */ +function propDeepCopy(sourceObject) { + if (!sourceObject || typeof sourceObject !== 'object') { + return sourceObject; + } + const copiedObjects = new Map(); + return recursiveDeepCopy(sourceObject); + function recursiveDeepCopy(sourceObject) { + if (!sourceObject || typeof sourceObject !== 'object') { + return sourceObject; + } + const storedObject = copiedObjects.get(sourceObject); + if (storedObject !== undefined) { + return storedObject; + } + const copy = copyDeepTrackable(sourceObject); + const objectToCopyFrom = (0, observable_1.getObservableTarget)(sourceObject); + Object.keys(objectToCopyFrom) + .forEach((key) => { + const property = objectToCopyFrom[key]; + if (typeof property === "function") { + Reflect.set(copy, key, property); + copy[key] = copy[key].bind(copy); + return; + } + Reflect.set(copy, key, recursiveDeepCopy(property)); + }); + return copy; + } + function copyDeepTrackable(sourceObject) { + if (sourceObject instanceof Set) { + const copy = new Set(); + Object.setPrototypeOf(copy, Object.getPrototypeOf(sourceObject)); + copiedObjects.set(sourceObject, copy); + for (const setKey of sourceObject.keys()) { + copy.add(recursiveDeepCopy(setKey)); + } + return copy; + } + if (sourceObject instanceof Map) { + const copy = new Map(); + Object.setPrototypeOf(copy, Object.getPrototypeOf(sourceObject)); + copiedObjects.set(sourceObject, copy); + for (const mapKey of sourceObject.keys()) { + copy.set(mapKey, recursiveDeepCopy(sourceObject.get(mapKey))); + } + return copy; + } + if (sourceObject instanceof Date) { + const copy = new Date(); + copy.setTime(sourceObject.getTime()); + Object.setPrototypeOf(copy, Object.getPrototypeOf(sourceObject)); + copiedObjects.set(sourceObject, copy); + return copy; + } + if (sourceObject instanceof Object) { + const copy = Array.isArray(sourceObject) ? [] : {}; + Object.setPrototypeOf(copy, Object.getPrototypeOf(sourceObject)); + copiedObjects.set(sourceObject, copy); + return copy; + } + return sourceObject; + } +} +exports.propDeepCopy = propDeepCopy; +//# sourceMappingURL=prop-deep-copy.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/reflection.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/reflection.d.ts new file mode 100644 index 000000000..231d7b525 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/reflection.d.ts @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare function lcClassName(object: Object): string; +//# sourceMappingURL=reflection.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/reflection.js b/koala-wrapper/koalaui/compat/dist/src/typescript/reflection.js new file mode 100644 index 000000000..73b3ff9e7 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/reflection.js @@ -0,0 +1,24 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lcClassName = void 0; +const ts_reflection_1 = require("./ts-reflection"); +function lcClassName(object) { + return (0, ts_reflection_1.className)(object).toLowerCase(); +} +exports.lcClassName = lcClassName; +//# sourceMappingURL=reflection.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/strings.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/strings.d.ts new file mode 100644 index 000000000..3af44f725 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/strings.d.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "./types"; +interface SystemTextEncoder { + encode(input?: string): Uint8Array; + encodeInto(src: string, dest: Uint8Array): void; +} +interface WithStreamOption { + stream?: boolean | undefined; +} +interface SystemTextDecoder { + decode(input?: ArrayBuffer | null, options?: WithStreamOption): string; +} +export declare class CustomTextEncoder { + static readonly HeaderLen: int32; + constructor(encoder?: SystemTextEncoder | undefined); + private readonly encoder; + static stringLength(input: string): int32; + encodedLength(input: string): int32; + private addLength; + static getHeaderLength(array: Uint8Array, offset?: int32): int32; + encode(input: string | undefined, addLength?: boolean): Uint8Array; + encodeArray(strings: Array): Uint8Array; + encodeInto(input: string, result: Uint8Array, position: int32): Uint8Array; +} +export declare class CustomTextDecoder { + static cpArrayMaxSize: number; + constructor(decoder?: SystemTextDecoder | undefined); + private readonly decoder; + decode(input: Uint8Array): string; +} +export {}; +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/strings.js b/koala-wrapper/koalaui/compat/dist/src/typescript/strings.js new file mode 100644 index 000000000..a2419d0a2 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/strings.js @@ -0,0 +1,189 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CustomTextDecoder = exports.CustomTextEncoder = void 0; +class CustomTextEncoder { + constructor(encoder = ((typeof TextEncoder != "undefined") ? new TextEncoder() : undefined)) { + this.encoder = encoder; + } + static stringLength(input) { + let length = 0; + for (let i = 0; i < input.length; i++) { + length++; + let cp = input.codePointAt(i); + if (cp >= 0x10000) { + i++; + } + } + return length; + } + encodedLength(input) { + let length = 0; + for (let i = 0; i < input.length; i++) { + let cp = input.codePointAt(i); + if (cp < 0x80) { + length += 1; + } + else if (cp < 0x800) { + length += 2; + } + else if (cp < 0x10000) { + length += 3; + } + else { + length += 4; + i++; + } + } + return length; + } + addLength(array, offset, len) { + array[offset] = (len & 0xff); + array[offset + 1] = ((len >> 8) & 0xff); + array[offset + 2] = ((len >> 16) & 0xff); + array[offset + 3] = ((len >> 24) & 0xff); + } + static getHeaderLength(array, offset = 0) { + return (array[offset] | (array[offset + 1] << 8) | (array[offset + 2] << 16) | (array[offset + 3] << 24)); + } + // Produces array of bytes with encoded string headed by 4 bytes (little endian) size information: + // [s0][s1][s2][s3] [c_0] ... [c_size-1] + encode(input, addLength = true) { + let headerLen = addLength ? CustomTextEncoder.HeaderLen : 0; + let result; + if (!input) { + result = new Uint8Array(headerLen); + } + else if (this.encoder !== undefined) { + result = this.encoder.encode('s'.repeat(headerLen) + input); + } + else { + let length = this.encodedLength(input); + result = new Uint8Array(length + headerLen); + this.encodeInto(input, result, headerLen); + } + if (addLength) { + this.addLength(result, 0, result.length - headerLen); + } + return result; + } + // Produces encoded array of strings with size information. + encodeArray(strings) { + let totalBytes = CustomTextEncoder.HeaderLen; + let lengths = new Int32Array(strings.length); + for (let i = 0; i < lengths.length; i++) { + let len = this.encodedLength(strings[i]); + lengths[i] = len; + totalBytes += len + CustomTextEncoder.HeaderLen; + } + let array = new Uint8Array(totalBytes); + let position = 0; + this.addLength(array, position, lengths.length); + position += CustomTextEncoder.HeaderLen; + for (let i = 0; i < lengths.length; i++) { + this.addLength(array, position, lengths[i]); + position += CustomTextEncoder.HeaderLen; + this.encodeInto(strings[i], array, position); + position += lengths[i]; + } + return array; + } + encodeInto(input, result, position) { + if (this.encoder !== undefined) { + this.encoder.encodeInto(input, result.subarray(position, result.length)); + return result; + } + let index = position; + for (let stringPosition = 0; stringPosition < input.length; stringPosition++) { + let cp = input.codePointAt(stringPosition); + if (cp < 0x80) { + result[index++] = (cp | 0); + } + else if (cp < 0x800) { + result[index++] = ((cp >> 6) | 0xc0); + result[index++] = ((cp & 0x3f) | 0x80); + } + else if (cp < 0x10000) { + result[index++] = ((cp >> 12) | 0xe0); + result[index++] = (((cp >> 6) & 0x3f) | 0x80); + result[index++] = ((cp & 0x3f) | 0x80); + } + else { + result[index++] = ((cp >> 18) | 0xf0); + result[index++] = (((cp >> 12) & 0x3f) | 0x80); + result[index++] = (((cp >> 6) & 0x3f) | 0x80); + result[index++] = ((cp & 0x3f) | 0x80); + stringPosition++; + } + } + result[index] = 0; + return result; + } +} +exports.CustomTextEncoder = CustomTextEncoder; +CustomTextEncoder.HeaderLen = Int32Array.BYTES_PER_ELEMENT; +class CustomTextDecoder { + constructor(decoder = ((typeof TextDecoder != "undefined") ? new TextDecoder() : undefined)) { + this.decoder = decoder; + } + decode(input) { + if (this.decoder !== undefined) { + return this.decoder.decode(input); + } + const cpSize = Math.min(CustomTextDecoder.cpArrayMaxSize, input.length); + let codePoints = new Int32Array(cpSize); + let cpIndex = 0; + let index = 0; + let result = ""; + while (index < input.length) { + let elem = input[index]; + let lead = elem & 0xff; + let count = 0; + let value = 0; + if (lead < 0x80) { + count = 1; + value = elem; + } + else if ((lead >> 5) == 0x6) { + value = ((elem << 6) & 0x7ff) + (input[index + 1] & 0x3f); + count = 2; + } + else if ((lead >> 4) == 0xe) { + value = ((elem << 12) & 0xffff) + ((input[index + 1] << 6) & 0xfff) + + (input[index + 2] & 0x3f); + count = 3; + } + else if ((lead >> 3) == 0x1e) { + value = ((elem << 18) & 0x1fffff) + ((input[index + 1] << 12) & 0x3ffff) + + ((input[index + 2] << 6) & 0xfff) + (input[index + 3] & 0x3f); + count = 4; + } + codePoints[cpIndex++] = value; + if (cpIndex == cpSize) { + cpIndex = 0; + result += String.fromCodePoint(...codePoints); + } + index += count; + } + if (cpIndex > 0) { + result += String.fromCodePoint(...codePoints.slice(0, cpIndex)); + } + return result; + } +} +exports.CustomTextDecoder = CustomTextDecoder; +CustomTextDecoder.cpArrayMaxSize = 128; +//# sourceMappingURL=strings.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/ts-reflection.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/ts-reflection.d.ts new file mode 100644 index 000000000..3d013c4d5 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/ts-reflection.d.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare function className(object?: Object): string; +export declare function isFunction(object?: Object): boolean; +export declare function functionOverValue(value: Value | (() => Value)): boolean; +export declare function refEqual(a: Value, b: Value): boolean; +export declare function isNotPrimitive(value: Object): boolean; +//# sourceMappingURL=ts-reflection.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/ts-reflection.js b/koala-wrapper/koalaui/compat/dist/src/typescript/ts-reflection.js new file mode 100644 index 000000000..c2ba31757 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/ts-reflection.js @@ -0,0 +1,40 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNotPrimitive = exports.refEqual = exports.functionOverValue = exports.isFunction = exports.className = void 0; +function className(object) { + var _a; + return (_a = object === null || object === void 0 ? void 0 : object.constructor.name) !== null && _a !== void 0 ? _a : ""; +} +exports.className = className; +function isFunction(object) { + return typeof object === 'function'; +} +exports.isFunction = isFunction; +// TODO: this is to match arkts counterpart +function functionOverValue(value) { + return typeof value === 'function'; +} +exports.functionOverValue = functionOverValue; +function refEqual(a, b) { + return a === b; +} +exports.refEqual = refEqual; +function isNotPrimitive(value) { + return true; +} +exports.isNotPrimitive = isNotPrimitive; +//# sourceMappingURL=ts-reflection.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/types.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/types.d.ts new file mode 100644 index 000000000..3a8beb40c --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/types.d.ts @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022-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. + */ + +/// +export type uint8 = int; +export type int8 = int; +export type int16 = int; +export type int32 = int; +export type uint32 = int; +export type int64 = long; +export type uint64 = long; +export type float32 = float; +export type float64 = double; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/types.js b/koala-wrapper/koalaui/compat/dist/src/typescript/types.js new file mode 100644 index 000000000..af49665f4 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/types.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +/// +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/utils.d.ts b/koala-wrapper/koalaui/compat/dist/src/typescript/utils.d.ts new file mode 100644 index 000000000..f359d5f17 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/utils.d.ts @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare function unsafeCast(value: unknown): T; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/dist/src/typescript/utils.js b/koala-wrapper/koalaui/compat/dist/src/typescript/utils.js new file mode 100644 index 000000000..ec1727664 --- /dev/null +++ b/koala-wrapper/koalaui/compat/dist/src/typescript/utils.js @@ -0,0 +1,22 @@ +"use strict"; +/* + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unsafeCast = void 0; +function unsafeCast(value) { + return value; +} +exports.unsafeCast = unsafeCast; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/compat/src/arkts/array.ts b/koala-wrapper/koalaui/compat/src/arkts/array.ts new file mode 100644 index 000000000..123dd33d7 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/array.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float64, int32, int8 } from "./types" + +// TODO: this can be a performance disaster +// just wait for the library to provide the proper functionality. +export function asArray(value: T[]): Array { + return Array.of(...value) +} + +// TODO: this can be a performance disaster +// just wait for the library to provide the proper functionality. +export function Array_from_set(set: Set): Array { + const array = new Array() // to avoid creation of undefined content + const values = set.values() + for (let it = values.next(); it.done != true; it = values.next()) { + array.push(it.value as T) + } + return array +} + +// TODO: this can be a performance disaster +// just wait for the library to provide the proper functionality. +export function Array_from_int32(data: Int32Array): number[] { + const result: number[] = [] + for (let i: int32 = 0; i < data.length; i++) { + result[i] = data.at(i) as number + } + return result +} + +// TODO: this can be a performance disaster +// just wait for the library to provide the proper functionality. +export function Array_from_number(data: float64[]): Array { + const result = new Array(data.length) + for (let i: int32 = 0; i < data.length; i++) { + result[i] = data[i] + } + return result +} + +export function int8Array(size: int32): int8[] { + return new int8[size] +} + diff --git a/koala-wrapper/koalaui/compat/src/arkts/atomic.ts b/koala-wrapper/koalaui/compat/src/arkts/atomic.ts new file mode 100644 index 000000000..241b0944c --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/atomic.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022-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. + */ + +/** + * A reference that may be updated atomically. + */ +export class AtomicRef { + value: Value + + /** + * Creates a new reference object with the given initial value. + * @param value - the new value + */ + constructor(value: Value) { + this.value = value + } + + /** + * Atomically sets the reference value to the given value and returns the previous one. + * @param value - the new value + * @returns the previous value + */ + getAndSet(value: Value): Value { + // TODO: replace with the implementation from ArkTS language when it is ready + const result = this.value + this.value = value + return result + } +} diff --git a/koala-wrapper/koalaui/compat/src/arkts/double.ts b/koala-wrapper/koalaui/compat/src/arkts/double.ts new file mode 100644 index 000000000..0dfb7fea3 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/double.ts @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float64, int32, float32 } from "./types" + +export function asFloat64(value: string): float64 { + return (new Number(value)).valueOf() +} + +export function asString(value: float64 | undefined): string | undefined { + if (value === undefined) return undefined + return (new Number(value)).toString() +} + +export function float32FromBits(value: int32): float32 { + return Float.bitCastFromInt(value) +} + +export function int32BitsFromFloat(value: float32): int32 { + return Float.bitCastToInt(value) +} diff --git a/koala-wrapper/koalaui/compat/src/arkts/finalization.ts b/koala-wrapper/koalaui/compat/src/arkts/finalization.ts new file mode 100644 index 000000000..92ba81b14 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/finalization.ts @@ -0,0 +1,31 @@ + +/* + * 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. + */ + +export interface Thunk { + clean(): void +} + +const registry = new FinalizationRegistry((thunk: Thunk) => { + thunk.clean() +}) + +export function finalizerRegister(target: Object, thunk: Object) { + registry.register(target, thunk as Thunk) +} + +export function finalizerUnregister(target: Object) { + registry.unregister(target) +} diff --git a/koala-wrapper/koalaui/compat/src/arkts/index.ts b/koala-wrapper/koalaui/compat/src/arkts/index.ts new file mode 100644 index 000000000..c6077254c --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/index.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022-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. + */ + +export * from "./array" +export * from "./atomic" +export * from "./double" +export * from "./finalization" +export * from "./performance" +export * from "./prop-deep-copy" +export * from "./observable" +export * from "./reflection" +export * from "./strings" +export * from "./ts-reflection" +export * from "./types" +export * from "./utils" diff --git a/koala-wrapper/koalaui/compat/src/arkts/observable.ts b/koala-wrapper/koalaui/compat/src/arkts/observable.ts new file mode 100644 index 000000000..4326f0122 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/observable.ts @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "./types" + +const OBSERVABLE_TARGET = "target" + +export function getObservableTarget(proxy: Object): Object { + try { + return Reflect.get(proxy, OBSERVABLE_TARGET) ?? proxy + } catch (error) { + return proxy + } +} + +/** + * Data class decorator that makes all child fields trackable. + */ +export function Observed() { + throw new Error("TypeScript class decorators are not supported yet") +} + +/** @internal */ +export interface Observable { + /** It is called when the observable value is accessed. */ + onAccess(): void + /** It is called when the observable value is modified. */ + onModify(): void +} + +/** @internal */ +export class ObservableHandler implements Observable { + private static handlers: WeakMap | undefined = undefined + + private parents = new Set() + private children = new Map() + + private readonly observables = new Set() + private _modified = false + + readonly observed: boolean + constructor(parent?: ObservableHandler, observed: boolean = false) { + this.observed = observed + if (parent) this.addParent(parent) + } + + onAccess(): void { + if (this.observables.size > 0) { + const it = this.observables.keys() + while (true) { + const result = it.next() + if (result.done) break + result.value?.onAccess() + } + } + } + + onModify(): void { + const set = new Set() + this.collect(true, set) + set.forEach((handler: ObservableHandler) => { + handler._modified = true + if (handler.observables.size > 0) { + const it = handler.observables.keys() + while (true) { + const result = it.next() + if (result.done) break + result.value?.onModify() + } + } + }) + } + + static dropModified(value: Value): boolean { + const handler = ObservableHandler.findIfObject(value) + if (handler === undefined) return false + const result = handler._modified + handler._modified = false + return result + } + + /** Adds the specified `observable` to the handler corresponding to the given `value`. */ + static attach(value: Value, observable: Observable): void { + const handler = ObservableHandler.findIfObject(value) + if (handler) handler.observables.add(observable) + } + + /** Deletes the specified `observable` from the handler corresponding to the given `value`. */ + static detach(value: Value, observable: Observable): void { + const handler = ObservableHandler.findIfObject(value) + if (handler) handler.observables.delete(observable) + } + + /** @returns the handler corresponding to the given `value` if it was installed */ + private static findIfObject(value: Value): ObservableHandler | undefined { + const handlers = ObservableHandler.handlers + return handlers !== undefined && value instanceof Object ? handlers.get(getObservableTarget(value as Object)) : undefined + } + + /** + * @param value - any non-null object including arrays + * @returns an observable handler or `undefined` if it is not installed + */ + static find(value: Object): ObservableHandler | undefined { + const handlers = ObservableHandler.handlers + return handlers ? handlers.get(getObservableTarget(value)) : undefined + } + + /** + * @param value - any non-null object including arrays + * @param observable - a handler to install on this object + * @throws an error if observable handler cannot be installed + */ + static installOn(value: Object, observable?: ObservableHandler): void { + let handlers = ObservableHandler.handlers + if (handlers === undefined) { + handlers = new WeakMap() + ObservableHandler.handlers = handlers + } + observable + ? handlers.set(getObservableTarget(value), observable) + : handlers.delete(getObservableTarget(value)) + } + + addParent(parent: ObservableHandler) { + const count = parent.children.get(this) ?? 0 + parent.children.set(this, count + 1) + this.parents.add(parent) + } + + removeParent(parent: ObservableHandler) { + const count = parent.children.get(this) ?? 0 + if (count > 1) { + parent.children.set(this, count - 1) + } + else if (count == 1) { + parent.children.delete(this) + this.parents.delete(parent) + } + } + + removeChild(value: Value) { + const child = ObservableHandler.findIfObject(value) + if (child) child.removeParent(this) + } + + private collect(all: boolean, guards: Set) { + if (guards.has(this)) return guards // already collected + guards.add(this) // handler is already guarded + this.parents.forEach((handler: ObservableHandler) => { handler.collect(all, guards) }) + if (all) this.children.forEach((_count: number, handler: ObservableHandler) => { handler.collect(all, guards) }) + return guards + } + + static contains(observable: ObservableHandler, guards?: Set) { + if (observable.observed) return true + if (guards === undefined) guards = new Set() // create if needed + else if (guards!.has(observable)) return false // already checked + guards.add(observable) // handler is already guarded + for (const it of observable.parents.keys()) { + if (ObservableHandler.contains(it, guards)) return true + } + return false + } +} + +/** @internal */ +export function observableProxyArray(...value: Value[]): Array { + return observableProxy(Array.of(...value)) +} + +const PROXY_DISABLED = true // because of ArkTS Reflection performance + +/** @internal */ +export function observableProxy(value: Value, parent?: ObservableHandler, observed?: boolean, strict: boolean = true): Value { + if (PROXY_DISABLED) return value + if (value instanceof ObservableHandler) return value as Value // do not proxy a marker itself + if (value == null || !(value instanceof Object)) return value as Value // only non-null object can be observable + const observable = ObservableHandler.find(value as Object) + if (observable) { + if (parent) { + if (strict) observable.addParent(parent) + if (observed === undefined) observed = ObservableHandler.contains(parent) + } + if (observed) { + if (value instanceof Array) { + for (let index = 0; index < value.length; index++) { + value[index] = observableProxy(value[index], observable, observed, false) + } + } else { + // TODO: proxy fields of the given object + } + } + return value as Value + } + if (value instanceof Array) { + const handler = new ObservableHandler(parent) + const array = proxyChildrenOnly(value, handler, observed) + ObservableHandler.installOn(array, handler) + return createProxyArray(array) as Value + } + // TODO: proxy the given object + return value as Value +} + +function createProxyArray(array: Array): Array { + return Proxy.create(array, new CustomArrayProxyHandler()) +} + +function proxyChildrenOnly(array: Array, parent: ObservableHandler, observed?: boolean): Array { + if (observed === undefined) observed = ObservableHandler.contains(parent) + return array.map((it: T) => observableProxy(it, parent, observed)) +} + +class CustomArrayProxyHandler extends DefaultArrayProxyHandler { + override get(target: Array, index: int32): T { + const observable = ObservableHandler.find(target) + if (observable) observable.onAccess() + return super.get(target, index) + } + + override set(target: Array, index: int32, value: T): boolean { + const observable = ObservableHandler.find(target) + if (observable) { + observable.onModify() + observable.removeChild(super.get(target, index)) + value = observableProxy(value, observable, ObservableHandler.contains(observable)) + } + return super.set(target, index, value) + } + + override get(target: Array, name: string): NullishType { + const observable = ObservableHandler.find(target) + if (observable) observable.onAccess() + return super.get(target, name) + } + + override set(target: Array, name: string, value: NullishType): boolean { + const observable = ObservableHandler.find(target) + if (observable) { + observable.onModify() + observable.removeChild(super.get(target, name)) + value = observableProxy(value, observable, ObservableHandler.contains(observable)) + } + return super.set(target, name, value) + } + + override invoke(target: Array, method: Method, args: NullishType[]): NullishType { + const observable = ObservableHandler.find(target) + if (observable) { + const name = method.getName() + if (name == "copyWithin" || name == "reverse" || name == "sort") { + observable.onModify() + return super.invoke(target, method, args) + } + if (name == "fill") { + observable.onModify() + if (args.length > 0) { + args[0] = observableProxy(args[0], observable) + } + return super.invoke(target, method, args) + } + if (name == "pop" || name == "shift") { + observable.onModify() + const result = super.invoke(target, method, args) + observable.removeChild(result) + return result + } + if (name == "push" || name == "unshift") { + observable.onModify() + if (args.length > 0) { + const items = args[0] + if (items instanceof Array) { + args[0] = proxyChildrenOnly(items, observable) + } + } + return super.invoke(target, method, args) + } + if (name == "splice") { + observable.onModify() + if (args.length > 2) { + const items = args[2] + if (items instanceof Array) { + args[2] = proxyChildrenOnly(items, observable) + } + } + const result = super.invoke(target, method, args) + if (result instanceof Array) { + for (let i = 0; i < result.length; i++) { + observable.removeChild(result[i]) + } + } + return result + } + observable.onAccess() + } + return super.invoke(target, method, args) + } +} diff --git a/koala-wrapper/koalaui/compat/src/arkts/performance.ts b/koala-wrapper/koalaui/compat/src/arkts/performance.ts new file mode 100644 index 000000000..2755960e8 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/performance.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022-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. + */ + +/** + * @returns the number of milliseconds elapsed since midnight, + * January 1, 1970 Universal Coordinated Time (UTC). + */ +export function timeNow(): number { + return Date.now() +} + +/** + * @param fractionDigits - number of digits after the decimal point [0 - 20] + * @returns a string representing a number in fixed-point notation + */ +export function numberToFixed(value: number, fractionDigits: number): string { + return new Number(value).toFixed(fractionDigits) +} diff --git a/koala-wrapper/koalaui/compat/src/arkts/prop-deep-copy.ts b/koala-wrapper/koalaui/compat/src/arkts/prop-deep-copy.ts new file mode 100644 index 000000000..25ec18c81 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/prop-deep-copy.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022-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. + */ + +/* + When decorating variables of complex types, + @Prop makes a deep copy, during which all types, + except primitive types, Map, Set, Date, and Array, will be lost. + */ + +export function propDeepCopy(sourceObject: T): T { + return sourceObject +} diff --git a/koala-wrapper/koalaui/compat/src/arkts/reflection.ts b/koala-wrapper/koalaui/compat/src/arkts/reflection.ts new file mode 100644 index 000000000..75bdadc33 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/reflection.ts @@ -0,0 +1,22 @@ + +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { className } from "./ts-reflection" + +export function lcClassName(object: Object) { + return className(object).toLowerCase() +} + +export @interface Entry {} diff --git a/koala-wrapper/koalaui/compat/src/arkts/strings.ts b/koala-wrapper/koalaui/compat/src/arkts/strings.ts new file mode 100644 index 000000000..b0129c085 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/strings.ts @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32, uint8 } from "./types" +import { Array_from_int32 } from "./array" + + +interface SystemTextEncoder { + encode(input?: string): Uint8Array; + encodeInto(src: string, dest: Uint8Array): void; +} + +interface WithStreamOption { + stream: Boolean | undefined; +} + +interface SystemTextDecoder { + decode( + input: ArrayBuffer | null | undefined | Uint8Array, + options: WithStreamOption | undefined + ): string; +} + +export class CustomTextEncoder { + static readonly HeaderLen: int32 = Int32Array.BYTES_PER_ELEMENT + + constructor(encoder:SystemTextEncoder|undefined = undefined) { + this.encoder = encoder + } + + private readonly encoder: SystemTextEncoder|undefined + + public static stringLength(input: string): int32 { + let length = 0 + for (let i = 0; i < input.length; i++) { + length++ + let cp = input.codePointAt(i)! + if (cp >= 0x10000) { + i++ + } + } + return length + } + + encodedLength(input: string): int32 { + let length = 0 + for (let i = 0; i < input.length; i++) { + let cp = input.codePointAt(i)! + if (cp < 0x80) { + length += 1 + } else if (cp < 0x800) { + length += 2 + } else if (cp < 0x10000) { + length += 3 + } else { + length += 4 + i++ + } + } + return length + } + + private addLength(array: Uint8Array, offset: int32, length: int32 | number): void { + const len = length as int32 + array.set(offset, len & 0xff) + array.set(offset + 1, (len >> 8) & 0xff) + array.set(offset + 2, (len >> 16) & 0xff) + array.set(offset + 3, (len >> 24) & 0xff) + } + + static getHeaderLength(array: Uint8Array, offset: int32 = 0): int32 { + return ( + (array.at(offset) as int32) | + (array.at(((offset + 1) << 8)) as int32) | + (array.at((offset + 2) << 16) as int32) | + (array.at((offset + 3) << 24)) as int32) + } + + // Produces array of bytes with encoded string headed by 4 bytes (little endian) size information: + // [s0][s1][s2][s3] [c_0] ... [c_size-1] + encode(input: string | undefined, addLength: boolean = true): Uint8Array { + let headerLen = addLength ? CustomTextEncoder.HeaderLen : 0 + let result: Uint8Array + if (!input) { + result = new Uint8Array(headerLen) + } else if (this.encoder !== undefined) { + result = this.encoder!.encode('s'.repeat(headerLen) + input) + } else { + let length = this.encodedLength(input) + result = new Uint8Array(length + headerLen) + this.encodeInto(input, result, headerLen) + } + if (addLength) { + this.addLength(result, 0, (result.length - headerLen) as int32) + } + return result + } + + // Produces encoded array of strings with size information. + encodeArray(strings: Array): Uint8Array { + let totalBytes = CustomTextEncoder.HeaderLen + let lengths = new Int32Array(strings.length) + for (let i = 0; i < lengths.length; i++) { + let len = this.encodedLength(strings[i]) + lengths[i] = len + totalBytes += len + CustomTextEncoder.HeaderLen + } + let array = new Uint8Array(totalBytes) + let position = 0 + this.addLength(array, position, lengths.length as int32) + position += CustomTextEncoder.HeaderLen + for (let i = 0; i < lengths.length; i++) { + this.addLength(array, position, lengths[i] as int32) + position += CustomTextEncoder.HeaderLen + this.encodeInto(strings[i], array, position) + position += lengths[i] + } + return array + } + + encodeInto(input: string, result: Uint8Array, position: int32): Uint8Array { + if (this.encoder !== undefined) { + this.encoder!.encodeInto(input, result.subarray(position, result.length)) + return result + } + let index = position + for (let stringPosition = 0; stringPosition < input.length; stringPosition++) { + let cp = input.codePointAt(stringPosition)! + if (cp < 0x80) { + result[index++] = (cp | 0) + } else if (cp < 0x800) { + result[index++] = ((cp >> 6) | 0xc0) + result[index++] = ((cp & 0x3f) | 0x80) + } else if (cp < 0x10000) { + result[index++] = ((cp >> 12) | 0xe0) + result[index++] = (((cp >> 6) & 0x3f) | 0x80) + result[index++] = ((cp & 0x3f) | 0x80) + } else { + result[index++] = ((cp >> 18) | 0xf0) + result[index++] = (((cp >> 12) & 0x3f) | 0x80) + result[index++] = (((cp >> 6) & 0x3f) | 0x80) + result[index++] = ((cp & 0x3f) | 0x80) + stringPosition++ + } + } + result[index] = 0 + return result + } +} + +export class CustomTextDecoder { + static cpArrayMaxSize = 128 + constructor(decoder: SystemTextDecoder|undefined = undefined) { + this.decoder = decoder + } + + private readonly decoder: SystemTextDecoder|undefined + + decode(input: Uint8Array): string { + if (this.decoder !== undefined) { + return this.decoder!.decode(input, undefined) + } + + const cpSize = Math.min(CustomTextDecoder.cpArrayMaxSize, input.length) + let codePoints = new Int32Array(cpSize) + let cpIndex = 0; + let index = 0 + let result = "" + while (index < input.length) { + let elem = input[index] as uint8 + let lead = elem & 0xff + let count = 0 + let value = 0 + if (lead < 0x80) { + count = 1 + value = elem + } else if ((lead >> 5) == 0x6) { + value = (((elem << 6) & 0x7ff) + (input[index + 1] & 0x3f)) as int32 + count = 2 + } else if ((lead >> 4) == 0xe) { + value = (((elem << 12) & 0xffff) + ((input[index + 1] << 6) & 0xfff) + + (input[index + 2] & 0x3f)) as int32 + count = 3 + } else if ((lead >> 3) == 0x1e) { + value = (((elem << 18) & 0x1fffff) + ((input[index + 1] << 12) & 0x3ffff) + + ((input[index + 2] << 6) & 0xfff) + (input[index + 3] & 0x3f)) as int32 + count = 4 + } + codePoints[cpIndex++] = value + if (cpIndex == cpSize) { + cpIndex = 0 + //result += String.fromCodePoint(...codePoints) + result += String.fromCodePoint(...Array_from_int32(codePoints)) + } + index += count + } + if (cpIndex > 0) { + result += String.fromCodePoint(...Array_from_int32(codePoints.slice(0, cpIndex))) + } + return result + } +} diff --git a/koala-wrapper/koalaui/compat/src/arkts/ts-reflection.ts b/koala-wrapper/koalaui/compat/src/arkts/ts-reflection.ts new file mode 100644 index 000000000..0214ccf02 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/ts-reflection.ts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022-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. + */ + +export function className(object?: Object): string { + return object ? (Type.of(object) as ClassType).getName() : "null" +} + +export function isFunction(object?: Object): boolean { + return Type.of(object) instanceof FunctionType +} + +// TODO: This is an very ad hoc function, +// but I could not find in ArkTS stdlib enough functionality +// for a more generic way. +export function functionOverValue(value: Value|(()=>Value)): boolean { + return Type.of(value) instanceof FunctionType +} + +// Somehow es2panda only allows === on reference types. +export function refEqual(a: Value, b: Value): boolean { + return a == b +} + +export function isNotPrimitive(value: Object): boolean { + return !Type.of(value).isPrimitive() +} diff --git a/koala-wrapper/koalaui/compat/src/arkts/types.ts b/koala-wrapper/koalaui/compat/src/arkts/types.ts new file mode 100644 index 000000000..3f4d932f4 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/types.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022-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. + */ + +export type uint8 = byte +export type int8 = byte +export type unt16 = short +export type int16 = short +export type int32 = int +export type uint32 = int +export type int64 = long +export type uint64 = long +export type float32 = float +export type float64 = double diff --git a/koala-wrapper/koalaui/compat/src/arkts/utils.ts b/koala-wrapper/koalaui/compat/src/arkts/utils.ts new file mode 100644 index 000000000..45c74d2e4 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/arkts/utils.ts @@ -0,0 +1,18 @@ +/* + * 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. + */ + +export function unsafeCast(value: Object): T { + return value as T +} diff --git a/koala-wrapper/koalaui/compat/src/index.ts b/koala-wrapper/koalaui/compat/src/index.ts new file mode 100644 index 000000000..e2760b0c7 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/index.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022-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. + */ + +export { + asArray, + Array_from_set, + Array_from_int32, + Array_from_number, + AtomicRef, + asFloat64, + asString, + float32FromBits, + int32BitsFromFloat, + Thunk, + finalizerRegister, + finalizerUnregister, + timeNow, + numberToFixed, + Observed, + Observable, + ObservableHandler, + observableProxy, + observableProxyArray, + propDeepCopy, + lcClassName, + CustomTextEncoder, + CustomTextDecoder, + className, + isFunction, + functionOverValue, + refEqual, + isNotPrimitive, + uint8, + int8, + int16, + int32, + uint32, + int64, + uint64, + float32, + float64, + int8Array, + unsafeCast, +} from "#platform" diff --git a/koala-wrapper/koalaui/compat/src/ohos/index.ts b/koala-wrapper/koalaui/compat/src/ohos/index.ts new file mode 100644 index 000000000..b5bd901b4 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/ohos/index.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022-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. + */ + +export { + asArray, + Array_from_set, + Array_from_int32, + Array_from_number, + AtomicRef, + asFloat64, + asString, + float32FromBits, + int32BitsFromFloat, + Thunk, + finalizerRegister, + finalizerUnregister, + Observed, + Observable, + ObservableHandler, + observableProxy, + observableProxyArray, + propDeepCopy, + lcClassName, + CustomTextEncoder, + CustomTextDecoder, + className, + isFunction, + functionOverValue, + refEqual, + isNotPrimitive, + uint8, + int8, + int16, + int32, + uint32, + int64, + uint64, + float32, + float64, + int8Array, + unsafeCast, +} from "../typescript" + +export { + timeNow, + numberToFixed, +} from "./performance" diff --git a/koala-wrapper/koalaui/compat/src/ohos/performance.ts b/koala-wrapper/koalaui/compat/src/ohos/performance.ts new file mode 100644 index 000000000..2755960e8 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/ohos/performance.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022-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. + */ + +/** + * @returns the number of milliseconds elapsed since midnight, + * January 1, 1970 Universal Coordinated Time (UTC). + */ +export function timeNow(): number { + return Date.now() +} + +/** + * @param fractionDigits - number of digits after the decimal point [0 - 20] + * @returns a string representing a number in fixed-point notation + */ +export function numberToFixed(value: number, fractionDigits: number): string { + return new Number(value).toFixed(fractionDigits) +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/Types.d.ts b/koala-wrapper/koalaui/compat/src/typescript/Types.d.ts new file mode 100644 index 000000000..6b3ee5d94 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/Types.d.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2022-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. + */ + +type int = number +type long = number +type float = number +type double = number diff --git a/koala-wrapper/koalaui/compat/src/typescript/array.ts b/koala-wrapper/koalaui/compat/src/typescript/array.ts new file mode 100644 index 000000000..9392bb412 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/array.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float64, int32, int8 } from "./types" + +export function asArray(value: T[]): Array { + return value +} + +export function Array_from_set(set: Set): Array { + return Array.from(set) +} + +export function Array_from_int32(data: Int32Array): int32[] { + return Array.from(data) +} + +export function Array_from_number(data: float64[]): Array { + return data +} + +export function int8Array(size: int32): int8[] { + return [] +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/atomic.ts b/koala-wrapper/koalaui/compat/src/typescript/atomic.ts new file mode 100644 index 000000000..e6312b700 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/atomic.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022-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. + */ + +/** + * A reference that may be updated atomically. + */ +export class AtomicRef { + value: Value + + /** + * Creates a new reference object with the given initial value. + * @param value - the new value + */ + constructor(value: Value) { + this.value = value + } + + /** + * Atomically sets the reference value to the given value and returns the previous one. + * @param value - the new value + * @returns the previous value + */ + getAndSet(value: Value): Value { + const result = this.value + this.value = value + return result + } +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/double.ts b/koala-wrapper/koalaui/compat/src/typescript/double.ts new file mode 100644 index 000000000..ee4ad821e --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/double.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float64, int32, float32 } from "./types" + +export function asFloat64(value: string): float64 { + return Number(value) +} + +export function asString(value: float64 | undefined): string | undefined { + return value?.toString() +} + +export function float32FromBits(value: int32): float32 { + return value +} + +export function int32BitsFromFloat(value: float32): int32 { + return value +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/finalization.ts b/koala-wrapper/koalaui/compat/src/typescript/finalization.ts new file mode 100644 index 000000000..4aa68d116 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/finalization.ts @@ -0,0 +1,43 @@ + +/* + * 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. + */ + +export interface Thunk { + clean(): void +} + +interface FinalizationRegistry { + register(target: object, value: any, token?: object): void; + unregister(token: object): void; +} + +interface FinalizationRegistryConstructor { + readonly prototype: FinalizationRegistry; + new(callback: (value: any) => void): FinalizationRegistry; +} + +declare const FinalizationRegistry: FinalizationRegistryConstructor + +const registry = new FinalizationRegistry((thunk: Thunk) => { + thunk.clean() +}) + +export function finalizerRegister(target: object, thunk: object) { + registry.register(target, thunk) +} + +export function finalizerUnregister(target: object) { + registry.unregister(target) +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/index.ts b/koala-wrapper/koalaui/compat/src/typescript/index.ts new file mode 100644 index 000000000..84eed3cf9 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/index.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022-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. + */ + +export * from "./array" +export * from "./atomic" +export * from "./double" +export * from "./finalization" +export * from "./observable" +export * from "./performance" +export * from "./prop-deep-copy" +export * from "./reflection" +export * from "./strings" +export * from "./ts-reflection" +export * from "./types" +export * from "./utils" diff --git a/koala-wrapper/koalaui/compat/src/typescript/observable.ts b/koala-wrapper/koalaui/compat/src/typescript/observable.ts new file mode 100644 index 000000000..fd40fcdcf --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/observable.ts @@ -0,0 +1,404 @@ +/* + * Copyright (c) 2022-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. + */ + +const OBSERVABLE_TARGET = "__proxy_observable_target__" + +export function getObservableTarget(proxy: Object): Object { + return getPropertyValue(OBSERVABLE_TARGET, proxy) ?? proxy +} + +function getPropertyValue(name: string, object: any): any { + return object[name] +} + +/** + * Data class decorator that makes all child fields trackable. + */ +export function Observed(constructorFunction: Function) { + constructorFunction.prototype[OBSERVED] = true +} + +const OBSERVED = "__ObservedByArkUI__" +function isObserved(value: any): boolean { + return value[OBSERVED] === true +} + +/** @internal */ +export interface Observable { + /** It is called when the observable value is accessed. */ + onAccess(): void + /** It is called when the observable value is modified. */ + onModify(): void +} + +/** @internal */ +export class ObservableHandler implements Observable { + private static handlers: WeakMap | undefined = undefined + + private parents = new Set() + private children = new Map() + + private readonly observables = new Set() + private _modified = false + + readonly observed: boolean + constructor(parent?: ObservableHandler, observed: boolean = false) { + this.observed = observed + if (parent) this.addParent(parent) + } + + onAccess(): void { + if (this.observables.size > 0) { + const it = this.observables.keys() + while (true) { + const result = it.next() + if (result.done) break + result.value?.onAccess() + } + } + } + + onModify(): void { + const set = new Set() + this.collect(true, set) + set.forEach((handler: ObservableHandler) => { + handler._modified = true + if (handler.observables.size > 0) { + const it = handler.observables.keys() + while (true) { + const result = it.next() + if (result.done) break + result.value?.onModify() + } + } + }) + } + + static dropModified(value: Value): boolean { + const handler = ObservableHandler.findIfObject(value) + if (handler === undefined) return false + const result = handler._modified + handler._modified = false + return result + } + + /** Adds the specified `observable` to the handler corresponding to the given `value`. */ + static attach(value: Value, observable: Observable): void { + const handler = ObservableHandler.findIfObject(value) + if (handler) handler.observables.add(observable) + } + + /** Deletes the specified `observable` from the handler corresponding to the given `value`. */ + static detach(value: Value, observable: Observable): void { + const handler = ObservableHandler.findIfObject(value) + if (handler) handler.observables.delete(observable) + } + + /** @returns the handler corresponding to the given `value` if it was installed */ + private static findIfObject(value: Value): ObservableHandler | undefined { + const handlers = ObservableHandler.handlers + return handlers !== undefined && value instanceof Object ? handlers.get(getObservableTarget(value as Object)) : undefined + } + + /** + * @param value - any non-null object including arrays + * @returns an observable handler or `undefined` if it is not installed + */ + static find(value: Object): ObservableHandler | undefined { + const handlers = ObservableHandler.handlers + return handlers ? handlers.get(getObservableTarget(value)) : undefined + } + + /** + * @param value - any non-null object including arrays + * @param observable - a handler to install on this object + * @throws an error if observable handler cannot be installed + */ + static installOn(value: Object, observable?: ObservableHandler): void { + let handlers = ObservableHandler.handlers + if (handlers === undefined) { + handlers = new WeakMap() + ObservableHandler.handlers = handlers + } + observable + ? handlers.set(getObservableTarget(value), observable) + : handlers.delete(getObservableTarget(value)) + } + + addParent(parent: ObservableHandler) { + const count = parent.children.get(this) ?? 0 + parent.children.set(this, count + 1) + this.parents.add(parent) + } + + removeParent(parent: ObservableHandler) { + const count = parent.children.get(this) ?? 0 + if (count > 1) { + parent.children.set(this, count - 1) + } + else if (count == 1) { + parent.children.delete(this) + this.parents.delete(parent) + } + } + + removeChild(value: Value) { + const child = ObservableHandler.findIfObject(value) + if (child) child.removeParent(this) + } + + private collect(all: boolean, guards = new Set()) { + if (guards.has(this)) return guards // already collected + guards.add(this) // handler is already guarded + this.parents.forEach(handler => handler.collect(all, guards)) + if (all) this.children.forEach((_count, handler) => handler.collect(all, guards)) + return guards + } + + static contains(observable: ObservableHandler, guards?: Set) { + if (observable.observed) return true + if (guards === undefined) guards = new Set() // create if needed + else if (guards.has(observable)) return false // already checked + guards.add(observable) // handler is already guarded + for (const it of observable.parents.keys()) { + if (ObservableHandler.contains(it, guards)) return true + } + return false + } +} + +/** @internal */ +export function observableProxyArray(...value: Value[]): Array { + return observableProxy(value) +} + +/** @internal */ +export function observableProxy(value: Value, parent?: ObservableHandler, observed?: boolean, strict = true): Value { + if (value instanceof ObservableHandler) return value // do not proxy a marker itself + if (value === null || !(value instanceof Object)) return value // only non-null object can be observable + const observable = ObservableHandler.find(value) + if (observable) { + if (parent) { + if (strict) observable.addParent(parent) + if (observed === undefined) observed = ObservableHandler.contains(parent) + } + if (observed) { + if (Array.isArray(value)) { + for (let index = 0; index < value.length; index++) { + value[index] = observableProxy(value[index], observable, observed, false) + } + } else { + proxyFields(value, false, observable) + } + } + return value + } + if (Array.isArray(value)) { + const handler = new ObservableHandler(parent) + const array = proxyChildrenOnly(value, handler, observed) + copyWithinObservable(array) + fillObservable(array) + popObservable(array) + pushObservable(array) + reverseObservable(array) + shiftObservable(array) + sortObservable(array) + spliceObservable(array) + unshiftObservable(array) + return proxyObject(array, handler) + } + if (value instanceof Date) { + const valueAsAny = (value as any) + const handler = new ObservableHandler(parent) + const setMethods = new Set([ + "setFullYear", "setMonth", "setDate", "setHours", "setMinutes", "setSeconds", + "setMilliseconds", "setTime", "setUTCFullYear", "setUTCMonth", "setUTCDate", + "setUTCHours", "setUTCMinutes", "setUTCSeconds", "setUTCMilliseconds" + ]) + setMethods.forEach((method: string) => { + const originalMethod = method + 'Original' + if (valueAsAny[originalMethod] !== undefined) { + return + } + valueAsAny[originalMethod] = valueAsAny[method] + valueAsAny[method] = function (...args: any[]) { + ObservableHandler.find(this)?.onModify() + return this[originalMethod](...args) + } + }) + return proxyObject(value, handler) + } + // TODO: support set/map + const handler = new ObservableHandler(parent, isObserved(value)) + if (handler.observed || observed) proxyFields(value, true, handler) + return proxyObject(value, handler) +} + +function proxyObject(value: any, observable: ObservableHandler) { + ObservableHandler.installOn(value, observable) + return new Proxy(value, { + get(target, property, receiver) { + if (property == OBSERVABLE_TARGET) return target + const value: any = Reflect.get(target, property, receiver) + ObservableHandler.find(target)?.onAccess() + return typeof value == "function" + ? value.bind(target) + : value + }, + set(target, property, value, receiver) { + const old = Reflect.get(target, property, receiver) + if (value === old) return true + const observable = ObservableHandler.find(target) + if (observable) { + observable.onModify() + observable.removeChild(old) + const observed = ObservableHandler.contains(observable) + if (observed || Array.isArray(target)) { + value = observableProxy(value, observable, observed) + } + } + return Reflect.set(target, property, value, receiver) + }, + deleteProperty(target, property) { + ObservableHandler.find(target)?.onModify() + delete target[property] + return true + }, + }) +} + +function proxyFields(value: any, strict: boolean, parent?: ObservableHandler) { + for (const name of Object.getOwnPropertyNames(value)) { + const descriptor = Object.getOwnPropertyDescriptor(value, name) + if (descriptor?.writable) value[name] = observableProxy(value[name], parent, true, strict) + } +} + +function proxyChildrenOnly(array: any[], parent: ObservableHandler, observed?: boolean): any[] { + if (observed === undefined) observed = ObservableHandler.contains(parent) + return array.map(it => observableProxy(it, parent, observed)) +} + +function copyWithinObservable(array: any) { + if (array.copyWithinOriginal === undefined) { + array.copyWithinOriginal = array.copyWithin + array.copyWithin = function (this, target: number, start: number, end?: number) { + const observable = ObservableHandler.find(this) + observable?.onModify() + return this.copyWithinOriginal(target, start, end) + } + } +} + +function fillObservable(array: any) { + if (array.fillOriginal === undefined) { + array.fillOriginal = array.fill + array.fill = function (this, value: any, start?: number, end?: number) { + const observable = ObservableHandler.find(this) + observable?.onModify() + if (observable) value = observableProxy(value, observable) + return this.fillOriginal(value, start, end) + } + } +} + +function popObservable(array: any) { + if (array.popOriginal === undefined) { + array.popOriginal = array.pop + array.pop = function (...args: any[]) { + const observable = ObservableHandler.find(this) + observable?.onModify() + const result = this.popOriginal(...args) + if (observable) observable.removeChild(result) + return result + } + } +} + +function pushObservable(array: any) { + if (array.pushOriginal === undefined) { + array.pushOriginal = array.push + array.push = function (this, ...args: any[]) { + const observable = ObservableHandler.find(this) + observable?.onModify() + if (observable) args = proxyChildrenOnly(args, observable) + return this.pushOriginal(...args) + } + } +} + +function reverseObservable(array: any) { + if (array.reverseOriginal === undefined) { + array.reverseOriginal = array.reverse + array.reverse = function (this) { + const observable = ObservableHandler.find(this) + observable?.onModify() + return this.reverseOriginal() + } + } +} + +function shiftObservable(array: any) { + if (array.shiftOriginal === undefined) { + array.shiftOriginal = array.shift + array.shift = function (this, ...args: any[]) { + const observable = ObservableHandler.find(this) + observable?.onModify() + const result = this.shiftOriginal(...args) + if (observable) observable.removeChild(result) + return result + } + } +} + +function sortObservable(array: any) { + if (array.sortOriginal === undefined) { + array.sortOriginal = array.sort + array.sort = function (this, compareFn?: (a: any, b: any) => number) { + const observable = ObservableHandler.find(this) + observable?.onModify() + return this.sortOriginal(compareFn) + } + } +} + +function spliceObservable(array: any) { + if (array.spliceOriginal === undefined) { + array.spliceOriginal = array.splice + array.splice = function (this, start: number, deleteCount: number, ...items: any[]) { + const observable = ObservableHandler.find(this) + observable?.onModify() + if (observable) items = proxyChildrenOnly(items, observable) + if (deleteCount === undefined) deleteCount = array.length + const result = this.spliceOriginal(start, deleteCount, ...items) + if (observable && Array.isArray(result)) { + result.forEach(it => observable.removeChild(it)) + } + return result + } + } +} + +function unshiftObservable(array: any) { + if (array.unshiftOriginal === undefined) { + array.unshiftOriginal = array.unshift + array.unshift = function (this, ...items: any[]) { + const observable = ObservableHandler.find(this) + observable?.onModify() + if (observable) items = proxyChildrenOnly(items, observable) + return this.unshiftOriginal(...items) + } + } +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/performance.ts b/koala-wrapper/koalaui/compat/src/typescript/performance.ts new file mode 100644 index 000000000..80ea8a14e --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/performance.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022-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. + */ + +/** + * @returns the number of milliseconds elapsed since midnight, + * January 1, 1970 Universal Coordinated Time (UTC). + */ +export function timeNow(): number { + return performance.now() +} + +/** + * @param fractionDigits - number of digits after the decimal point [0 - 20] + * @returns a string representing a number in fixed-point notation + */ +export function numberToFixed(value: number, fractionDigits: number): string { + return value.toFixed(fractionDigits) +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/prop-deep-copy.ts b/koala-wrapper/koalaui/compat/src/typescript/prop-deep-copy.ts new file mode 100644 index 000000000..8da5c4f71 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/prop-deep-copy.ts @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { getObservableTarget } from "./observable" + +/* + When decorating variables of complex types, + @Prop makes a deep copy, during which all types, + except primitive types, Map, Set, Date, and Array, will be lost. + */ + +export function propDeepCopy(sourceObject: T): T { + if (!sourceObject || typeof sourceObject !== 'object') { + return sourceObject + } + + const copiedObjects = new Map() + return recursiveDeepCopy(sourceObject) as T + + function recursiveDeepCopy(sourceObject: Object): Object { + if (!sourceObject || typeof sourceObject !== 'object') { + return sourceObject + } + + const storedObject = copiedObjects.get(sourceObject) + if (storedObject !== undefined) { + return storedObject + } + + const copy: any = copyDeepTrackable(sourceObject) + + const objectToCopyFrom = getObservableTarget(sourceObject) + Object.keys(objectToCopyFrom) + .forEach((key) => { + const property = objectToCopyFrom[key as keyof Object] + + if (typeof property === "function") { + Reflect.set(copy, key, property) + copy[key] = copy[key].bind(copy) + return + } + Reflect.set(copy, key, recursiveDeepCopy(property)); + }) + + return copy + } + + function copyDeepTrackable(sourceObject: T): T { + if (sourceObject instanceof Set) { + const copy = new Set() + Object.setPrototypeOf(copy, Object.getPrototypeOf(sourceObject)) + copiedObjects.set(sourceObject, copy) + for (const setKey of sourceObject.keys()) { + copy.add(recursiveDeepCopy(setKey)) + } + return copy as T + } + if (sourceObject instanceof Map) { + const copy = new Map() + Object.setPrototypeOf(copy, Object.getPrototypeOf(sourceObject)) + copiedObjects.set(sourceObject, copy) + for (const mapKey of sourceObject.keys()) { + copy.set(mapKey, recursiveDeepCopy(sourceObject.get(mapKey))) + } + return copy as T + } + if (sourceObject instanceof Date) { + const copy = new Date() + copy.setTime(sourceObject.getTime()) + Object.setPrototypeOf(copy, Object.getPrototypeOf(sourceObject)) + copiedObjects.set(sourceObject, copy) + return copy as T + } + if (sourceObject instanceof Object) { + const copy = Array.isArray(sourceObject) ? [] : {} + Object.setPrototypeOf(copy, Object.getPrototypeOf(sourceObject)) + copiedObjects.set(sourceObject, copy) + return copy as T + } + + return sourceObject + } +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/reflection.ts b/koala-wrapper/koalaui/compat/src/typescript/reflection.ts new file mode 100644 index 000000000..50e1863f0 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/reflection.ts @@ -0,0 +1,20 @@ + +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { className } from "./ts-reflection" + +export function lcClassName(object: Object) { + return className(object).toLowerCase() +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/strings.ts b/koala-wrapper/koalaui/compat/src/typescript/strings.ts new file mode 100644 index 000000000..79ad7c2d6 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/strings.ts @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "./types" + +interface SystemTextEncoder { + encode(input?: string): Uint8Array; + encodeInto(src: string, dest: Uint8Array): void; +} + +interface WithStreamOption { + stream?: boolean | undefined; +} + +interface SystemTextDecoder { + decode( + input?: ArrayBuffer | null, + options?: WithStreamOption + ): string; +} + +export class CustomTextEncoder { + static readonly HeaderLen: int32 = Int32Array.BYTES_PER_ELEMENT + + constructor(encoder: SystemTextEncoder|undefined = ((typeof TextEncoder != "undefined") ? new TextEncoder() : undefined)) { + this.encoder = encoder + } + + private readonly encoder: SystemTextEncoder|undefined + + public static stringLength(input: string): int32 { + let length = 0 + for (let i = 0; i < input.length; i++) { + length++ + let cp = input.codePointAt(i)! + if (cp >= 0x10000) { + i++ + } + } + return length + } + + encodedLength(input: string): int32 { + let length = 0 + for (let i = 0; i < input.length; i++) { + let cp = input.codePointAt(i)! + if (cp < 0x80) { + length += 1 + } else if (cp < 0x800) { + length += 2 + } else if (cp < 0x10000) { + length += 3 + } else { + length += 4 + i++ + } + } + return length + } + + private addLength(array: Uint8Array, offset: int32, len: int32): void { + array[offset] = (len & 0xff) + array[offset + 1] = ((len >> 8) & 0xff) + array[offset + 2] = ((len >> 16) & 0xff) + array[offset + 3] = ((len >> 24) & 0xff) + } + + static getHeaderLength(array: Uint8Array, offset: int32 = 0): int32 { + return (array[offset] | (array[offset + 1] << 8) | (array[offset + 2] << 16) | (array[offset + 3] << 24)) + } + + // Produces array of bytes with encoded string headed by 4 bytes (little endian) size information: + // [s0][s1][s2][s3] [c_0] ... [c_size-1] + encode(input: string | undefined, addLength: boolean = true): Uint8Array { + let headerLen = addLength ? CustomTextEncoder.HeaderLen : 0 + let result: Uint8Array + if (!input) { + result = new Uint8Array(headerLen) + } else if (this.encoder !== undefined) { + result = this.encoder!.encode('s'.repeat(headerLen) + input) + } else { + let length = this.encodedLength(input) + result = new Uint8Array(length + headerLen) + this.encodeInto(input, result, headerLen) + } + if (addLength) { + this.addLength(result, 0, result.length - headerLen) + } + return result + } + + // Produces encoded array of strings with size information. + encodeArray(strings: Array): Uint8Array { + let totalBytes = CustomTextEncoder.HeaderLen + let lengths = new Int32Array(strings.length) + for (let i = 0; i < lengths.length; i++) { + let len = this.encodedLength(strings[i]) + lengths[i] = len + totalBytes += len + CustomTextEncoder.HeaderLen + } + let array = new Uint8Array(totalBytes) + let position = 0 + this.addLength(array, position, lengths.length) + position += CustomTextEncoder.HeaderLen + for (let i = 0; i < lengths.length; i++) { + this.addLength(array, position, lengths[i]) + position += CustomTextEncoder.HeaderLen + this.encodeInto(strings[i], array, position) + position += lengths[i] + } + return array + } + + encodeInto(input: string, result: Uint8Array, position: int32): Uint8Array { + if (this.encoder !== undefined) { + this.encoder!.encodeInto(input, result.subarray(position, result.length)) + return result + } + let index = position + for (let stringPosition = 0; stringPosition < input.length; stringPosition++) { + let cp = input.codePointAt(stringPosition)! + if (cp < 0x80) { + result[index++] = (cp | 0) + } else if (cp < 0x800) { + result[index++] = ((cp >> 6) | 0xc0) + result[index++] = ((cp & 0x3f) | 0x80) + } else if (cp < 0x10000) { + result[index++] = ((cp >> 12) | 0xe0) + result[index++] = (((cp >> 6) & 0x3f) | 0x80) + result[index++] = ((cp & 0x3f) | 0x80) + } else { + result[index++] = ((cp >> 18) | 0xf0) + result[index++] = (((cp >> 12) & 0x3f) | 0x80) + result[index++] = (((cp >> 6) & 0x3f) | 0x80) + result[index++] = ((cp & 0x3f) | 0x80) + stringPosition++ + } + } + result[index] = 0 + return result + } +} + +export class CustomTextDecoder { + static cpArrayMaxSize = 128 + constructor(decoder: SystemTextDecoder|undefined = ((typeof TextDecoder != "undefined") ? new TextDecoder() : undefined)) { + this.decoder = decoder + } + + private readonly decoder: SystemTextDecoder|undefined + + decode(input: Uint8Array): string { + if (this.decoder !== undefined) { + return this.decoder!.decode(input) + } + const cpSize = Math.min(CustomTextDecoder.cpArrayMaxSize, input.length) + let codePoints = new Int32Array(cpSize) + let cpIndex = 0; + let index = 0 + let result = "" + while (index < input.length) { + let elem = input[index] + let lead = elem & 0xff + let count = 0 + let value = 0 + if (lead < 0x80) { + count = 1 + value = elem + } else if ((lead >> 5) == 0x6) { + value = ((elem << 6) & 0x7ff) + (input[index + 1] & 0x3f) + count = 2 + } else if ((lead >> 4) == 0xe) { + value = ((elem << 12) & 0xffff) + ((input[index + 1] << 6) & 0xfff) + + (input[index + 2] & 0x3f) + count = 3 + } else if ((lead >> 3) == 0x1e) { + value = ((elem << 18) & 0x1fffff) + ((input[index + 1] << 12) & 0x3ffff) + + ((input[index + 2] << 6) & 0xfff) + (input[index + 3] & 0x3f) + count = 4 + } + codePoints[cpIndex++] = value + if (cpIndex == cpSize) { + cpIndex = 0 + result += String.fromCodePoint(...codePoints) + } + index += count + } + if (cpIndex > 0) { + result += String.fromCodePoint(...codePoints.slice(0, cpIndex)) + } + return result + } +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/ts-reflection.ts b/koala-wrapper/koalaui/compat/src/typescript/ts-reflection.ts new file mode 100644 index 000000000..f820e0045 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/ts-reflection.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022-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. + */ + +export function className(object?: Object): string { + return object?.constructor.name ?? "" +} + +export function isFunction(object?: Object): boolean { + return typeof object === 'function' +} + +// TODO: this is to match arkts counterpart +export function functionOverValue(value: Value|(()=>Value)): boolean { + return typeof value === 'function' +} + +export function refEqual(a: Value, b: Value): boolean { + return a === b +} + +export function isNotPrimitive(value: Object): boolean { + return true +} diff --git a/koala-wrapper/koalaui/compat/src/typescript/types.ts b/koala-wrapper/koalaui/compat/src/typescript/types.ts new file mode 100644 index 000000000..4a2c8a411 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/types.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022-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. + */ + +/// +export type uint8 = int +export type int8 = int +export type int16 = int +export type int32 = int +export type uint32 = int +export type int64 = long +export type uint64 = long +export type float32 = float +export type float64 = double diff --git a/koala-wrapper/koalaui/compat/src/typescript/utils.ts b/koala-wrapper/koalaui/compat/src/typescript/utils.ts new file mode 100644 index 000000000..a689f8905 --- /dev/null +++ b/koala-wrapper/koalaui/compat/src/typescript/utils.ts @@ -0,0 +1,18 @@ +/* + * 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. + */ + +export function unsafeCast(value: unknown): T { + return value as unknown as T +} diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/arkts/ResourceManager.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/arkts/ResourceManager.d.ts new file mode 100644 index 000000000..87813a2b6 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/arkts/ResourceManager.d.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/common"; +export type ResourceId = int32; +export declare class ResourceHolder { + private static nextResourceId; + private resources; + private static _instance; + static instance(): ResourceHolder; + hold(resourceId: ResourceId): void; + release(resourceId: ResourceId): void; + registerAndHold(resource: object): ResourceId; + get(resourceId: ResourceId): object; + has(resourceId: ResourceId): boolean; +} +//# sourceMappingURL=ResourceManager.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/arkts/ResourceManager.js b/koala-wrapper/koalaui/interop/dist/lib/src/arkts/ResourceManager.js new file mode 100644 index 000000000..3671e17e8 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/arkts/ResourceManager.js @@ -0,0 +1,61 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResourceHolder = void 0; +class ResourceHolder { + constructor() { + this.resources = new Map(); + } + static instance() { + if (ResourceHolder._instance == undefined) { + ResourceHolder._instance = new ResourceHolder(); + } + return ResourceHolder._instance; + } + hold(resourceId) { + if (!this.resources.has(resourceId)) + throw new Error(`Resource ${resourceId} does not exists, can not hold`); + this.resources.get(resourceId).holdersCount++; + } + release(resourceId) { + if (!this.resources.has(resourceId)) + throw new Error(`Resource ${resourceId} does not exists, can not release`); + const resource = this.resources.get(resourceId); + resource.holdersCount--; + if (resource.holdersCount <= 0) + this.resources.delete(resourceId); + } + registerAndHold(resource) { + const resourceId = ResourceHolder.nextResourceId++; + this.resources.set(resourceId, { + resource: resource, + holdersCount: 1, + }); + return resourceId; + } + get(resourceId) { + if (!this.resources.has(resourceId)) + throw new Error(`Resource ${resourceId} does not exists`); + return this.resources.get(resourceId).resource; + } + has(resourceId) { + return this.resources.has(resourceId); + } +} +exports.ResourceHolder = ResourceHolder; +ResourceHolder.nextResourceId = 100; +ResourceHolder._instance = undefined; +//# sourceMappingURL=ResourceManager.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/DeserializerBase.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/DeserializerBase.d.ts new file mode 100644 index 000000000..5edd7608a --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/DeserializerBase.d.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32, int32, int64 } from "#koalaui/common"; +import { CallbackResource } from "./SerializerBase"; +import { pointer } from "./InteropTypes"; +export declare class DeserializerBase { + private position; + private readonly buffer; + private readonly length; + private view; + private static textDecoder; + private static customDeserializers; + static registerCustomDeserializer(deserializer: CustomDeserializer): void; + constructor(buffer: ArrayBuffer, length: int32); + static get(factory: (args: Uint8Array, length: int32) => T, args: Uint8Array, length: int32): T; + asArray(position?: number, length?: number): Uint8Array; + currentPosition(): int32; + resetCurrentPosition(): void; + private checkCapacity; + readInt8(): int32; + readInt32(): int32; + readInt64(): int64; + readPointer(): pointer; + readFloat32(): float32; + readBoolean(): boolean; + readFunction(): any; + readMaterialized(): object; + readString(): string; + readCustomObject(kind: string): any; + readNumber(): number | undefined; + readCallbackResource(): CallbackResource; + static lengthUnitFromInt(unit: int32): string; + readBuffer(): ArrayBuffer; +} +export declare abstract class CustomDeserializer { + protected supported: Array; + protected constructor(supported: Array); + supports(kind: string): boolean; + abstract deserialize(serializer: DeserializerBase, kind: string): any; + next: CustomDeserializer | undefined; +} +//# sourceMappingURL=DeserializerBase.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/DeserializerBase.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/DeserializerBase.js new file mode 100644 index 000000000..4e72e82db --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/DeserializerBase.js @@ -0,0 +1,208 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CustomDeserializer = exports.DeserializerBase = void 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. + */ +const common_1 = require("#koalaui/common"); +const SerializerBase_1 = require("./SerializerBase"); +const InteropNativeModule_1 = require("./InteropNativeModule"); +class DeserializerBase { + static registerCustomDeserializer(deserializer) { + let current = DeserializerBase.customDeserializers; + if (current == undefined) { + DeserializerBase.customDeserializers = deserializer; + } + else { + while (current.next != undefined) { + current = current.next; + } + current.next = deserializer; + } + } + constructor(buffer, length) { + this.position = 0; + this.buffer = buffer; + this.length = length; + this.view = new DataView(this.buffer); + } + static get(factory, args, length) { + // TBD: Use cache + return factory(args, length); + } + asArray(position, length) { + return new Uint8Array(this.buffer, position, length); + } + currentPosition() { + return this.position; + } + resetCurrentPosition() { + this.position = 0; + } + checkCapacity(value) { + if (value > this.length) { + throw new Error(`${value} is less than remaining buffer length`); + } + } + readInt8() { + this.checkCapacity(1); + const value = this.view.getInt8(this.position); + this.position += 1; + return value; + } + readInt32() { + this.checkCapacity(4); + const value = this.view.getInt32(this.position, true); + this.position += 4; + return value; + } + readInt64() { + this.checkCapacity(8); + const value = this.view.getBigInt64(this.position, true); + this.position += 8; + return Number(value); + } + readPointer() { + this.checkCapacity(8); + const value = this.view.getBigInt64(this.position, true); + this.position += 8; + return value; + } + readFloat32() { + this.checkCapacity(4); + const value = this.view.getFloat32(this.position, true); + this.position += 4; + return value; + } + readBoolean() { + this.checkCapacity(1); + const value = this.view.getInt8(this.position); + this.position += 1; + return value == 1; + } + readFunction() { + // TODO: not exactly correct. + const id = this.readInt32(); + return id; + } + readMaterialized() { + const ptr = this.readPointer(); + return { ptr: ptr }; + } + readString() { + const length = this.readInt32(); + this.checkCapacity(length); + // read without null-terminated byte + const value = DeserializerBase.textDecoder.decode(this.asArray(this.position, length - 1)); + this.position += length; + return value; + } + readCustomObject(kind) { + let current = DeserializerBase.customDeserializers; + while (current) { + if (current.supports(kind)) { + return current.deserialize(this, kind); + } + current = current.next; + } + // consume tag + const tag = this.readInt8(); + return undefined; + } + readNumber() { + const tag = this.readInt8(); + switch (tag) { + case SerializerBase_1.Tags.UNDEFINED: + return undefined; + case SerializerBase_1.Tags.INT32: + return this.readInt32(); + case SerializerBase_1.Tags.FLOAT32: + return this.readFloat32(); + default: + throw new Error(`Unknown number tag: ${tag}`); + break; + } + } + readCallbackResource() { + return { + resourceId: this.readInt32(), + hold: this.readPointer(), + release: this.readPointer(), + }; + } + static lengthUnitFromInt(unit) { + let suffix; + switch (unit) { + case 0: + suffix = "px"; + break; + case 1: + suffix = "vp"; + break; + case 3: + suffix = "%"; + break; + case 4: + suffix = "lpx"; + break; + default: + suffix = ""; + } + return suffix; + } + readBuffer() { + const resource = this.readCallbackResource(); + const data = this.readPointer(); + const length = this.readInt64(); + return InteropNativeModule_1.InteropNativeModule._MaterializeBuffer(data, length, resource.resourceId, resource.hold, resource.release); + } +} +exports.DeserializerBase = DeserializerBase; +DeserializerBase.textDecoder = new common_1.CustomTextDecoder(); +DeserializerBase.customDeserializers = undefined; +class CustomDeserializer { + constructor(supported) { + this.supported = supported; + this.next = undefined; + } + supports(kind) { + return this.supported.includes(kind); + } +} +exports.CustomDeserializer = CustomDeserializer; +class DateDeserializer extends CustomDeserializer { + constructor() { + super(["Date"]); + } + deserialize(serializer, kind) { + return new Date(serializer.readString()); + } +} +DeserializerBase.registerCustomDeserializer(new DateDeserializer()); +//# sourceMappingURL=DeserializerBase.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/Finalizable.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Finalizable.d.ts new file mode 100644 index 000000000..2df1edf89 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Finalizable.d.ts @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Wrapper } from "./Wrapper"; +import { Thunk } from "#koalaui/common"; +import { pointer } from "./InteropTypes"; +export declare class NativeThunk implements Thunk { + finalizer: pointer; + obj: pointer; + name: string | undefined; + constructor(obj: pointer, finalizer: pointer, name?: string); + clean(): void; + destroyNative(ptr: pointer, finalizer: pointer): void; +} +/** + * Class with the custom finalizer, usually used to release a native peer. + * Do not use directly, only via subclasses. + */ +export declare class Finalizable extends Wrapper { + finalizer: pointer; + cleaner?: NativeThunk; + managed: boolean; + constructor(ptr: pointer, finalizer: pointer, managed?: boolean); + createHandle(): string | undefined; + makeNativeThunk(ptr: pointer, finalizer: pointer, handle: string | undefined): NativeThunk; + close(): void; + release(): pointer; + resetPeer(pointer: pointer): void; + use(body: (value: Finalizable) => R): R; +} +//# sourceMappingURL=Finalizable.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/Finalizable.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Finalizable.js new file mode 100644 index 000000000..21c45b5b0 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Finalizable.js @@ -0,0 +1,100 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Finalizable = exports.NativeThunk = void 0; +const Wrapper_1 = require("./Wrapper"); +const common_1 = require("#koalaui/common"); +const InteropNativeModule_1 = require("./InteropNativeModule"); +class NativeThunk { + constructor(obj, finalizer, name) { + this.finalizer = finalizer; + this.obj = obj; + this.name = name; + } + clean() { + if (!(0, Wrapper_1.isNullPtr)(this.obj)) { + this.destroyNative(this.obj, this.finalizer); + } + this.obj = Wrapper_1.nullptr; + } + destroyNative(ptr, finalizer) { + InteropNativeModule_1.InteropNativeModule._InvokeFinalizer(ptr, finalizer); + } +} +exports.NativeThunk = NativeThunk; +/** + * Class with the custom finalizer, usually used to release a native peer. + * Do not use directly, only via subclasses. + */ +class Finalizable extends Wrapper_1.Wrapper { + constructor(ptr, finalizer, managed = true) { + super(ptr); + this.cleaner = undefined; + this.finalizer = finalizer; + this.managed = managed; + const handle = this.createHandle(); + if (this.managed) { + // TODO: reenable exception. + if (this.ptr == Wrapper_1.nullptr) + return; // throw new Error("Can't have nullptr ptr ${}") + if (this.finalizer == Wrapper_1.nullptr) + throw new Error("Managed finalizer is 0"); + const thunk = this.makeNativeThunk(ptr, finalizer, handle); + (0, common_1.finalizerRegister)(this, thunk); + this.cleaner = thunk; + } + } + createHandle() { + return undefined; + } + makeNativeThunk(ptr, finalizer, handle) { + return new NativeThunk(ptr, finalizer, handle); + } + close() { + if ((0, Wrapper_1.isNullPtr)(this.ptr)) { + throw new Error(`Closing a closed object: ` + this.toString()); + } + else if (this.cleaner == null) { + throw new Error(`No thunk assigned to ` + this.toString()); + } + else { + (0, common_1.finalizerUnregister)(this); + this.cleaner.clean(); + this.cleaner = undefined; + this.ptr = Wrapper_1.nullptr; + } + } + release() { + (0, common_1.finalizerUnregister)(this); + if (this.cleaner) + this.cleaner.obj = Wrapper_1.nullptr; + let result = this.ptr; + this.ptr = Wrapper_1.nullptr; + return result; + } + resetPeer(pointer) { + if (this.managed) + throw new Error("Can only reset peer for an unmanaged object"); + this.ptr = pointer; + } + use(body) { + let result = body(this); + this.close(); + return result; + } +} +exports.Finalizable = Finalizable; +//# sourceMappingURL=Finalizable.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropNativeModule.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropNativeModule.d.ts new file mode 100644 index 000000000..75ea2a718 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropNativeModule.d.ts @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/common"; +import { KPointer, KStringPtr, KUint8ArrayPtr } from "./InteropTypes"; +export declare class InteropNativeModule { + static _SetCallbackDispatcher(dispatcher: (id: int32, args: Uint8Array, length: int32) => int32): void; + static _CleanCallbackDispatcher(): void; + static _GetGroupedLog(index: int32): KPointer; + static _StartGroupedLog(index: int32): void; + static _StopGroupedLog(index: int32): void; + static _AppendGroupedLog(index: int32, message: string): void; + static _PrintGroupedLog(index: int32): void; + static _GetStringFinalizer(): KPointer; + static _InvokeFinalizer(ptr1: KPointer, ptr2: KPointer): void; + static _GetPtrVectorElement(ptr1: KPointer, arg: int32): KPointer; + static _StringLength(ptr1: KPointer): int32; + static _StringData(ptr1: KPointer, arr: KUint8ArrayPtr, i: int32): void; + static _StringMake(str1: KStringPtr): KPointer; + static _GetPtrVectorSize(ptr1: KPointer): int32; + static _ManagedStringWrite(str1: string, arr: Uint8Array, arg: int32): int32; + static _NativeLog(str1: string): void; + static _Utf8ToString(data: KUint8ArrayPtr, offset: int32, length: int32): string; + static _StdStringToString(cstring: KPointer): string; + static _CheckCallbackEvent(buffer: KUint8ArrayPtr, bufferLength: int32): int32; + static _HoldCallbackResource(resourceId: int32): void; + static _ReleaseCallbackResource(resourceId: int32): void; + static _CallCallback(callbackKind: int32, args: Uint8Array, argsSize: int32): void; + static _CallCallbackSync(callbackKind: int32, args: Uint8Array, argsSize: int32): void; + static _CallCallbackResourceHolder(holder: KPointer, resourceId: int32): void; + static _CallCallbackResourceReleaser(releaser: KPointer, resourceId: int32): void; + static _MaterializeBuffer(data: KPointer, length: int32, resourceId: int32, hold: KPointer, release: KPointer): ArrayBuffer; + static _GetNativeBufferPointer(data: ArrayBuffer): KPointer; + static _LoadVirtualMachine(arg0: int32, arg1: string, arg2: string): int32; + static _RunApplication(arg0: int32, arg1: int32): number; + static _StartApplication(appUrl: string, appParams: string): KPointer; + static _EmitEvent(eventType: int32, target: int32, arg0: int32, arg1: int32): void; + static _CallForeignVM(foreignContext: KPointer, kind: int32, args: Uint8Array, argsSize: int32): int32; +} +export declare function loadInteropNativeModule(): void; +//# sourceMappingURL=InteropNativeModule.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropNativeModule.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropNativeModule.js new file mode 100644 index 000000000..404c7f6c0 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropNativeModule.js @@ -0,0 +1,59 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadInteropNativeModule = exports.InteropNativeModule = void 0; +const loadLibraries_1 = require("./loadLibraries"); +class InteropNativeModule { + static _SetCallbackDispatcher(dispatcher) { throw "method not loaded"; } + static _CleanCallbackDispatcher() { throw "method not loaded"; } + static _GetGroupedLog(index) { throw "method not loaded"; } + static _StartGroupedLog(index) { throw "method not loaded"; } + static _StopGroupedLog(index) { throw "method not loaded"; } + static _AppendGroupedLog(index, message) { throw "method not loaded"; } + static _PrintGroupedLog(index) { throw "method not loaded"; } + static _GetStringFinalizer() { throw "method not loaded"; } + static _InvokeFinalizer(ptr1, ptr2) { throw "method not loaded"; } + static _GetPtrVectorElement(ptr1, arg) { throw "method not loaded"; } + static _StringLength(ptr1) { throw "method not loaded"; } + static _StringData(ptr1, arr, i) { throw "method not loaded"; } + static _StringMake(str1) { throw "method not loaded"; } + static _GetPtrVectorSize(ptr1) { throw "method not loaded"; } + static _ManagedStringWrite(str1, arr, arg) { throw "method not loaded"; } + static _NativeLog(str1) { throw "method not loaded"; } + static _Utf8ToString(data, offset, length) { throw "method not loaded"; } + static _StdStringToString(cstring) { throw "method not loaded"; } + static _CheckCallbackEvent(buffer, bufferLength) { throw "method not loaded"; } + static _HoldCallbackResource(resourceId) { throw "method not loaded"; } + static _ReleaseCallbackResource(resourceId) { throw "method not loaded"; } + static _CallCallback(callbackKind, args, argsSize) { throw "method not loaded"; } + static _CallCallbackSync(callbackKind, args, argsSize) { throw "method not loaded"; } + static _CallCallbackResourceHolder(holder, resourceId) { throw "method not loaded"; } + static _CallCallbackResourceReleaser(releaser, resourceId) { throw "method not loaded"; } + static _MaterializeBuffer(data, length, resourceId, hold, release) { throw "method not loaded"; } + static _GetNativeBufferPointer(data) { throw "method not loaded"; } + static _LoadVirtualMachine(arg0, arg1, arg2) { throw "method not loaded"; } + static _RunApplication(arg0, arg1) { throw "method not loaded"; } + static _StartApplication(appUrl, appParams) { throw "method not loaded"; } + static _EmitEvent(eventType, target, arg0, arg1) { throw "method not loaded"; } + static _CallForeignVM(foreignContext, kind, args, argsSize) { throw "method not loaded"; } +} +exports.InteropNativeModule = InteropNativeModule; +function loadInteropNativeModule() { + (0, loadLibraries_1.loadNativeModuleLibrary)("InteropNativeModule", InteropNativeModule); +} +exports.loadInteropNativeModule = loadInteropNativeModule; +//# sourceMappingURL=InteropNativeModule.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropOps.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropOps.d.ts new file mode 100644 index 000000000..2b1206036 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropOps.d.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/common"; +export type CallbackType = (args: Uint8Array, length: int32) => int32; +export declare function wrapCallback(callback: CallbackType, autoDisposable?: boolean): int32; +export declare function wrapSystemCallback(id: number, callback: CallbackType): int32; +export declare function disposeCallback(id: int32): void; +export declare function callCallback(id: int32, args: Uint8Array, length: int32): int32; +//# sourceMappingURL=InteropOps.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropOps.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropOps.js new file mode 100644 index 000000000..150decb9c --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropOps.js @@ -0,0 +1,75 @@ +"use strict"; +/* + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.callCallback = exports.disposeCallback = exports.wrapSystemCallback = exports.wrapCallback = void 0; +class CallbackRecord { + constructor(callback, autoDisposable) { + this.callback = callback; + this.autoDisposable = autoDisposable; + } +} +class CallbackRegistry { + constructor() { + this.callbacks = new Map(); + this.id = 1024; + this.callbacks.set(0, new CallbackRecord((args, length) => { + console.log(`Callback 0 called with args = ${args} and length = ${length}`); + throw new Error(`Null callback called`); + }, false)); + } + wrap(callback, autoDisposable) { + const id = this.id++; + this.callbacks.set(id, new CallbackRecord(callback, autoDisposable)); + return id; + } + wrapSystem(id, callback, autoDisposable) { + this.callbacks.set(id, new CallbackRecord(callback, autoDisposable)); + return id; + } + call(id, args, length) { + const record = this.callbacks.get(id); + if (!record) { + console.log(`Callback ${id} is not known`); + // throw new Error(`Disposed or unwrapped callback called (id = ${id})`) + return 0; // todo + } + if (record.autoDisposable) { + this.dispose(id); + } + return record.callback(args, length); + } + dispose(id) { + this.callbacks.delete(id); + } +} +CallbackRegistry.INSTANCE = new CallbackRegistry(); +function wrapCallback(callback, autoDisposable = true) { + return CallbackRegistry.INSTANCE.wrap(callback, autoDisposable); +} +exports.wrapCallback = wrapCallback; +function wrapSystemCallback(id, callback) { + return CallbackRegistry.INSTANCE.wrapSystem(id, callback, false); +} +exports.wrapSystemCallback = wrapSystemCallback; +function disposeCallback(id) { + CallbackRegistry.INSTANCE.dispose(id); +} +exports.disposeCallback = disposeCallback; +function callCallback(id, args, length) { + return CallbackRegistry.INSTANCE.call(id, args, length); +} +exports.callCallback = callCallback; +//# sourceMappingURL=InteropOps.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropTypes.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropTypes.d.ts new file mode 100644 index 000000000..2b012790e --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropTypes.d.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32, int64, float32, float64 } from "#koalaui/common"; +export type KStringPtr = int32 | string | null; +export type KStringArrayPtr = int32 | Uint8Array | null; +export type KInt32ArrayPtr = int32 | Int32Array | null; +export type KFloat32ArrayPtr = int32 | Float32Array | null; +export type KUint8ArrayPtr = int32 | Uint8Array | null; +export type KInt = int32; +export type KUInt = int32; +export type KLong = int64; +export type KFloat = float32; +export type KDouble = float64; +export type KBoolean = int32; +export type KPointer = number | bigint; +export type pointer = KPointer; +export type KNativePointer = KPointer; +export type KInteropReturnBuffer = Uint8Array; +//# sourceMappingURL=InteropTypes.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropTypes.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropTypes.js new file mode 100644 index 000000000..41af5b8e8 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/InteropTypes.js @@ -0,0 +1,18 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ + +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=InteropTypes.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/MaterializedBase.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/MaterializedBase.d.ts new file mode 100644 index 000000000..beaa7d02c --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/MaterializedBase.d.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Finalizable } from "./Finalizable"; +export interface MaterializedBase { + getPeer(): Finalizable | undefined; +} +//# sourceMappingURL=MaterializedBase.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/MaterializedBase.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/MaterializedBase.js new file mode 100644 index 000000000..629c7d70e --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/MaterializedBase.js @@ -0,0 +1,17 @@ +"use strict"; +/* + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MaterializedBase.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeBuffer.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeBuffer.d.ts new file mode 100644 index 000000000..8c309b51f --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeBuffer.d.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { pointer } from './InteropTypes'; +import { int32, int64 } from '#koalaui/common'; +export declare class NativeBuffer extends ArrayBuffer { + data: pointer; + length: int64; + resourceId: int32; + hold: pointer; + release: pointer; + constructor(data: pointer, length: int64, resourceId: int32, hold: pointer, release: pointer); + static wrap(data: pointer, length: int64, resourceId: int32, hold: pointer, release: pointer): NativeBuffer; +} +//# sourceMappingURL=NativeBuffer.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeBuffer.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeBuffer.js new file mode 100644 index 000000000..96755df13 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeBuffer.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NativeBuffer = void 0; +// stub wrapper for KInteropBuffer +class NativeBuffer extends ArrayBuffer { + constructor(data, length, resourceId, hold, release) { + super(length); + this.data = 0; + this.length = 0; + this.resourceId = 0; + this.hold = 0; + this.release = 0; + this.data = data; + this.length = length; + this.resourceId = resourceId; + this.hold = hold; + this.release = release; + } + static wrap(data, length, resourceId, hold, release) { + return new NativeBuffer(data, length, resourceId, hold, release); + } +} +exports.NativeBuffer = NativeBuffer; +//# sourceMappingURL=NativeBuffer.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeString.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeString.d.ts new file mode 100644 index 000000000..e59b72f42 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeString.d.ts @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Finalizable } from "./Finalizable"; +import { pointer } from "./InteropTypes"; +export declare class NativeString extends Finalizable { + constructor(ptr: pointer); + static Make(value: string): NativeString; + toString(): string; +} +//# sourceMappingURL=NativeString.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeString.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeString.js new file mode 100644 index 000000000..0bd0d1586 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/NativeString.js @@ -0,0 +1,32 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NativeString = void 0; +const Finalizable_1 = require("./Finalizable"); +const InteropNativeModule_1 = require("./InteropNativeModule"); +class NativeString extends Finalizable_1.Finalizable { + constructor(ptr) { + super(ptr, InteropNativeModule_1.InteropNativeModule._GetStringFinalizer()); + } + static Make(value) { + return new NativeString(InteropNativeModule_1.InteropNativeModule._StringMake(value)); + } + toString() { + return InteropNativeModule_1.InteropNativeModule._StdStringToString(this.ptr); + } +} +exports.NativeString = NativeString; +//# sourceMappingURL=NativeString.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/Platform.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Platform.d.ts new file mode 100644 index 000000000..078095680 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Platform.d.ts @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/common"; +import { Wrapper } from "./Wrapper"; +import { KPointer } from "./InteropTypes"; +export declare abstract class NativeStringBase extends Wrapper { + constructor(ptr: KPointer); + protected abstract bytesLength(): int32; + protected abstract getData(data: Uint8Array): void; + toString(): string; + abstract close(): void; +} +export declare abstract class ArrayDecoder { + abstract getArraySize(blob: KPointer): int32; + abstract disposeArray(blob: KPointer): void; + abstract getArrayElement(blob: KPointer, index: int32): T; + decode(blob: KPointer): Array; +} +export interface CallbackRegistry { + registerCallback(callback: any, obj: any): KPointer; +} +export interface PlatformDefinedData { + nativeString(ptr: KPointer): NativeStringBase; + nativeStringArrayDecoder(): ArrayDecoder; + callbackRegistry(): CallbackRegistry | undefined; +} +export declare function providePlatformDefinedData(platformDataParam: PlatformDefinedData): void; +export declare function withStringResult(ptr: KPointer): string | undefined; +export declare function withStringArrayResult(ptr: KPointer): Array; +//# sourceMappingURL=Platform.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/Platform.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Platform.js new file mode 100644 index 000000000..adf11745b --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Platform.js @@ -0,0 +1,69 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.withStringArrayResult = exports.withStringResult = exports.providePlatformDefinedData = exports.ArrayDecoder = exports.NativeStringBase = void 0; +const Wrapper_1 = require("./Wrapper"); +const arrays_1 = require("#common/wrappers/arrays"); +const Callback_1 = require("#common/wrappers/Callback"); +class NativeStringBase extends Wrapper_1.Wrapper { + constructor(ptr) { + super(ptr); + } + toString() { + let length = this.bytesLength(); + let data = new Uint8Array(length); + this.getData(data); + return (0, arrays_1.decodeToString)(data); + } +} +exports.NativeStringBase = NativeStringBase; +class ArrayDecoder { + decode(blob) { + const size = this.getArraySize(blob); + const result = new Array(size); + for (let index = 0; index < size; index++) { + result[index] = this.getArrayElement(blob, index); + } + this.disposeArray(blob); + return result; + } +} +exports.ArrayDecoder = ArrayDecoder; +let platformData = undefined; +function providePlatformDefinedData(platformDataParam) { + platformData = platformDataParam; + let registry = platformDataParam.callbackRegistry(); + if (registry) + (0, Callback_1.setCallbackRegistry)(registry); +} +exports.providePlatformDefinedData = providePlatformDefinedData; +function withStringResult(ptr) { + if ((0, Wrapper_1.isNullPtr)(ptr)) + return undefined; + let managedString = platformData.nativeString(ptr); + let result = managedString === null || managedString === void 0 ? void 0 : managedString.toString(); + managedString === null || managedString === void 0 ? void 0 : managedString.close(); + return result; +} +exports.withStringResult = withStringResult; +function withStringArrayResult(ptr) { + if (ptr == Wrapper_1.nullptr) + return new Array(); + let managedStringArray = platformData.nativeStringArrayDecoder().decode(ptr); + return managedStringArray.map((nativeString) => nativeString.toString()); +} +exports.withStringArrayResult = withStringArrayResult; +//# sourceMappingURL=Platform.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/SerializerBase.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/SerializerBase.d.ts new file mode 100644 index 000000000..6dbd43280 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/SerializerBase.d.ts @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32, int32, int64 } from "#koalaui/common"; +import { pointer, KPointer } from "./InteropTypes"; +import { ResourceId } from "../arkts/ResourceManager"; +/** + * Value representing possible JS runtime object type. + * Must be synced with "enum RuntimeType" in C++. + */ +export declare enum RuntimeType { + UNEXPECTED = -1, + NUMBER = 1, + STRING = 2, + OBJECT = 3, + BOOLEAN = 4, + UNDEFINED = 5, + BIGINT = 6, + FUNCTION = 7, + SYMBOL = 8, + MATERIALIZED = 9 +} +/** + * Value representing object type in serialized data. + * Must be synced with "enum Tags" in C++. + */ +export declare enum Tags { + UNDEFINED = 101, + INT32 = 102, + FLOAT32 = 103, + STRING = 104, + LENGTH = 105, + RESOURCE = 106, + OBJECT = 107 +} +export declare function runtimeType(value: any): int32; +export declare function isResource(value: unknown): boolean; +export declare function isInstanceOf(className: string, value: object | undefined): boolean; +export declare function registerCallback(value: object | undefined): int32; +export declare function registerMaterialized(value: object | undefined): number; +export interface CallbackResource { + resourceId: int32; + hold: pointer; + release: pointer; +} +export declare abstract class CustomSerializer { + protected supported: Array; + constructor(supported: Array); + supports(kind: string): boolean; + abstract serialize(serializer: SerializerBase, value: any, kind: string): void; + next: CustomSerializer | undefined; +} +export declare class SerializerBase { + private position; + private buffer; + private view; + private static customSerializers; + static registerCustomSerializer(serializer: CustomSerializer): void; + constructor(); + release(): void; + asArray(): Uint8Array; + length(): int32; + currentPosition(): int32; + private checkCapacity; + private heldResources; + holdAndWriteCallback(callback: object, hold?: KPointer, release?: KPointer, call?: KPointer, callSync?: KPointer): ResourceId; + holdAndWriteCallbackForPromiseVoid(hold?: KPointer, release?: KPointer, call?: KPointer, callSync?: number): [Promise, ResourceId]; + holdAndWriteCallbackForPromise(hold?: KPointer, release?: KPointer, call?: KPointer): [Promise, ResourceId]; + writeCallbackResource(resource: CallbackResource): void; + private releaseResources; + writeCustomObject(kind: string, value: any): void; + writeNumber(value: number | undefined): void; + writeInt8(value: int32): void; + writeInt32(value: int32): void; + writeInt64(value: int64): void; + writePointer(value: pointer): void; + writeFloat32(value: float32): void; + writeBoolean(value: boolean | undefined): void; + writeFunction(value: object | undefined): void; + writeString(value: string): void; + writeBuffer(buffer: ArrayBuffer): void; +} +export declare function unsafeCast(value: unknown): T; +//# sourceMappingURL=SerializerBase.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/SerializerBase.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/SerializerBase.js new file mode 100644 index 000000000..5af311bb5 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/SerializerBase.js @@ -0,0 +1,298 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ + + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unsafeCast = exports.SerializerBase = exports.CustomSerializer = exports.registerMaterialized = exports.registerCallback = exports.isInstanceOf = exports.isResource = exports.runtimeType = exports.Tags = exports.RuntimeType = void 0; +const InteropOps_1 = require("./InteropOps"); +const InteropNativeModule_1 = require("./InteropNativeModule"); +const ResourceManager_1 = require("../arkts/ResourceManager"); +// imports required interfaces (now generation is disabled) +// import { Resource } from "@arkoala/arkui" +/** + * Value representing possible JS runtime object type. + * Must be synced with "enum RuntimeType" in C++. + */ +var RuntimeType; +(function (RuntimeType) { + RuntimeType[RuntimeType["UNEXPECTED"] = -1] = "UNEXPECTED"; + RuntimeType[RuntimeType["NUMBER"] = 1] = "NUMBER"; + RuntimeType[RuntimeType["STRING"] = 2] = "STRING"; + RuntimeType[RuntimeType["OBJECT"] = 3] = "OBJECT"; + RuntimeType[RuntimeType["BOOLEAN"] = 4] = "BOOLEAN"; + RuntimeType[RuntimeType["UNDEFINED"] = 5] = "UNDEFINED"; + RuntimeType[RuntimeType["BIGINT"] = 6] = "BIGINT"; + RuntimeType[RuntimeType["FUNCTION"] = 7] = "FUNCTION"; + RuntimeType[RuntimeType["SYMBOL"] = 8] = "SYMBOL"; + RuntimeType[RuntimeType["MATERIALIZED"] = 9] = "MATERIALIZED"; +})(RuntimeType = exports.RuntimeType || (exports.RuntimeType = {})); +/** + * Value representing object type in serialized data. + * Must be synced with "enum Tags" in C++. + */ +var Tags; +(function (Tags) { + Tags[Tags["UNDEFINED"] = 101] = "UNDEFINED"; + Tags[Tags["INT32"] = 102] = "INT32"; + Tags[Tags["FLOAT32"] = 103] = "FLOAT32"; + Tags[Tags["STRING"] = 104] = "STRING"; + Tags[Tags["LENGTH"] = 105] = "LENGTH"; + Tags[Tags["RESOURCE"] = 106] = "RESOURCE"; + Tags[Tags["OBJECT"] = 107] = "OBJECT"; +})(Tags = exports.Tags || (exports.Tags = {})); +function runtimeType(value) { + let type = typeof value; + if (type == "number") + return RuntimeType.NUMBER; + if (type == "string") + return RuntimeType.STRING; + if (type == "undefined") + return RuntimeType.UNDEFINED; + if (type == "object") + return RuntimeType.OBJECT; + if (type == "boolean") + return RuntimeType.BOOLEAN; + if (type == "bigint") + return RuntimeType.BIGINT; + if (type == "function") + return RuntimeType.FUNCTION; + if (type == "symbol") + return RuntimeType.SYMBOL; + throw new Error(`bug: ${value} is ${type}`); +} +exports.runtimeType = runtimeType; +function isResource(value) { + return value !== undefined + && typeof value === 'object' + && value !== null + && value.hasOwnProperty("bundleName") + && value.hasOwnProperty("moduleName"); +} +exports.isResource = isResource; +// Poor man's instanceof, fails on subclasses +function isInstanceOf(className, value) { + return (value === null || value === void 0 ? void 0 : value.constructor.name) === className; +} +exports.isInstanceOf = isInstanceOf; +function registerCallback(value) { + return (0, InteropOps_1.wrapCallback)((args, length) => { + // TBD: deserialize the callback arguments and call the callback + return 42; + }); +} +exports.registerCallback = registerCallback; +function registerMaterialized(value) { + // TODO: fix me! + return 42; +} +exports.registerMaterialized = registerMaterialized; +/* Serialization extension point */ +class CustomSerializer { + constructor(supported) { + this.supported = supported; + this.next = undefined; + } + supports(kind) { return this.supported.includes(kind); } +} +exports.CustomSerializer = CustomSerializer; +class SerializerBase { + static registerCustomSerializer(serializer) { + if (SerializerBase.customSerializers == undefined) { + SerializerBase.customSerializers = serializer; + } + else { + let current = SerializerBase.customSerializers; + while (current.next != undefined) { + current = current.next; + } + current.next = serializer; + } + } + constructor() { + this.position = 0; + this.heldResources = []; + this.buffer = new ArrayBuffer(96); + this.view = new DataView(this.buffer); + } + release() { + this.releaseResources(); + this.position = 0; + } + asArray() { + return new Uint8Array(this.buffer); + } + length() { + return this.position; + } + currentPosition() { return this.position; } + checkCapacity(value) { + if (value < 1) { + throw new Error(`${value} is less than 1`); + } + let buffSize = this.buffer.byteLength; + if (this.position > buffSize - value) { + const minSize = this.position + value; + const resizedSize = Math.max(minSize, Math.round(3 * buffSize / 2)); + let resizedBuffer = new ArrayBuffer(resizedSize); + // TODO: can we grow without new? + new Uint8Array(resizedBuffer).set(new Uint8Array(this.buffer)); + this.buffer = resizedBuffer; + this.view = new DataView(resizedBuffer); + } + } + holdAndWriteCallback(callback, hold = 0, release = 0, call = 0, callSync = 0) { + const resourceId = ResourceManager_1.ResourceHolder.instance().registerAndHold(callback); + this.heldResources.push(resourceId); + this.writeInt32(resourceId); + this.writePointer(hold); + this.writePointer(release); + this.writePointer(call); + this.writePointer(callSync); + return resourceId; + } + holdAndWriteCallbackForPromiseVoid(hold = 0, release = 0, call = 0, callSync = 0) { + let resourceId; + const promise = new Promise((resolve, reject) => { + const callback = (err) => { + if (err !== undefined) + reject(err); + else + resolve(); + }; + resourceId = this.holdAndWriteCallback(callback, hold, release, call, callSync); + }); + return [promise, resourceId]; + } + holdAndWriteCallbackForPromise(hold = 0, release = 0, call = 0) { + let resourceId; + const promise = new Promise((resolve, reject) => { + const callback = (value, err) => { + if (err !== undefined) + reject(err); + else + resolve(value); + }; + resourceId = this.holdAndWriteCallback(callback, hold, release, call); + }); + return [promise, resourceId]; + } + writeCallbackResource(resource) { + this.writeInt32(resource.resourceId); + this.writePointer(resource.hold); + this.writePointer(resource.release); + } + releaseResources() { + for (const resourceId of this.heldResources) + InteropNativeModule_1.InteropNativeModule._ReleaseCallbackResource(resourceId); + // todo think about effective array clearing/pushing + this.heldResources = []; + } + writeCustomObject(kind, value) { + let current = SerializerBase.customSerializers; + while (current) { + if (current.supports(kind)) { + current.serialize(this, value, kind); + return; + } + current = current.next; + } + console.log(`Unsupported custom serialization for ${kind}, write undefined`); + this.writeInt8(Tags.UNDEFINED); + } + writeNumber(value) { + this.checkCapacity(5); + if (value == undefined) { + this.view.setInt8(this.position, Tags.UNDEFINED); + this.position++; + return; + } + if (value == Math.round(value)) { + this.view.setInt8(this.position, Tags.INT32); + this.view.setInt32(this.position + 1, value, true); + this.position += 5; + return; + } + this.view.setInt8(this.position, Tags.FLOAT32); + this.view.setFloat32(this.position + 1, value, true); + this.position += 5; + } + writeInt8(value) { + this.checkCapacity(1); + this.view.setInt8(this.position, value); + this.position += 1; + } + writeInt32(value) { + this.checkCapacity(4); + this.view.setInt32(this.position, value, true); + this.position += 4; + } + writeInt64(value) { + this.checkCapacity(8); + this.view.setBigInt64(this.position, BigInt(value), true); + this.position += 8; + } + writePointer(value) { + this.checkCapacity(8); + this.view.setBigInt64(this.position, BigInt(value !== null && value !== void 0 ? value : 0), true); + this.position += 8; + } + writeFloat32(value) { + this.checkCapacity(4); + this.view.setFloat32(this.position, value, true); + this.position += 4; + } + writeBoolean(value) { + this.checkCapacity(1); + this.view.setInt8(this.position, value == undefined ? RuntimeType.UNDEFINED : +value); + this.position++; + } + writeFunction(value) { + this.writeInt32(registerCallback(value)); + } + writeString(value) { + this.checkCapacity(4 + value.length * 4); // length, data + let encodedLength = InteropNativeModule_1.InteropNativeModule._ManagedStringWrite(value, new Uint8Array(this.view.buffer, 0), this.position + 4); + this.view.setInt32(this.position, encodedLength, true); + this.position += encodedLength + 4; + } + writeBuffer(buffer) { + const resourceId = ResourceManager_1.ResourceHolder.instance().registerAndHold(buffer); + this.writeCallbackResource({ + resourceId, + hold: 0, + release: 0 + }); + const ptr = InteropNativeModule_1.InteropNativeModule._GetNativeBufferPointer(buffer); + this.writePointer(ptr); + this.writeInt64(buffer.byteLength); + } +} +exports.SerializerBase = SerializerBase; +SerializerBase.customSerializers = undefined; +class DateSerializer extends CustomSerializer { + constructor() { + super(["Date"]); + } + serialize(serializer, value, kind) { + serializer.writeString(value.toISOString()); + } +} +SerializerBase.registerCustomSerializer(new DateSerializer()); +function unsafeCast(value) { + return value; +} +exports.unsafeCast = unsafeCast; +//# sourceMappingURL=SerializerBase.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/Wrapper.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Wrapper.d.ts new file mode 100644 index 000000000..44c84a9f8 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Wrapper.d.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KPointer } from "./InteropTypes"; +export { isNullPtr, nullptr, ptrToBits, bitsToPtr, isSamePtr, ptrToString } from "#common/wrappers/Wrapper"; +/** + * An object holding reference to the native pointer. + */ +export declare class Wrapper { + ptr: KPointer; + constructor(ptr: KPointer); + toString(): string; +} +export declare function getPtr(value: Wrapper | undefined): KPointer; +export declare function ptrEqual(a: Wrapper | undefined, b: Wrapper | undefined): boolean; +//# sourceMappingURL=Wrapper.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/Wrapper.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Wrapper.js new file mode 100644 index 000000000..dfbdcd17e --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/Wrapper.js @@ -0,0 +1,54 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ptrEqual = exports.getPtr = exports.Wrapper = exports.ptrToString = exports.isSamePtr = exports.bitsToPtr = exports.ptrToBits = exports.nullptr = exports.isNullPtr = void 0; +const Wrapper_1 = require("#common/wrappers/Wrapper"); +const common_1 = require("#koalaui/common"); +var Wrapper_2 = require("#common/wrappers/Wrapper"); +Object.defineProperty(exports, "isNullPtr", { enumerable: true, get: function () { return Wrapper_2.isNullPtr; } }); +Object.defineProperty(exports, "nullptr", { enumerable: true, get: function () { return Wrapper_2.nullptr; } }); +Object.defineProperty(exports, "ptrToBits", { enumerable: true, get: function () { return Wrapper_2.ptrToBits; } }); +Object.defineProperty(exports, "bitsToPtr", { enumerable: true, get: function () { return Wrapper_2.bitsToPtr; } }); +Object.defineProperty(exports, "isSamePtr", { enumerable: true, get: function () { return Wrapper_2.isSamePtr; } }); +Object.defineProperty(exports, "ptrToString", { enumerable: true, get: function () { return Wrapper_2.ptrToString; } }); +/** + * An object holding reference to the native pointer. + */ +class Wrapper { + constructor(ptr) { + if (ptr == null) + throw new Error(`Init <${(0, common_1.className)(this)}> with null native peer`); + this.ptr = ptr; + } + toString() { + return `[native object <${(0, common_1.className)(this)}> at ${(0, Wrapper_1.ptrToString)(this.ptr)}]`; + } +} +exports.Wrapper = Wrapper; +function getPtr(value) { + var _a; + return (_a = value === null || value === void 0 ? void 0 : value.ptr) !== null && _a !== void 0 ? _a : Wrapper_1.nullptr; +} +exports.getPtr = getPtr; +function ptrEqual(a, b) { + if (a === b) + return true; + if (a == undefined || b == undefined) + return false; + return (0, Wrapper_1.isSamePtr)(a.ptr, b.ptr); +} +exports.ptrEqual = ptrEqual; +//# sourceMappingURL=Wrapper.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/arrays.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/arrays.d.ts new file mode 100644 index 000000000..e610b47da --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/arrays.d.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/common"; +export declare enum Access { + READ = 1, + WRITE = 2, + READWRITE = 3 +} +export declare function isRead(access: Access): number; +export declare function isWrite(access: Access): number; +export type Exec = (pointer: P) => R; +export type ExecWithLength = (pointer: P, length: int32) => R; +export type TypedArray = Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array; +export type PtrArray = Uint32Array | BigUint64Array; +//# sourceMappingURL=arrays.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/arrays.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/arrays.js new file mode 100644 index 000000000..783d697f1 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/arrays.js @@ -0,0 +1,32 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isWrite = exports.isRead = exports.Access = void 0; +var Access; +(function (Access) { + Access[Access["READ"] = 1] = "READ"; + Access[Access["WRITE"] = 2] = "WRITE"; + Access[Access["READWRITE"] = 3] = "READWRITE"; +})(Access = exports.Access || (exports.Access = {})); +function isRead(access) { + return access & Access.READ; +} +exports.isRead = isRead; +function isWrite(access) { + return access & Access.WRITE; +} +exports.isWrite = isWrite; +//# sourceMappingURL=arrays.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/buffer.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/buffer.d.ts new file mode 100644 index 000000000..09fa8065b --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/buffer.d.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare class KBuffer { + private readonly _buffer; + get buffer(): ArrayBuffer; + get length(): number; + constructor(length: number); + set(index: number, value: number): void; + get(index: number): number; +} +//# sourceMappingURL=buffer.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/buffer.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/buffer.js new file mode 100644 index 000000000..9a8111a81 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/buffer.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.KBuffer = void 0; +// todo can be removed if passing ArrayBuffer type through interop is possible +class KBuffer { + get buffer() { + return this._buffer; + } + get length() { + return this._buffer.length; + } + constructor(length) { + this._buffer = new Uint8Array(length); + } + set(index, value) { + this._buffer[index] = value; + } + get(index) { + return this._buffer[index]; + } +} +exports.KBuffer = KBuffer; +//# sourceMappingURL=buffer.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/index.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/index.d.ts new file mode 100644 index 000000000..b06ae1e32 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/index.d.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { withFloat32Array, withFloat64Array, withInt16Array, withInt32Array, withInt8Array, withUint16Array, withUint32Array, withUint8Array, wasmHeap as wasmHeapArrayBuffer } from "#common/wrappers/arrays"; +export { registerCallback, setCallbackRegistry } from "#common/wrappers/Callback"; +export { Access, Exec } from "./arrays"; +export { Finalizable, NativeThunk } from "./Finalizable"; +export { nullable } from "./nullable"; +export { getPtr, isNullPtr, nullptr, ptrEqual, Wrapper, ptrToBits, bitsToPtr } from "./Wrapper"; +export { decodeToString, encodeToData, withString, withStringArray, withPtrArray, fromPtrArray, toPtrArray } from "#common/wrappers/arrays"; +export declare const withFloatArray: typeof withFloat32Array; +export declare const withByteArray: typeof withUint8Array; +export declare const withIntArray: typeof withInt32Array; +export declare const wasmHeap: typeof wasmHeapArrayBuffer; +export { withFloat32Array, withFloat64Array, withInt8Array, withInt16Array, withInt32Array, withUint8Array, withUint16Array, withUint32Array, }; +export * from "./Platform"; +export * from "./InteropTypes"; +export * from "./InteropOps"; +export * from "./NativeString"; +export * from "./buffer"; +export * from "../arkts/ResourceManager"; +export * from "./NativeBuffer"; +export { InteropNativeModule, loadInteropNativeModule } from "./InteropNativeModule"; +export { SerializerBase, RuntimeType, Tags, runtimeType, CallbackResource, unsafeCast, isResource, isInstanceOf } from "./SerializerBase"; +export { DeserializerBase } from "./DeserializerBase"; +export { loadNativeModuleLibrary, loadNativeLibrary, registerNativeModuleLibraryName } from "./loadLibraries"; +export * from "./MaterializedBase"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/index.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/index.js new file mode 100644 index 000000000..8067bd807 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/index.js @@ -0,0 +1,96 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.registerNativeModuleLibraryName = exports.loadNativeLibrary = exports.loadNativeModuleLibrary = exports.DeserializerBase = exports.isInstanceOf = exports.isResource = exports.unsafeCast = exports.runtimeType = exports.Tags = exports.RuntimeType = exports.SerializerBase = exports.loadInteropNativeModule = exports.InteropNativeModule = exports.withUint32Array = exports.withUint16Array = exports.withUint8Array = exports.withInt32Array = exports.withInt16Array = exports.withInt8Array = exports.withFloat64Array = exports.withFloat32Array = exports.wasmHeap = exports.withIntArray = exports.withByteArray = exports.withFloatArray = exports.toPtrArray = exports.fromPtrArray = exports.withPtrArray = exports.withStringArray = exports.withString = exports.encodeToData = exports.decodeToString = exports.bitsToPtr = exports.ptrToBits = exports.Wrapper = exports.ptrEqual = exports.nullptr = exports.isNullPtr = exports.getPtr = exports.nullable = exports.NativeThunk = exports.Finalizable = exports.Access = exports.setCallbackRegistry = exports.registerCallback = void 0; +const arrays_1 = require("#common/wrappers/arrays"); +Object.defineProperty(exports, "withFloat32Array", { enumerable: true, get: function () { return arrays_1.withFloat32Array; } }); +Object.defineProperty(exports, "withFloat64Array", { enumerable: true, get: function () { return arrays_1.withFloat64Array; } }); +Object.defineProperty(exports, "withInt16Array", { enumerable: true, get: function () { return arrays_1.withInt16Array; } }); +Object.defineProperty(exports, "withInt32Array", { enumerable: true, get: function () { return arrays_1.withInt32Array; } }); +Object.defineProperty(exports, "withInt8Array", { enumerable: true, get: function () { return arrays_1.withInt8Array; } }); +Object.defineProperty(exports, "withUint16Array", { enumerable: true, get: function () { return arrays_1.withUint16Array; } }); +Object.defineProperty(exports, "withUint32Array", { enumerable: true, get: function () { return arrays_1.withUint32Array; } }); +Object.defineProperty(exports, "withUint8Array", { enumerable: true, get: function () { return arrays_1.withUint8Array; } }); +var Callback_1 = require("#common/wrappers/Callback"); +Object.defineProperty(exports, "registerCallback", { enumerable: true, get: function () { return Callback_1.registerCallback; } }); +Object.defineProperty(exports, "setCallbackRegistry", { enumerable: true, get: function () { return Callback_1.setCallbackRegistry; } }); +var arrays_2 = require("./arrays"); +Object.defineProperty(exports, "Access", { enumerable: true, get: function () { return arrays_2.Access; } }); +var Finalizable_1 = require("./Finalizable"); +Object.defineProperty(exports, "Finalizable", { enumerable: true, get: function () { return Finalizable_1.Finalizable; } }); +Object.defineProperty(exports, "NativeThunk", { enumerable: true, get: function () { return Finalizable_1.NativeThunk; } }); +var nullable_1 = require("./nullable"); +Object.defineProperty(exports, "nullable", { enumerable: true, get: function () { return nullable_1.nullable; } }); +var Wrapper_1 = require("./Wrapper"); +Object.defineProperty(exports, "getPtr", { enumerable: true, get: function () { return Wrapper_1.getPtr; } }); +Object.defineProperty(exports, "isNullPtr", { enumerable: true, get: function () { return Wrapper_1.isNullPtr; } }); +Object.defineProperty(exports, "nullptr", { enumerable: true, get: function () { return Wrapper_1.nullptr; } }); +Object.defineProperty(exports, "ptrEqual", { enumerable: true, get: function () { return Wrapper_1.ptrEqual; } }); +Object.defineProperty(exports, "Wrapper", { enumerable: true, get: function () { return Wrapper_1.Wrapper; } }); +Object.defineProperty(exports, "ptrToBits", { enumerable: true, get: function () { return Wrapper_1.ptrToBits; } }); +Object.defineProperty(exports, "bitsToPtr", { enumerable: true, get: function () { return Wrapper_1.bitsToPtr; } }); +var arrays_3 = require("#common/wrappers/arrays"); +Object.defineProperty(exports, "decodeToString", { enumerable: true, get: function () { return arrays_3.decodeToString; } }); +Object.defineProperty(exports, "encodeToData", { enumerable: true, get: function () { return arrays_3.encodeToData; } }); +Object.defineProperty(exports, "withString", { enumerable: true, get: function () { return arrays_3.withString; } }); +Object.defineProperty(exports, "withStringArray", { enumerable: true, get: function () { return arrays_3.withStringArray; } }); +Object.defineProperty(exports, "withPtrArray", { enumerable: true, get: function () { return arrays_3.withPtrArray; } }); +Object.defineProperty(exports, "fromPtrArray", { enumerable: true, get: function () { return arrays_3.fromPtrArray; } }); +Object.defineProperty(exports, "toPtrArray", { enumerable: true, get: function () { return arrays_3.toPtrArray; } }); +exports.withFloatArray = arrays_1.withFloat32Array; +exports.withByteArray = arrays_1.withUint8Array; +exports.withIntArray = arrays_1.withInt32Array; +exports.wasmHeap = arrays_1.wasmHeap; +__exportStar(require("./Platform"), exports); +__exportStar(require("./InteropTypes"), exports); +__exportStar(require("./InteropOps"), exports); +__exportStar(require("./NativeString"), exports); +__exportStar(require("./buffer"), exports); +__exportStar(require("../arkts/ResourceManager"), exports); +__exportStar(require("./NativeBuffer"), exports); +var InteropNativeModule_1 = require("./InteropNativeModule"); +Object.defineProperty(exports, "InteropNativeModule", { enumerable: true, get: function () { return InteropNativeModule_1.InteropNativeModule; } }); +Object.defineProperty(exports, "loadInteropNativeModule", { enumerable: true, get: function () { return InteropNativeModule_1.loadInteropNativeModule; } }); +var SerializerBase_1 = require("./SerializerBase"); +Object.defineProperty(exports, "SerializerBase", { enumerable: true, get: function () { return SerializerBase_1.SerializerBase; } }); +Object.defineProperty(exports, "RuntimeType", { enumerable: true, get: function () { return SerializerBase_1.RuntimeType; } }); +Object.defineProperty(exports, "Tags", { enumerable: true, get: function () { return SerializerBase_1.Tags; } }); +Object.defineProperty(exports, "runtimeType", { enumerable: true, get: function () { return SerializerBase_1.runtimeType; } }); +Object.defineProperty(exports, "unsafeCast", { enumerable: true, get: function () { return SerializerBase_1.unsafeCast; } }); +Object.defineProperty(exports, "isResource", { enumerable: true, get: function () { return SerializerBase_1.isResource; } }); +Object.defineProperty(exports, "isInstanceOf", { enumerable: true, get: function () { return SerializerBase_1.isInstanceOf; } }); +var DeserializerBase_1 = require("./DeserializerBase"); +Object.defineProperty(exports, "DeserializerBase", { enumerable: true, get: function () { return DeserializerBase_1.DeserializerBase; } }); +var loadLibraries_1 = require("./loadLibraries"); +Object.defineProperty(exports, "loadNativeModuleLibrary", { enumerable: true, get: function () { return loadLibraries_1.loadNativeModuleLibrary; } }); +Object.defineProperty(exports, "loadNativeLibrary", { enumerable: true, get: function () { return loadLibraries_1.loadNativeLibrary; } }); +Object.defineProperty(exports, "registerNativeModuleLibraryName", { enumerable: true, get: function () { return loadLibraries_1.registerNativeModuleLibraryName; } }); +__exportStar(require("./MaterializedBase"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/loadLibraries.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/loadLibraries.d.ts new file mode 100644 index 000000000..1089c8bd4 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/loadLibraries.d.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2022-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. + */ + +export declare function loadNativeLibrary(name: string): Record; +export declare function registerNativeModuleLibraryName(nativeModule: string, libraryName: string): void; +export declare function loadNativeModuleLibrary(moduleName: string, module?: object): void; +//# sourceMappingURL=loadLibraries.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/loadLibraries.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/loadLibraries.js new file mode 100644 index 000000000..5446b33c3 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/loadLibraries.js @@ -0,0 +1,45 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadNativeModuleLibrary = exports.registerNativeModuleLibraryName = exports.loadNativeLibrary = void 0; +const nativeModuleLibraries = new Map(); +function loadNativeLibrary(name) { + if (globalThis.requireNapi) + return globalThis.requireNapi(name, true); + else { + const suffixedName = name.endsWith(".node") ? name : `${name}.node`; + return require(suffixedName) + } +} +exports.loadNativeLibrary = loadNativeLibrary; +function registerNativeModuleLibraryName(nativeModule, libraryName) { + nativeModuleLibraries.set(nativeModule, libraryName); +} +exports.registerNativeModuleLibraryName = registerNativeModuleLibraryName; +function loadNativeModuleLibrary(moduleName, module) { + var _a; + if (!module) + throw new Error(" argument is required and optional only for compatibility with ArkTS"); + const library = loadNativeLibrary((_a = nativeModuleLibraries.get(moduleName)) !== null && _a !== void 0 ? _a : moduleName); + if (!library || !library[moduleName]) { + console.error(`Failed to load library for module ${moduleName}`); + return; + } + Object.assign(module, library[moduleName]); +} +exports.loadNativeModuleLibrary = loadNativeModuleLibrary; +//# sourceMappingURL=loadLibraries.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/nullable.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/interop/nullable.d.ts new file mode 100644 index 000000000..bf90c00ac --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/nullable.d.ts @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KPointer } from "./InteropTypes"; +export declare function nullable(value: KPointer, body: (arg: KPointer) => T | undefined): T | undefined; +//# sourceMappingURL=nullable.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/interop/nullable.js b/koala-wrapper/koalaui/interop/dist/lib/src/interop/nullable.js new file mode 100644 index 000000000..13b7d505e --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/interop/nullable.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.nullable = void 0; +const Wrapper_1 = require("./Wrapper"); +function nullable(value, body) { + if ((0, Wrapper_1.isNullPtr)(value)) { + return undefined; + } + else { + return body(value); + } +} +exports.nullable = nullable; +//# sourceMappingURL=nullable.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Callback.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Callback.d.ts new file mode 100644 index 000000000..bef3cebce --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Callback.d.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KPointer } from "../../interop/InteropTypes"; +import { CallbackRegistry } from "../../interop/Platform"; +export declare function registerCallback(callback: any, obj?: any): KPointer; +export declare function setCallbackRegistry(registry: CallbackRegistry): void; +//# sourceMappingURL=Callback.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Callback.js b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Callback.js new file mode 100644 index 000000000..c30af143e --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Callback.js @@ -0,0 +1,27 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setCallbackRegistry = exports.registerCallback = void 0; +function registerCallback(callback, obj = null) { + return theRegistry.registerCallback(callback, obj); +} +exports.registerCallback = registerCallback; +let theRegistry = undefined; +function setCallbackRegistry(registry) { + theRegistry = registry; +} +exports.setCallbackRegistry = setCallbackRegistry; +//# sourceMappingURL=Callback.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Wrapper.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Wrapper.d.ts new file mode 100644 index 000000000..6a35ba0bd --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Wrapper.d.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/common"; +import { KPointer } from "../../interop/InteropTypes"; +export declare const nullptr: bigint; +export declare function isNullPtr(value: KPointer): boolean; +export declare function ptrToString(ptr: KPointer): string; +export declare function isSamePtr(a: KPointer, b: KPointer): boolean; +export declare function ptrToBits(ptr: KPointer): Uint32Array | null; +export declare function bitsToPtr(array: Int32Array, offset: int32): KPointer; +//# sourceMappingURL=Wrapper.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Wrapper.js b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Wrapper.js new file mode 100644 index 000000000..dd3dd6116 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/Wrapper.js @@ -0,0 +1,46 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bitsToPtr = exports.ptrToBits = exports.isSamePtr = exports.ptrToString = exports.isNullPtr = exports.nullptr = void 0; +exports.nullptr = BigInt(0); +function isNullPtr(value) { + return value === exports.nullptr; +} +exports.isNullPtr = isNullPtr; +function ptrToString(ptr) { + return `0x${ptr.toString(16).padStart(8, "0")}`; +} +exports.ptrToString = ptrToString; +function isSamePtr(a, b) { + return (a === b); +} +exports.isSamePtr = isSamePtr; +// TODO rethink me +function ptrToBits(ptr) { + let result = new Uint32Array(2); + let ptrBigInt = ptr; + result[0] = Number(ptrBigInt & BigInt(0xFFFFFFFF)); + result[1] = Number((ptrBigInt >> BigInt(32)) & BigInt(0xFFFFFFFF)); + return result; +} +exports.ptrToBits = ptrToBits; +function bitsToPtr(array, offset) { + let ptrBigInt = BigInt(array[offset + 1]) & BigInt(0xFFFFFFFF); + ptrBigInt = (ptrBigInt << BigInt(32)) | (BigInt(array[offset]) & BigInt(0xFFFFFFFF)); + return ptrBigInt; +} +exports.bitsToPtr = bitsToPtr; +//# sourceMappingURL=Wrapper.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/arrays.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/arrays.d.ts new file mode 100644 index 000000000..c6a9d1171 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/arrays.d.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Access, Exec, ExecWithLength, PtrArray } from "../../interop/arrays"; +import { Wrapper } from "../../interop/Wrapper"; +import { KPointer, KStringArrayPtr } from "../../interop"; +export declare function decodeToString(array: Uint8Array): string; +export declare function encodeToData(string: string): Uint8Array; +export declare function withString(data: string | undefined, exec: Exec): R; +export declare function withStringArray(strings: Array | undefined, exec: Exec): R; +export declare function withPtrArray(data: BigUint64Array, access: Access, exec: ExecWithLength): R; +export declare function toPtrArray(data: Array | undefined): BigUint64Array; +export declare function fromPtrArray(array: PtrArray, factory: (ptr: KPointer) => T): Array; +export declare function withUint8Array(data: Uint8Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withInt8Array(data: Int8Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withUint16Array(data: Uint16Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withInt16Array(data: Int16Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withUint32Array(data: Uint32Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withInt32Array(data: Int32Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withFloat32Array(data: Float32Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withFloat64Array(data: Float64Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function wasmHeap(): ArrayBuffer; +//# sourceMappingURL=arrays.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/arrays.js b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/arrays.js new file mode 100644 index 000000000..bf8bea46d --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/napi/wrappers/arrays.js @@ -0,0 +1,116 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wasmHeap = exports.withFloat64Array = exports.withFloat32Array = exports.withInt32Array = exports.withUint32Array = exports.withInt16Array = exports.withUint16Array = exports.withInt8Array = exports.withUint8Array = exports.fromPtrArray = exports.toPtrArray = exports.withPtrArray = exports.withStringArray = exports.withString = exports.encodeToData = exports.decodeToString = void 0; +const common_1 = require("#koalaui/common"); +const Wrapper_1 = require("./Wrapper"); +const encoder = new common_1.CustomTextEncoder(); +const decoder = new common_1.CustomTextDecoder(); +function decodeToString(array) { + return decoder.decode(array); +} +exports.decodeToString = decodeToString; +function encodeToData(string) { + return encoder.encode(string, false); +} +exports.encodeToData = encodeToData; +function withString(data, exec) { + return exec(data === undefined ? null : data); +} +exports.withString = withString; +function withStringArray(strings, exec) { + if (strings === undefined || strings.length === 0) { + return exec(null); + } + let array = encoder.encodeArray(strings); + return exec(array); +} +exports.withStringArray = withStringArray; +function withArray(data, exec) { + var _a; + return exec(data !== null && data !== void 0 ? data : null, (_a = data === null || data === void 0 ? void 0 : data.length) !== null && _a !== void 0 ? _a : 0); +} +function withPtrArray(data, access, exec) { + var _a; + return exec(data !== null && data !== void 0 ? data : null, (_a = data === null || data === void 0 ? void 0 : data.length) !== null && _a !== void 0 ? _a : 0); // TODO rethink +} +exports.withPtrArray = withPtrArray; +function toPtrArray(data) { + if (data == undefined || data.length === 0) { + return new BigUint64Array(0); + } + const array = new BigUint64Array(data.length); + for (let i = 0; i < data.length; i++) { + let item = data[i]; + array[i] = item != undefined ? item.ptr : Wrapper_1.nullptr; + } + return array; +} +exports.toPtrArray = toPtrArray; +function fromPtrArray(array, factory) { + if (array.length === 0) { + return new Array(0); + } + const result = new Array(array.length); + for (let i = 0; i < array.length; i++) { + let ptr = array[i]; + if (ptr == Wrapper_1.nullptr) { + result[i] = undefined; + } + else { + result[i] = factory(ptr); + } + } + return result; +} +exports.fromPtrArray = fromPtrArray; +function withUint8Array(data, access, exec) { + return withArray(data, exec); +} +exports.withUint8Array = withUint8Array; +function withInt8Array(data, access, exec) { + return withArray(data, exec); +} +exports.withInt8Array = withInt8Array; +function withUint16Array(data, access, exec) { + return withArray(data, exec); +} +exports.withUint16Array = withUint16Array; +function withInt16Array(data, access, exec) { + return withArray(data, exec); +} +exports.withInt16Array = withInt16Array; +function withUint32Array(data, access, exec) { + return withArray(data, exec); +} +exports.withUint32Array = withUint32Array; +function withInt32Array(data, access, exec) { + return withArray(data, exec); +} +exports.withInt32Array = withInt32Array; +function withFloat32Array(data, access, exec) { + return withArray(data, exec); +} +exports.withFloat32Array = withFloat32Array; +function withFloat64Array(data, access, exec) { + return withArray(data, exec); +} +exports.withFloat64Array = withFloat64Array; +function wasmHeap() { + throw new Error("Unused"); +} +exports.wasmHeap = wasmHeap; +//# sourceMappingURL=arrays.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Callback.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Callback.d.ts new file mode 100644 index 000000000..558d0b4fd --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Callback.d.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KPointer } from "../../interop/InteropTypes"; +import { CallbackRegistry } from "../../interop/Platform"; +export declare function registerCallback(callback: any, obj?: any): KPointer; +export declare function setCallbackRegistry(_ignoredRegistry: CallbackRegistry): void; +//# sourceMappingURL=Callback.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Callback.js b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Callback.js new file mode 100644 index 000000000..42d551ac4 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Callback.js @@ -0,0 +1,81 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setCallbackRegistry = exports.registerCallback = void 0; +class CallbackInfo { + constructor(callback, obj = null) { + this.cb = callback; + this.recv = obj; + } +} +const GLOBAL_SCOPE = new (_a = class CallbackScope { + constructor() { + this.nextId = 1; + this.callbackMap = new Map(); + this.callbackMap.set(CallbackScope.CB_NULL_ID, CallbackScope.CB_NULL); + } + addCallback(cb, obj) { + var _a; + let id = this.nextId++; + (_a = this.callbackMap) === null || _a === void 0 ? void 0 : _a.set(id, new CallbackInfo(cb, obj)); + return id; + } + getCallback(id) { + var _a; + return ((_a = this.callbackMap) === null || _a === void 0 ? void 0 : _a.get(id)) || CallbackScope.CB_UNDEFINED; + } + deleteCallback(id) { + var _a; + if (id > CallbackScope.CB_NULL_ID) { + (_a = this.callbackMap) === null || _a === void 0 ? void 0 : _a.delete(id); + } + } + release() { + this.callbackMap = null; + } + }, + _a.CB_NULL = new CallbackInfo(() => { throw new Error("attempted to call a callback at NULL"); }, null), + _a.CB_UNDEFINED = new CallbackInfo(() => { throw new Error("attempted to call an uninitialized callback"); }, null), + _a.CB_NULL_ID = 0, + _a); +function callCallback(callbackId) { + let CallbackInfo = GLOBAL_SCOPE.getCallback(callbackId); + try { + let cb = CallbackInfo.cb; + if (CallbackInfo.recv !== null) { + cb = cb.bind(CallbackInfo.recv); + } + return cb(); + } + catch (e) { + console.error(e); + } +} +function registerCallback(callback, obj = null) { + return GLOBAL_SCOPE.addCallback(callback, obj); +} +exports.registerCallback = registerCallback; +function releaseCallback(callbackId) { + return GLOBAL_SCOPE.deleteCallback(callbackId); +} +globalThis.callCallback = callCallback; +globalThis.releaseCallback = releaseCallback; +function setCallbackRegistry(_ignoredRegistry) { + // On WASM we don't need registry in current implementation. +} +exports.setCallbackRegistry = setCallbackRegistry; +//# sourceMappingURL=Callback.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Wrapper.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Wrapper.d.ts new file mode 100644 index 000000000..dc132570a --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Wrapper.d.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "#koalaui/common"; +import { KPointer } from "../../interop/InteropTypes"; +export declare const nullptr: number; +export declare function isNullPtr(value: KPointer): boolean; +export declare function ptrToString(ptr: KPointer): string; +export declare function isSamePtr(a: KPointer, b: KPointer): boolean; +export declare function ptrToBits(ptr: KPointer): Uint32Array; +export declare function bitsToPtr(array: Int32Array, offset: int32): KPointer; +//# sourceMappingURL=Wrapper.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Wrapper.js b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Wrapper.js new file mode 100644 index 000000000..b849ad662 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/Wrapper.js @@ -0,0 +1,44 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bitsToPtr = exports.ptrToBits = exports.isSamePtr = exports.ptrToString = exports.isNullPtr = exports.nullptr = void 0; +exports.nullptr = 0; +function isNullPtr(value) { + return (value == exports.nullptr); +} +exports.isNullPtr = isNullPtr; +function ptrToString(ptr) { + if (ptr === 0) + return "0x0"; + const hex = ptr.toString(16).padStart(8, "0"); + return `0x${hex}`; +} +exports.ptrToString = ptrToString; +function isSamePtr(a, b) { + return a === b; +} +exports.isSamePtr = isSamePtr; +function ptrToBits(ptr) { + let result = new Uint32Array(2); + result[0] = ptr; + return result; +} +exports.ptrToBits = ptrToBits; +function bitsToPtr(array, offset) { + return array[offset]; +} +exports.bitsToPtr = bitsToPtr; +//# sourceMappingURL=Wrapper.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/arrays.d.ts b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/arrays.d.ts new file mode 100644 index 000000000..e539c7462 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/arrays.d.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KPointer } from "../../interop/InteropTypes"; +import { Wrapper } from "../../interop/Wrapper"; +import { Access, Exec, ExecWithLength } from "../../interop/arrays"; +export declare function decodeToString(array: Uint8Array): string; +export declare function encodeToData(string: string): Uint8Array; +export declare function withString(data: string | undefined, exec: Exec): R; +export declare function withStringArray(strings: Array | undefined, exec: Exec): R; +export declare function withPtrArray(data: Uint32Array, access: Access, exec: ExecWithLength): R; +export declare function toPtrArray(data: Array | undefined): Uint32Array; +export declare function fromPtrArray(array: Uint32Array, factory: (ptr: KPointer) => T): Array; +export declare function withUint8Array(data: Uint8Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withInt8Array(data: Int8Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withUint16Array(data: Uint16Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withInt16Array(data: Int16Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withUint32Array(data: Uint32Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withInt32Array(data: Int32Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withFloat32Array(data: Float32Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function withFloat64Array(data: Float64Array | undefined, access: Access, exec: ExecWithLength): T; +export declare function wasmHeap(): ArrayBuffer; +//# sourceMappingURL=arrays.d.ts.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/arrays.js b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/arrays.js new file mode 100644 index 000000000..9ee0f6369 --- /dev/null +++ b/koala-wrapper/koalaui/interop/dist/lib/src/wasm/wrappers/arrays.js @@ -0,0 +1,147 @@ +"use strict"; +/* + * Copyright (c) 2022-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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wasmHeap = exports.withFloat64Array = exports.withFloat32Array = exports.withInt32Array = exports.withUint32Array = exports.withInt16Array = exports.withUint16Array = exports.withInt8Array = exports.withUint8Array = exports.fromPtrArray = exports.toPtrArray = exports.withPtrArray = exports.withStringArray = exports.withString = exports.encodeToData = exports.decodeToString = void 0; +const common_1 = require("#koalaui/common"); +const arrays_1 = require("../../interop/arrays"); +const encoder = new common_1.CustomTextEncoder(); +const decoder = new common_1.CustomTextDecoder(); +function decodeToString(array) { + return decoder.decode(array); +} +exports.decodeToString = decodeToString; +function encodeToData(string) { + return encoder.encode(string, false); +} +exports.encodeToData = encodeToData; +const nullptr = 0; +// with string as array of utf8 data headed by length +function withString(data, exec) { + if (data === undefined) + return exec(nullptr); + let array = encoder.encode(data, true); + return withUint8Array(array, arrays_1.Access.READ, exec); +} +exports.withString = withString; +function withStringArray(strings, exec) { + if (strings === undefined || strings.length === 0) { + return exec(nullptr); + } + let array = encoder.encodeArray(strings); + return withUint8Array(array, arrays_1.Access.READ, exec); +} +exports.withStringArray = withStringArray; +function withArray(data, access, exec, bytesPerElement, ctor) { + if (data === undefined || data.length === 0) { + return exec(nullptr, 0); + } + let ptr = _malloc(data.length * bytesPerElement); + let wasmArray = ctor(ptr, data.length); + if ((0, arrays_1.isRead)(access)) { + wasmArray.set(data); + } + let result = exec(ptr, data.length); + if ((0, arrays_1.isWrite)(access)) { + data.set(wasmArray); + } + _free(ptr); + return result; +} +function withPtrArray(data, access, exec) { + return withArray(data, access, exec, Uint32Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Uint32Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withPtrArray = withPtrArray; +function toPtrArray(data) { + var _a; + if (data === undefined || data.length === 0) { + return new Uint32Array(0); + } + const array = new Uint32Array(data.length); + for (let i = 0; i < data.length; i++) { + array[i] = (_a = data[i]) === null || _a === void 0 ? void 0 : _a.ptr; + } + return array; +} +exports.toPtrArray = toPtrArray; +function fromPtrArray(array, factory) { + const result = new Array(array.length); + for (let i = 0; i < array.length; i++) { + let v = array[i]; + if (v == 0) { + result[i] = undefined; + } + else { + result[i] = factory(v); + } + } + return result; +} +exports.fromPtrArray = fromPtrArray; +function withUint8Array(data, access, exec) { + return withArray(data, access, exec, Uint8Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Uint8Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withUint8Array = withUint8Array; +function withInt8Array(data, access, exec) { + return withArray(data, access, exec, Int8Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Int8Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withInt8Array = withInt8Array; +function withUint16Array(data, access, exec) { + return withArray(data, access, exec, Uint16Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Uint16Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withUint16Array = withUint16Array; +function withInt16Array(data, access, exec) { + return withArray(data, access, exec, Int16Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Int16Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withInt16Array = withInt16Array; +function withUint32Array(data, access, exec) { + return withArray(data, access, exec, Uint32Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Uint32Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withUint32Array = withUint32Array; +function withInt32Array(data, access, exec) { + return withArray(data, access, exec, Int32Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Int32Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withInt32Array = withInt32Array; +function withFloat32Array(data, access, exec) { + return withArray(data, access, exec, Float32Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Float32Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withFloat32Array = withFloat32Array; +function withFloat64Array(data, access, exec) { + return withArray(data, access, exec, Float64Array.BYTES_PER_ELEMENT, (ptr, length) => { + return new Float64Array(_heaps.HEAPU8().buffer, ptr, length); + }); +} +exports.withFloat64Array = withFloat64Array; +function wasmHeap() { + return _heaps.HEAP32().buffer; +} +exports.wasmHeap = wasmHeap; +//# sourceMappingURL=arrays.js.map \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/oh-package.json5 b/koala-wrapper/koalaui/interop/oh-package.json5 new file mode 100644 index 000000000..49ca1a9b2 --- /dev/null +++ b/koala-wrapper/koalaui/interop/oh-package.json5 @@ -0,0 +1,62 @@ +{ + "name": "@koalaui/interop", + "version": "1.4.1+devel", + "description": "", + "files": [ + "build/lib/src/**/*.js", + "build/lib/src/**/*.d.ts" + ], + "main": "./build/lib/src/interop/index.js", + "exports": { + ".": "./build/lib/src/interop/index.js", + "./*.js": "./build/lib/src/interop/*.js", + "./*": "./build/lib/src/interop/*.js" + }, + "imports": { + "#common/wrappers": { + "browser": "./build/lib/src/wasm/wrappers/index.js", + "node": "./build/lib/src/napi/wrappers/index.js" + }, + "#common/wrappers/*": { + "browser": "./build/lib/src/wasm/wrappers/*.js", + "node": "./build/lib/src/napi/wrappers/*.js" + } + }, + "types": "./index.d.ts", + "typesVersions": { + "*": { + "*": ["./build/lib/src/interop/*"] + } + }, + "scripts": { + "clean": "tsc -b . --clean && rimraf dist build types", + "ets-api": "node scripts/download-ets-api.mjs", + "compile": "tsc -b .", + "compile:ohos": "npm run ets-api && npm run compile", + "compile:all": "npm run compile:ohos", + "compile:arkts": "bash ../tools/panda/arkts/arktsc --arktsconfig arktsconfig.json", + "lint": "eslint src test components", + "test:wasm:coverage": "NODE_OPTIONS='--conditions browser --no-experimental-fetch' nyc mocha", + "test:wasm": "NODE_OPTIONS='--conditions browser --no-experimental-fetch' mocha", + "test:node:coverage": "nyc mocha", + "test:node": "mocha", + "test:coverage": "npm run test:node:coverage", + "test": "npm run test:node", + "watch": "tsc -b . --watch" + }, + "keywords": [], + "dependencies": { + "@koalaui/common": "../common" + }, + "devDependencies": { + "@types/chai": "^4.3.1", + "@types/mocha": "^9.1.0", + "@typescript-eslint/eslint-plugin": "^5.20.0", + "@typescript-eslint/parser": "^5.20.0", + "chai": "^4.3.6", + "eslint": "^8.13.0", + "eslint-plugin-unused-imports": "^2.0.0", + "mocha": "^9.2.2", + "source-map-support": "^0.5.21" + } +} diff --git a/koala-wrapper/koalaui/interop/src/arkts/DeserializerBase.sts b/koala-wrapper/koalaui/interop/src/arkts/DeserializerBase.sts new file mode 100644 index 000000000..13b585d03 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/DeserializerBase.sts @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { float32, int32, int64, float32FromBits } from "@koalaui/common" +import { pointer, KUint8ArrayPtr } from "./InteropTypes" +import { KBuffer } from "./buffer" +import { NativeBuffer } from "./NativeBuffer" +import { InteropNativeModule } from "./InteropNativeModule" +import { Tags, CallbackResource } from "./SerializerBase"; + +export class DeserializerBase { + private position = 0 + private readonly buffer: KBuffer + private readonly length: int32 + private static customDeserializers: CustomDeserializer | undefined = new DateDeserializer() + + static registerCustomDeserializer(deserializer: CustomDeserializer) { + let current = DeserializerBase.customDeserializers + if (current == undefined) { + DeserializerBase.customDeserializers = deserializer + } else { + while (current!.next != undefined) { + current = current!.next + } + current!.next = deserializer + } + } + + constructor(buffer: KUint8ArrayPtr, length: int32) { + this.buffer = new KBuffer(buffer) + this.length = length + } + + static get( + factory: (args: Uint8Array, length: int32) => T, + args: Uint8Array, length: int32): T { + + // TBD: Use cache + return factory(args, length); + } + + asArray(): KUint8ArrayPtr { + return this.buffer.buffer + } + + currentPosition(): int32 { + return this.position + } + + resetCurrentPosition(): void { + this.position = 0 + } + + private checkCapacity(value: int32) { + if (value > this.length) { + throw new Error(`${value} is less than remaining buffer length`) + } + } + + readInt8(): int32 { + this.checkCapacity(1) + const value = this.buffer.get(this.position) + this.position += 1 + return value + } + + readInt32(): int32 { + this.checkCapacity(4) + let res: int32 = 0; + for (let i = 0; i < 4; i++) { + let byteVal = this.buffer.get(this.position + i) as int32; + byteVal &= 0xff + res = (res | byteVal << (8 * i)) as int32; + } + this.position += 4 + return res + } + + readPointer(): pointer { + this.checkCapacity(8) + let res: int64 = 0; + for (let i = 0; i < 8; i++) { + let byteVal = this.buffer.get(this.position + i) as int64; + byteVal &= 0xff + res = (res | byteVal << (8 * i)) as int64; + } + this.position += 8 + return res + } + + readInt64(): int64 { + this.checkCapacity(8) + let res: int64 = 0; + for (let i = 0; i < 8; i++) { + let byteVal = this.buffer.get(this.position + i) as int64; + byteVal &= 0xff + res = (res | byteVal << (8 * i)) as int64; + } + this.position += 8 + return res + } + + readFloat32(): float32 { + this.checkCapacity(4) + let res: int32 = 0; + for (let i = 0; i < 4; i++) { + let byteVal = this.buffer.get(this.position + i) as int32; + byteVal &= 0xff + res = (res | byteVal << (8 * i)) as int32; + } + this.position += 4 + return float32FromBits(res) + } + + readBoolean(): boolean { + this.checkCapacity(1) + const value = this.buffer.get(this.position) + this.position += 1 + return value == 1 + } + + readFunction(): int32 { + // TODO: not exactly correct. + const id = this.readInt32() + return id + } + + // readMaterialized(): object { + // const ptr = this.readPointer() + // return { ptr: ptr } + // } + + readCallbackResource(): CallbackResource { + return ({ + resourceId: this.readInt32(), + hold: this.readPointer(), + release: this.readPointer(), + } as CallbackResource) + } + + readString(): string { + const length = this.readInt32() + this.checkCapacity(length) + // read without null-terminated byte + const value = InteropNativeModule._Utf8ToString(this.buffer.buffer, this.position, length) + this.position += length + return value + } + + readCustomObject(kind: string): object { + let current = DeserializerBase.customDeserializers + while (current) { + if (current!.supports(kind)) { + return current!.deserialize(this, kind) + } + current = current!.next + } + // consume tag + const tag = this.readInt8() + throw Error(`${kind} is not supported`) + } + + readNumber(): number | undefined { + const tag = this.readInt8() + if (tag == Tags.UNDEFINED) { + return undefined + } else if (tag == Tags.INT32) { + return this.readInt32() + } else if (tag == Tags.FLOAT32) { + return this.readFloat32() + } else { + throw new Error(`Unknown number tag: ${tag}`) + } + } + + static lengthUnitFromInt(unit: int32): string { + let suffix: string + switch (unit) { + case 0: + suffix = "px" + break + case 1: + suffix = "vp" + break + case 3: + suffix = "%" + break + case 4: + suffix = "lpx" + break + default: + suffix = "" + } + return suffix + } + + readBuffer(): NativeBuffer { + /* not implemented */ + const resource = this.readCallbackResource() + const data = this.readPointer() + const length = this.readInt64() + return NativeBuffer.wrap(data, length, resource.resourceId, resource.hold, resource.release) + } + + readUint8ClampedArray(): Uint8ClampedArray { + throw new Error("Not implemented") + } +} + +export abstract class CustomDeserializer { + protected supported: string + protected constructor(supported_: string) { + this.supported = supported_ + } + + supports(kind: string): boolean { + return this.supported.includes(kind) + } + + abstract deserialize(serializer: DeserializerBase, kind: string): object + + next: CustomDeserializer | undefined = undefined +} + +class DateDeserializer extends CustomDeserializer { + constructor() { + super("Date") + } + + deserialize(serializer: DeserializerBase, kind: string): Date { + return new Date(serializer.readString()) + } +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/arkts/Finalizable.sts b/koala-wrapper/koalaui/interop/src/arkts/Finalizable.sts new file mode 100644 index 000000000..6ae3ac2d8 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/Finalizable.sts @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { finalizerRegister, finalizerUnregister, Thunk } from "@koalaui/common" +import { InteropNativeModule } from "./InteropNativeModule" +import { pointer, nullptr } from "./InteropTypes" + +class NativeThunk implements Thunk { + finalizer: pointer + obj: pointer + name: string|undefined + + constructor(obj: pointer, finalizer: pointer, name?: string) { + this.finalizer = finalizer + this.obj = obj + this.name = name + } + + clean() { + if (this.obj != nullptr) { + this.destroyNative(this.obj, this.finalizer) + } + this.obj = nullptr + } + + destroyNative(ptr: pointer, finalizer: pointer): void { + InteropNativeModule._InvokeFinalizer(ptr, finalizer) + } +} + +/** + * Class with the custom finalizer, usually used to release a native peer. + * Do not use directly, only via subclasses. + */ +export class Finalizable { + ptr: pointer + finalizer: pointer + cleaner: NativeThunk|undefined = undefined + managed: boolean + constructor(ptr: pointer, finalizer: pointer, managed: boolean = true) { + this.ptr = ptr + this.finalizer = finalizer + this.managed = managed + const handle = undefined + + if (this.managed) { + if (this.ptr == nullptr) throw new Error("Can't have nullptr ptr ${}") + if (this.finalizer == nullptr) throw new Error("Managed finalizer is 0") + + const thunk = new NativeThunk(ptr, finalizer, handle) + finalizerRegister(this, thunk) + this.cleaner = thunk + } + } + + close() { + if (this.ptr == nullptr) { + throw new Error(`Closing a closed object: ` + this.toString()) + } else if (this.cleaner == undefined) { + throw new Error(`No thunk assigned to ` + this.toString()) + } else { + finalizerUnregister(this) + this.cleaner!.clean() + this.cleaner = undefined + this.ptr = nullptr + } + } + + release(): pointer { + finalizerUnregister(this) + if (this.cleaner) + this.cleaner!.obj = nullptr + let result = this.ptr + this.ptr = nullptr + return result + } + + resetPeer(pointer: pointer) { + if (this.managed) throw new Error("Can only reset peer for an unmanaged object") + this.ptr = pointer + } + + use(body: (value: Finalizable) => R): R { + let result = body(this) + this.close() + return result + } +} diff --git a/koala-wrapper/koalaui/interop/src/arkts/InteropNativeModule.sts b/koala-wrapper/koalaui/interop/src/arkts/InteropNativeModule.sts new file mode 100644 index 000000000..d804174f6 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/InteropNativeModule.sts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common"; +import { KPointer, KUint8ArrayPtr, KInt } from "./InteropTypes"; +import { callCallback } from "./callback" +import { loadNativeModuleLibrary } from "./loadLibraries" + +export class InteropNativeModule { + static { + loadNativeModuleLibrary("InteropNativeModule") + } + static callCallbackFromNative(id: KInt, args: KUint8ArrayPtr, length: KInt): KInt { + return callCallback(id, args, length) + } + native static _GetGroupedLog(index: int32): KPointer + native static _StartGroupedLog(index: int32): void + native static _StopGroupedLog(index: int32): void + native static _AppendGroupedLog(index: int32, message: string): void + native static _PrintGroupedLog(index: int32): void + native static _GetStringFinalizer(): KPointer + native static _InvokeFinalizer(ptr1: KPointer, ptr2: KPointer): void + native static _GetPtrVectorElement(ptr1: KPointer, arg: int32): KPointer + native static _StringLength(ptr1: KPointer): int32 + native static _StringData(ptr1: KPointer, arr: KUint8ArrayPtr, i: int32): void + native static _StringMake(str1: string): KPointer + native static _GetPtrVectorSize(ptr1: KPointer): int32 + native static _ManagedStringWrite(str1: string, arr: KUint8ArrayPtr, arg: int32): int32 + native static _NativeLog(str1: string): void + native static _Utf8ToString(data: KUint8ArrayPtr, offset: int32, length: int32): string + native static _StdStringToString(cstring: KPointer): string + native static _CheckCallbackEvent(buffer: KUint8ArrayPtr, bufferLength: int32): int32 + native static _HoldCallbackResource(resourceId: int32): void + native static _ReleaseCallbackResource(resourceId: int32): void + native static _CallCallback(callbackKind: int32, args: KUint8ArrayPtr, argsSize: int32): void + native static _CallCallbackSync(callbackKind: int32, args: KUint8ArrayPtr, argsSize: int32): void + native static _CallCallbackResourceHolder(holder: KPointer, resourceId: int32): void + native static _CallCallbackResourceReleaser(releaser: KPointer, resourceId: int32): void + native static _LoadVirtualMachine(arg0: int32, arg1: string, arg2: string): int32 + native static _RunApplication(arg0: int32, arg1: int32): boolean + native static _StartApplication(appUrl: string, appParams: string): KPointer + native static _EmitEvent(eventType: int32, target: int32, arg0: int32, arg1: int32): void + native static _CallForeignVM(context:KPointer, callback: int32, data: KUint8ArrayPtr, dataLength: int32): int32 + native static _RestartWith(page: string): void +} + diff --git a/koala-wrapper/koalaui/interop/src/arkts/InteropTypes.sts b/koala-wrapper/koalaui/interop/src/arkts/InteropTypes.sts new file mode 100644 index 000000000..adbf6e433 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/InteropTypes.sts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022-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. + */ + +export type NodePointer = pointer // todo: move to NativeModule + +export type KStringPtr = string +export type KStringPtrArray = byte[] +export type KUint8ArrayPtr = byte[] +export type KInt32ArrayPtr = int[] +export type KFloat32ArrayPtr = float[] +export type KInt = int +export type KLong = long +export type KUInt = KInt +export type KBoolean = int +export type KFloat = float +export type KPointer = long // look once again +export type pointer = KPointer +export type KNativePointer = KPointer +export type KInteropReturnBuffer = byte[] + +export const nullptr: pointer = 0 + diff --git a/koala-wrapper/koalaui/interop/src/arkts/MaterializedBase.sts b/koala-wrapper/koalaui/interop/src/arkts/MaterializedBase.sts new file mode 100644 index 000000000..f0ea6ee4c --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/MaterializedBase.sts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Finalizable } from "./Finalizable" + +export interface MaterializedBase { + getPeer(): Finalizable | undefined +} + diff --git a/koala-wrapper/koalaui/interop/src/arkts/NativeBuffer.sts b/koala-wrapper/koalaui/interop/src/arkts/NativeBuffer.sts new file mode 100644 index 000000000..3c7eb7afe --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/NativeBuffer.sts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { pointer } from './InteropTypes' +import { int32, int64 } from '@koalaui/common' + +// stub wrapper for KInteropBuffer +export class NativeBuffer { + public data:pointer = 0 + public length: int64 = 0 + public resourceId: int32 = 0 + public hold:pointer = 0 + public release: pointer = 0 + + constructor(data:pointer, length: int64, resourceId: int32, hold:pointer, release: pointer) { + this.data = data + this.length = length + this.resourceId = resourceId + this.hold = hold + this.release = release + } + + static wrap(data:pointer, length: int64, resourceId: int32, hold:pointer, release: pointer): NativeBuffer { + return new NativeBuffer(data, length, resourceId, hold, release) + } +} diff --git a/koala-wrapper/koalaui/interop/src/arkts/ResourceManager.ts b/koala-wrapper/koalaui/interop/src/arkts/ResourceManager.ts new file mode 100644 index 000000000..985c81298 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/ResourceManager.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common" + +export type ResourceId = int32 + +interface ResourceInfo { + resource: object + holdersCount: int32 +} + +export class ResourceHolder { + private static nextResourceId: ResourceId = 100 + private resources: Map = new Map() + private static _instance: ResourceHolder|undefined = undefined + static instance(): ResourceHolder { + if (ResourceHolder._instance == undefined) { + ResourceHolder._instance = new ResourceHolder() + } + return ResourceHolder._instance! + } + + public hold(resourceId: ResourceId) { + if (!this.resources.has(resourceId)) + throw new Error(`Resource ${resourceId} does not exists, can not hold`) + this.resources.get(resourceId)!.holdersCount++ + } + + public release(resourceId: ResourceId) { + if (!this.resources.has(resourceId)) + throw new Error(`Resource ${resourceId} does not exists, can not release`) + const resource = this.resources.get(resourceId)! + resource.holdersCount-- + if (resource.holdersCount <= 0) + this.resources.delete(resourceId) + } + + public registerAndHold(resource: object): ResourceId { + const resourceId = ResourceHolder.nextResourceId++ + this.resources.set(resourceId, { + resource: resource, + holdersCount: 1, + }) + return resourceId + } + + public get(resourceId: ResourceId): object { + if (!this.resources.has(resourceId)) + throw new Error(`Resource ${resourceId} does not exists`) + return this.resources.get(resourceId)!.resource + } + + public has(resourceId: ResourceId): boolean { + return this.resources.has(resourceId) + } +} diff --git a/koala-wrapper/koalaui/interop/src/arkts/SerializerBase.sts b/koala-wrapper/koalaui/interop/src/arkts/SerializerBase.sts new file mode 100644 index 000000000..764590c8d --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/SerializerBase.sts @@ -0,0 +1,324 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { float32, float64, int8, int32, int64, int32BitsFromFloat } from "@koalaui/common" +import { pointer, KUint8ArrayPtr } from "./InteropTypes" +import { ResourceId, ResourceHolder } from "./ResourceManager" +import { KBuffer } from "./buffer" +import { NativeBuffer } from "./NativeBuffer" +import { InteropNativeModule } from "./InteropNativeModule" + +/** + * Value representing possible JS runtime object type. + * Must be synced with "enum RuntimeType" in C++. + */ +export class RuntimeType { + static UNEXPECTED = -1 + static NUMBER = 1 + static STRING = 2 + static OBJECT = 3 + static BOOLEAN = 4 + static UNDEFINED = 5 + static BIGINT = 6 + static FUNCTION = 7 + static SYMBOL = 8 + static MATERIALIZED = 9 +} + +/** + * Value representing object type in serialized data. + * Must be synced with "enum Tags" in C++. + */ +export class Tags { + static UNDEFINED = 101 + static INT32 = 102 + static FLOAT32 = 103 + static STRING = 104 + static LENGTH = 105 + static RESOURCE = 106 + static OBJECT = 107 +} + +export function runtimeType(value: Object|String|number|undefined|null): int32 { + let type = typeof value + if (type == "number") return RuntimeType.NUMBER + if (type == "string") return RuntimeType.STRING + if (type == "undefined") return RuntimeType.UNDEFINED + if (type == "object") return RuntimeType.OBJECT + if (type == "boolean") return RuntimeType.BOOLEAN + if (type == "bigint") return RuntimeType.BIGINT + if (type == "function") return RuntimeType.FUNCTION + if (type == "symbol") return RuntimeType.SYMBOL + + throw new Error(`bug: ${value} is ${type}`) +} + +export function registerCallback(value: object): int32 { + // TODO: fix me! + return 42 +} + +function registerMaterialized(value: Object): int32 { + // TODO: fix me! + return 42 +} + +export function isResource(value: Object|undefined): boolean { + // TODO: fix me! + return false +} + +export function isInstanceOf(className: string, value: Object|undefined): boolean { + // TODO: fix me! + return false +} + +export interface CallbackResource { + resourceId: int32 + hold: pointer + release: pointer +} + +/* Serialization extension point */ +export abstract class CustomSerializer { + protected supported: Array + constructor(supported: Array) { + this.supported = supported + } + supports(kind: string): boolean { return this.supported.includes(kind) } + abstract serialize(serializer: SerializerBase, value: object, kind: string): void + next: CustomSerializer | undefined = undefined +} + +class DateSerializer extends CustomSerializer { + constructor() { + super(Array.of("Date" as string)) + } + + serialize(serializer: SerializerBase, value: object, kind: string): void { + serializer.writeString((value as Date).toISOString()) + } +} +SerializerBase.registerCustomSerializer(new DateSerializer()) + +export class SerializerBase { + private position = 0 + private buffer: KBuffer + + private static customSerializers: CustomSerializer | undefined = new DateSerializer() + static registerCustomSerializer(serializer: CustomSerializer) { + if (SerializerBase.customSerializers == undefined) { + SerializerBase.customSerializers = serializer + } else { + let current = SerializerBase.customSerializers + while (current!.next != undefined) { + current = current!.next + } + current!.next = serializer + } + } + + resetCurrentPosition(): void { this.position = 0 } + + constructor() { + this.buffer = new KBuffer(96) + } + public release() { + this.releaseResources() + this.position = 0 + } + asArray(): KUint8ArrayPtr { + return this.buffer.buffer + } + length(): int32 { + return this.position + } + currentPosition(): int32 { return this.position } + private checkCapacity(value: int32) { + if (value < 1) { + throw new Error(`${value} is less than 1`) + } + let buffSize = this.buffer.length + if (this.position > buffSize - value) { + const minSize = this.position + value + const resizedSize = Math.max(minSize, Math.round(3 * buffSize / 2)) + let resizedBuffer = new KBuffer(resizedSize as int32) + for (let i = 0; i < this.buffer.length; i++) { + resizedBuffer.set(i, this.buffer.get(i)) + } + this.buffer = resizedBuffer + } + } + private heldResources: Array = new Array() + holdAndWriteCallback(callback: object, hold: pointer = 0, release: pointer = 0, call: pointer = 0, callSync: pointer = 0): ResourceId { + const resourceId = ResourceHolder.instance().registerAndHold(callback) + this.heldResources.push(resourceId) + this.writeInt32(resourceId) + this.writePointer(hold) + this.writePointer(release) + this.writePointer(call) + this.writePointer(callSync) + return resourceId + } + holdAndWriteCallbackForPromiseVoid(hold: pointer = 0, release: pointer = 0, call: pointer = 0): [Promise, ResourceId] { + let resourceId: ResourceId + const promise = new Promise((resolve: (value: PromiseLike) => void, reject: (err: Object|null|undefined) => void) => { + const callback = (err: string[]|undefined) => { + if (err !== undefined) + reject(err!) + else + resolve(Promise.resolve()) + } + resourceId = this.holdAndWriteCallback(callback, hold, release, call) + }) + return [promise, resourceId] + } + holdAndWriteCallbackForPromise(hold: pointer = 0, release: pointer = 0, call: pointer = 0): [Promise, ResourceId] { + let resourceId: ResourceId + const promise = new Promise((resolve: (value: T|PromiseLike) => void, reject: (err: Object|null|undefined) => void) => { + const callback = (value: T|undefined, err: string[]|undefined) => { + if (err !== undefined) + reject(err!) + else + resolve(value!) + } + resourceId = this.holdAndWriteCallback(callback, hold, release, call) + }) + return [promise, resourceId] + } + writeCallbackResource(resource: CallbackResource) { + this.writeInt32(resource.resourceId) + this.writePointer(resource.hold) + this.writePointer(resource.release) + } + writeResource(resource: object) { + const resourceId = ResourceHolder.instance().registerAndHold(resource) + this.heldResources.push(resourceId) + this.writeInt32(resourceId) + } + private releaseResources() { + for (const resourceId of this.heldResources) + InteropNativeModule._ReleaseCallbackResource(resourceId) + // todo think about effective array clearing/pushing + this.heldResources = new Array() + } + writeCustomObject(kind: string, value: object) { + let current = SerializerBase.customSerializers + while (current) { + if (current!.supports(kind)) { + current!.serialize(this, value, kind) + return + } + current = current!.next + } + // console.log(`Unsupported custom serialization for ${kind}, write undefined`) + this.writeInt8(Tags.UNDEFINED as int32) + } + writeFunction(value: Object) { + this.writeInt32(registerCallback(value)) + } + writeTag(tag: int32): void { + this.buffer.set(this.position, tag as int8) + this.position++ + } + writeNumber(value: number|undefined) { + this.checkCapacity(5) + if (value == undefined) { + this.writeTag(Tags.UNDEFINED) + this.position++ + return + } + if ((value as float64) == Math.round(value)) { + this.writeTag(Tags.INT32) + this.writeInt32(value as int32) + return + } else { + this.writeTag(Tags.FLOAT32) + this.writeFloat32(value as float32) + } + } + writeInt8(value: int32) { + this.checkCapacity(1) + this.buffer.set(this.position, value as int8) + this.position += 1 + } + private setInt32(position: int32, value: int32): void { + this.buffer.set(position + 0, ((value ) & 0xff) as int8) + this.buffer.set(position + 1, ((value >> 8) & 0xff) as int8) + this.buffer.set(position + 2, ((value >> 16) & 0xff) as int8) + this.buffer.set(position + 3, ((value >> 24) & 0xff) as int8) + } + writeInt32(value: int32) { + this.checkCapacity(4) + this.setInt32(this.position, value) + this.position += 4 + } + writeInt64(value: int64) { + this.checkCapacity(8) + this.buffer.set(this.position + 0, ((value ) & 0xff) as int8) + this.buffer.set(this.position + 1, ((value >> 8) & 0xff) as int8) + this.buffer.set(this.position + 2, ((value >> 16) & 0xff) as int8) + this.buffer.set(this.position + 3, ((value >> 24) & 0xff) as int8) + this.buffer.set(this.position + 4, ((value >> 32) & 0xff) as int8) + this.buffer.set(this.position + 5, ((value >> 40) & 0xff) as int8) + this.buffer.set(this.position + 6, ((value >> 48) & 0xff) as int8) + this.buffer.set(this.position + 7, ((value >> 56) & 0xff) as int8) + this.position += 8 + } + writeFloat32(value: float32) { + let bits = int32BitsFromFloat(value) + // TODO: this is wrong! + this.checkCapacity(4) + this.buffer.set(this.position + 0, ((bits ) & 0xff) as int8) + this.buffer.set(this.position + 1, ((bits >> 8) & 0xff) as int8) + this.buffer.set(this.position + 2, ((bits >> 16) & 0xff) as int8) + this.buffer.set(this.position + 3, ((bits >> 24) & 0xff) as int8) + this.position += 4 + } + writePointer(value: pointer) { + if (typeof value === "bigint") + // todo where it is possible to be called from? + throw new Error("Not implemented") + this.writeInt64(value) + } + writeBoolean(value: boolean|undefined) { + this.checkCapacity(1) + if (value == undefined) { + this.buffer.set(this.position, RuntimeType.UNDEFINED as int32 as int8) + } else { + this.buffer.set(this.position, (value ? 1 : 0) as int8) + } + this.position++ + } + writeMaterialized(value: Object) { + this.writePointer(registerMaterialized(value)) + } + writeString(value: string) { + this.checkCapacity((4 + value.length * 4 + 1) as int32) // length, data + let encodedLength = InteropNativeModule._ManagedStringWrite(value, this.asArray(), this.position + 4) + this.setInt32(this.position, encodedLength) + this.position += encodedLength + 4 + } + //TODO: Needs to be implemented + writeBuffer(value: NativeBuffer) { + this.writeCallbackResource({ + resourceId: value.resourceId, + hold: value.hold, + release: value.release + }) + this.writePointer(value.data) + this.writeInt64(value.length as int64) + } +} + diff --git a/koala-wrapper/koalaui/interop/src/arkts/buffer.sts b/koala-wrapper/koalaui/interop/src/arkts/buffer.sts new file mode 100644 index 000000000..d808bdc82 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/buffer.sts @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int8 } from "@koalaui/common" + +export class KBuffer { + private readonly _buffer: byte[] + public get buffer(): byte[] { + return this._buffer + } + public get length(): int { + return this._buffer.length + } + + constructor(length: int) { + this._buffer = new byte[length] + } + + constructor(buffer: byte[]) { + this._buffer = buffer + } + + set(index: int, value: int8): void { + this._buffer[index] = value as byte + } + + get(index: int): byte { + return this._buffer[index] + } +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/arkts/callback.sts b/koala-wrapper/koalaui/interop/src/arkts/callback.sts new file mode 100644 index 000000000..06992e1ac --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/callback.sts @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KUint8ArrayPtr } from "./InteropTypes" +import { int32 } from "@koalaui/common" + +export type CallbackType = (args: KUint8ArrayPtr, length: int32) => int32 + +class CallbackRecord { + public readonly callback: CallbackType + public readonly autoDisposable: boolean + + constructor( + callback: CallbackType, + autoDisposable: boolean + ) { + this.callback = callback + this.autoDisposable = autoDisposable + } +} + +class CallbackRegistry { + + static INSTANCE = new CallbackRegistry() + + private callbacks = new Map() + private id = 1024 + + constructor() { + this.callbacks.set(0, new CallbackRecord( + (args: KUint8ArrayPtr, length: int32): int32 => { + console.log(`Callback 0 called with args = ${args} and length = ${length}`) + throw new Error(`Null callback called`) + }, false) + ) + } + + wrap(callback: CallbackType, autoDisposable: boolean): int32 { + const id = this.id++ + this.callbacks.set(id, new CallbackRecord(callback, autoDisposable)) + return id + } + + wrapSystem(id: int32, callback: CallbackType, autoDisposable: boolean): int32 { + this.callbacks.set(id, new CallbackRecord(callback, autoDisposable)) + return id + } + + call(id: int32, args: KUint8ArrayPtr, length: int32): int32 { + const record = this.callbacks.get(id) + if (!record) { + console.log(`Callback ${id} is not known`) + throw new Error(`Disposed or unwrapped callback called (id = ${id})`) + } + if (record.autoDisposable) { + this.dispose(id) + } + return record.callback(args, length) + } + + dispose(id: int32) { + this.callbacks.delete(id) + } +} + +export function wrapCallback(callback: CallbackType, autoDisposable: boolean = true): int32 { + return CallbackRegistry.INSTANCE.wrap(callback, autoDisposable) +} + +export function wrapSystemCallback(id:int32, callback: CallbackType): int32 { + return CallbackRegistry.INSTANCE.wrapSystem(id, callback, false) +} + +export function disposeCallback(id: int32) { + CallbackRegistry.INSTANCE.dispose(id) +} + +export function callCallback(id: int32, args: KUint8ArrayPtr, length: int32): int32 { + return CallbackRegistry.INSTANCE.call(id, args, length) +} diff --git a/koala-wrapper/koalaui/interop/src/arkts/index.sts b/koala-wrapper/koalaui/interop/src/arkts/index.sts new file mode 100644 index 000000000..b57068080 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/index.sts @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022-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. + */ + +export * from "./InteropTypes" +export * from "./callback" +export * from "./buffer" +export * from "./ResourceManager" +export * from "./NativeBuffer" +export * from "./InteropNativeModule" +export * from "./SerializerBase" +export * from "./DeserializerBase" +export * from "./Finalizable" +export * from "./loadLibraries" +export * from "./MaterializedBase" diff --git a/koala-wrapper/koalaui/interop/src/arkts/loadLibraries.sts b/koala-wrapper/koalaui/interop/src/arkts/loadLibraries.sts new file mode 100644 index 000000000..1db028d2e --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/arkts/loadLibraries.sts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022-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. + */ + +const nativeModuleLibraries: Map = new Map() + +export function loadNativeLibrary(library: string) { + loadLibrary(library) +} + +export function registerNativeModuleLibraryName(nativeModule: string, libraryName: string) { + nativeModuleLibraries.set(nativeModule, libraryName) +} + +export function loadNativeModuleLibrary(nativeModule: string) { + loadLibrary(nativeModuleLibraries.get(nativeModule) ?? nativeModule) +} diff --git a/koala-wrapper/koalaui/interop/src/cangjie/DeserializerBase.cj b/koala-wrapper/koalaui/interop/src/cangjie/DeserializerBase.cj new file mode 100644 index 000000000..0e3e2d449 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cangjie/DeserializerBase.cj @@ -0,0 +1,134 @@ +/* + * 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. + */ +package Interop + +import std.binary.* +import std.collection.* + +public class CallbackResource { + public var resourceId: Int32 + public var hold: pointer + public var release: pointer + init(resourceId: Int32, hold: pointer, release: pointer) { + this.resourceId = resourceId + this.hold = hold + this.release = release + } +} + +public open class DeserializerBase { + private var position = 0 + private var length = 96 + private var buffer: Array + + public init(buffer: Array, length: Int64) { + this.buffer = buffer + this.length = length + } + + public func asArray(position: Int64, length: Int64): ArrayList { + return ArrayList() + } + + public func currentPosition(): Int64 { + return this.position + } + + public func resetCurrentPosition(): Unit { + this.position = 0 + } + + private func checkCapacity(value: Int64) { + if (value > this.length) { + throw Exception("${value} is less than remaining buffer length") + } + } + + public func readInt8(): Int8 { + this.checkCapacity(1) + let res = Int8.readLittleEndian(this.buffer[this.position..this.position+1]) + this.position += 1 + return res + } + + public func readInt32(): Int32 { + this.checkCapacity(4) + let res = Int32.readLittleEndian(this.buffer[this.position..this.position+4]) + this.position += 4 + return res + } + + public func readInt64(): Int64 { + this.checkCapacity(8) + let res = Int64.readLittleEndian(this.buffer[this.position..this.position+8]) + this.position += 8 + return res + } + + public func readPointer(): KPointer { + this.checkCapacity(8) + let res = UInt64.readLittleEndian(this.buffer[this.position..this.position+8]) + this.position += 8 + return res + } + + public func readFloat32(): Float32 { + this.checkCapacity(4) + let res = Float32.readLittleEndian(this.buffer[this.position..this.position+4]) + this.position += 4 + return res + } + + public func readBoolean(): Bool { + let res = Bool.readLittleEndian(this.buffer[this.position..this.position+1]) + this.position += 1 + return res + } + + // readMaterialized(): object { + // const ptr = this.readPointer() + // return { ptr: ptr } + // } + + public func readString(): String { + let length = Int64(this.readInt32()) + this.checkCapacity(length) + // read without null-terminated byte + let value = InteropNativeModule._Utf8ToString(this.buffer.toArray(), Int32(this.position), Int32(length)) + this.position += length + return value + } + + public func readCustomObject(kind: String): Object{ + throw Exception("readCustomObject") + } + + public func readNumber(): Float64 { + let tag = this.readInt8() + if (tag == Tag.UNDEFINED.value) { + throw Exception("Read number can't return undefined.") + } else if (tag == Tag.INT32.value) { + return Float64(this.readInt32()) + } else if (tag == Tag.FLOAT32.value) { + return Float64(this.readFloat32()) + } else { + throw Exception("Unknown number tag: ${tag}") + } + } + + public func readCallbackResource(): CallbackResource { + return CallbackResource(this.readInt32(), this.readPointer(), this.readPointer()) + } +} diff --git a/koala-wrapper/koalaui/interop/src/cangjie/Finalizable.cj b/koala-wrapper/koalaui/interop/src/cangjie/Finalizable.cj new file mode 100644 index 000000000..b5ac709d4 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cangjie/Finalizable.cj @@ -0,0 +1,33 @@ +/* + * 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. + */ +package Interop + +public open class Finalizable { + public var ptr: KPointer + public var finalizer: KPointer + + public Finalizable(ptr: KPointer, finalizer: KPointer) { + this.ptr = ptr + this.finalizer = finalizer + } +} + +public abstract class MaterializedBase { + public var peer: Option = Option.None + + public func getPeer(): ?Finalizable { + return this.peer + } +} diff --git a/koala-wrapper/koalaui/interop/src/cangjie/InteropNativeModule.cj b/koala-wrapper/koalaui/interop/src/cangjie/InteropNativeModule.cj new file mode 100644 index 000000000..5d4617498 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cangjie/InteropNativeModule.cj @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2024-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. + */ + +package Interop + +import std.collection.* + +foreign { + func CheckCallbackEvent(buffer: CPointer, bufferLength: Int32): Int32 + + func GetGroupedLog(index: Int32): UInt64 + func StartGroupedLog(index: Int32): Unit + func StopGroupedLog(index: Int32): Unit + func AppendGroupedLog(index: Int32, message: CString): Unit + func PrintGroupedLog(index: Int32): Unit + func GetStringFinalizer(): UInt64 + func InvokeFinalizer(ptr1: UInt64, ptr2: UInt64): Unit + func GetPtrVectorElement(ptr1: UInt64, arg: Int32): UInt64 + func StringLength(ptr1: UInt64): Int32 + func StringData(ptr1: UInt64, arr: CPointer, i: Int32): Unit + func StringMake(str1: CString): UInt64 + func GetPtrVectorSize(ptr1: UInt64): Int32 + func ManagedStringWrite(str1: CString, arr: CPointer, arg: Int32): Int32 + func NativeLog(str1: CString): Unit + func Utf8ToString(data: CPointer, offset: Int32, length: Int32): CString + func StdStringToString(cstring: UInt64): CString + func CallCallback(callbackKind: Int32, args: CPointer, argsSize: Int32): Unit + func CallCallbackSync(callbackKind: Int32, args: CPointer, argsSize: Int32): Unit + func CallCallbackResourceHolder(holder: UInt64, resourceId: Int32): Unit + func CallCallbackResourceReleaser(releaser: UInt64, resourceId: Int32): Unit + func LoadVirtualMachine(arg0: Int32, arg1: CString, arg2: CString): Int32 + func RunApplication(arg0: Int32, arg1: Int32): Bool + func StartApplication(appUrl: CString, appParams: CString): UInt64 + func EmitEvent(eventType: Int32, target: Int32, arg0: Int32, arg1: Int32): Unit +} + +public open class InteropNativeModule { + public static func _CheckCallbackEvent(buffer: Array, bufferLength: Int32): Int32 { + unsafe { + let handle_0 = acquireArrayRawData(buffer) + let result = CheckCallbackEvent(handle_0.pointer, bufferLength) + releaseArrayRawData(handle_0); + return result + } + } + public static func _GetGroupedLog(index: Int32): UInt64 { + unsafe { + let result = GetGroupedLog(index) + return result + } + } + public static func _StartGroupedLog(index: Int32): Unit { + unsafe { + StartGroupedLog(index) + } + } + public static func _StopGroupedLog(index: Int32): Unit { + unsafe { + StopGroupedLog(index) + } + } + public static func _AppendGroupedLog(index: Int32, message: String): Unit { + unsafe { + let message = LibC.mallocCString(message) + AppendGroupedLog(index, message) + LibC.free(message) + } + } + public static func _PrintGroupedLog(index: Int32): Unit { + unsafe { + PrintGroupedLog(index) + } + } + public static func _GetStringFinalizer(): UInt64 { + unsafe { + let result = GetStringFinalizer() + return result + } + } + public static func _InvokeFinalizer(ptr1: UInt64, ptr2: UInt64): Unit { + unsafe { + InvokeFinalizer(ptr1, ptr2) + } + } + public static func _GetPtrVectorElement(ptr1: UInt64, arg: Int32): UInt64 { + unsafe { + let result = GetPtrVectorElement(ptr1, arg) + return result + } + } + public static func _StringLength(ptr1: UInt64): Int32 { + unsafe { + let result = StringLength(ptr1) + return result + } + } + public static func _StringData(ptr1: UInt64, arr: ArrayList, i: Int32): Unit { + unsafe { + let handle_1 = acquireArrayRawData(arr.toArray()) + StringData(ptr1, handle_1.pointer, i) + releaseArrayRawData(handle_1) + } + } + public static func _StringMake(str1: String): UInt64 { + unsafe { + let str1 = LibC.mallocCString(str1) + let result = StringMake(str1) + LibC.free(str1) + return result + } + } + public static func _GetPtrVectorSize(ptr1: UInt64): Int32 { + unsafe { + let result = GetPtrVectorSize(ptr1) + return result + } + } + public static func _ManagedStringWrite(str1: String, arr: ArrayList, arg: Int32): Int32 { + unsafe { + let str1 = LibC.mallocCString(str1) + let handle_1 = acquireArrayRawData(arr.toArray()) + let result = ManagedStringWrite(str1, handle_1.pointer, arg) + LibC.free(str1) + releaseArrayRawData(handle_1) + return result + } + } + public static func _NativeLog(str1: String): Unit { + unsafe { + let str1 = LibC.mallocCString(str1) + NativeLog(str1) + LibC.free(str1) + } + } + public static func _Utf8ToString(data: Array, offset: Int32, length: Int32): String { + unsafe { + let handle_0 = acquireArrayRawData(data) + let result = Utf8ToString(handle_0.pointer, offset, length) + releaseArrayRawData(handle_0) + return result.toString() + } + } + public static func _StdStringToString(cstring: UInt64): String { + unsafe { + let result = StdStringToString(cstring) + return result.toString() + } + } + public static func _CallCallback(callbackKind: Int32, args: ArrayList, argsSize: Int32): Unit { + unsafe { + let handle_1 = acquireArrayRawData(args.toArray()) + CallCallback(callbackKind, handle_1.pointer, argsSize) + releaseArrayRawData(handle_1) + } + } + public static func _CallCallbackSync(callbackKind: Int32, args: ArrayList, argsSize: Int32): Unit { + unsafe { + let handle_1 = acquireArrayRawData(args.toArray()) + CallCallbackSync(callbackKind, handle_1.pointer, argsSize) + releaseArrayRawData(handle_1) + } + } + public static func _CallCallbackResourceHolder(holder: UInt64, resourceId: Int32): Unit { + unsafe { + CallCallbackResourceHolder(holder, resourceId) + } + } + public static func _CallCallbackResourceReleaser(releaser: UInt64, resourceId: Int32): Unit { + unsafe { + CallCallbackResourceReleaser(releaser, resourceId) + } + } + public static func _LoadVirtualMachine(arg0: Int32, arg1: String, arg2: String): Int32 { + unsafe { + let arg1 = LibC.mallocCString(arg1) + let arg2 = LibC.mallocCString(arg2) + let result = LoadVirtualMachine(arg0, arg1, arg2) + LibC.free(arg1) + LibC.free(arg1) + return result + } + } + public static func _RunApplication(arg0: Int32, arg1: Int32): Bool { + unsafe { + let result = RunApplication(arg0, arg1) + return result + } + } + public static func _StartApplication(appUrl: String, appParams: String): UInt64 { + unsafe { + let appUrl = LibC.mallocCString(appUrl) + let appParams = LibC.mallocCString(appParams) + let result = StartApplication(appUrl, appParams) + LibC.free(appUrl) + LibC.free(appUrl) + return result + } + } + public static func _EmitEvent(eventType: Int32, target: Int32, arg0: Int32, arg1: Int32): Unit { + unsafe { + EmitEvent(eventType, target, arg0, arg1) + } + } + public static func _StringData(ptr: KPointer, data: Array, arg2: Int32): Unit { + unsafe { + let handle_1 = acquireArrayRawData(data) + StringData(ptr, handle_1.pointer, arg2) + releaseArrayRawData(handle_1) + } + } +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cangjie/InteropTypes.cj b/koala-wrapper/koalaui/interop/src/cangjie/InteropTypes.cj new file mode 100644 index 000000000..2e2895609 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cangjie/InteropTypes.cj @@ -0,0 +1,24 @@ +/* + * 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. + */ +package Interop + +import std.collection.* + +public type KPointer = UInt64 +public type KFloat = Float32 +public type pointer = KPointer +public type KInt = Int32 +public type KStringPtr = String +public type ArrayBuffer = ArrayList \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cangjie/ResourceManager.cj b/koala-wrapper/koalaui/interop/src/cangjie/ResourceManager.cj new file mode 100644 index 000000000..61d207889 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cangjie/ResourceManager.cj @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022-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. + */ +package Interop + +import std.binary.* +import std.math.* +import std.collection.* + +public type ResourceId = Int32 + +class ResourceInfo { + public var resource: Any + public var holdersCount: Int32 + init(resource: Any, holdersCount: Int32 ) { + this.resource = resource + this.holdersCount = holdersCount + } +} + +public class ResourceHolder { + private static var nextResourceId: ResourceId = 100 + private var resources: HashMap = HashMap() + private static var _instance: ?ResourceHolder = Option.None + public static func instance(): ResourceHolder { + ResourceHolder._instance = match (ResourceHolder._instance) { + case Some(resourceHolder) => resourceHolder + case _ => ResourceHolder() + } + if (let Some(rh) <- ResourceHolder._instance) { + return rh + } else { + throw Exception() + } + } + public func hold(resourceId: ResourceId) { + match(this.resources.get(resourceId)) { + case Some(resource) => resource.holdersCount++ + case _ => throw Exception("Resource ${resourceId} does not exists, can not hold") + } + } + + public func release(resourceId: ResourceId) { + let resource = match (this.resources.get(resourceId)) { + case Some(resource) => resource + case _ => throw Exception("Resource ${resourceId} does not exists, can not hold") + } + resource.holdersCount-- + if (resource.holdersCount <= 0) { + this.resources.remove(resourceId) + } + } + + public func registerAndHold(resource: Any): ResourceId { + ResourceHolder.nextResourceId += 1 + let resourceId = ResourceHolder.nextResourceId + this.resources.add(resourceId, ResourceInfo(resource, resourceId)) + return resourceId + } + + public func get(resourceId: ResourceId): Any { + match(this.resources.get(resourceId)) { + case Some(resource) => return resource.resource + case _ => throw Exception("Resource ${resourceId} does not exists") + } + } +} diff --git a/koala-wrapper/koalaui/interop/src/cangjie/SerializerBase.cj b/koala-wrapper/koalaui/interop/src/cangjie/SerializerBase.cj new file mode 100644 index 000000000..526e566d6 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cangjie/SerializerBase.cj @@ -0,0 +1,262 @@ +/* + * 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. + */ + +package Interop + +import std.binary.* +import std.math.* +import std.reflect.* +import std.collection.* + +public enum RuntimeType { + |UNEXPECTED + |NUMBER + |STRING + |OBJECT + |BOOLEAN + |UNDEFINED + |BIGINT + |FUNCTION + |SYMBOL + |MATERIALIZED + public prop ordinal: Int32 { + get() { + match (this) { + case UNEXPECTED => -1 + case NUMBER => 1 + case STRING => 2 + case OBJECT => 3 + case BOOLEAN => 4 + case UNDEFINED => 5 + case BIGINT => 6 + case FUNCTION => 7 + case SYMBOL => 8 + case MATERIALIZED => 9 + } + } + } +} + + +/* Serialization extension point */ +public abstract class CustomSerializer { + public var supported: Array + init(supported: Array) { + this.supported = supported + } + public func supports(kind: String): Bool { return this.supported.contains(kind) } + public func serialize(serializer: SerializerBase, value: Object, kind: String): Unit {} + var next: ?CustomSerializer = Option.None +} + +public open class SerializerBase { + protected var isHolding: Bool = false + private var position: Int64 = 0 + private var buffer: ArrayList = ArrayList() + + private static var customSerializers: ?CustomSerializer = Option.None + static func registerCustomSerializer(serializer: CustomSerializer) { + //TODO + } + + public init() { + this.buffer = ArrayList(Array(96, repeat: UInt8(0))) + } + public open func release() { + this.isHolding = false + // todo handle release resources + this.position = 0 + } + public func asArray(): ArrayList { + return this.buffer + } + public func length(): Int32 { + return Int32(this.position) + } + public func currentPosition(): Int64 { return this.position } + private func checkCapacity(value: Int64) { + if (value < 1) { + throw Exception("${value} is less than 1") + } + var buffSize = this.buffer.size + if (this.position > buffSize - value) { + let minSize = this.position + value + let resizedSize = max(minSize, Int64(round(3.0 * Float64(buffSize) / 2.0))) + var resizedBuffer = ArrayList(this.buffer) + while (resizedBuffer.size < resizedSize) { + resizedBuffer.add(0) + } + this.buffer = resizedBuffer + } + } + public func writeCustomObject(kind: String, value: Any): Unit { + var current = SerializerBase.customSerializers + // TODO + println("Unsupported custom serialization for ${kind}, write undefined") + this.writeInt8(Tag.UNDEFINED.value) + } + private var heldResources: ArrayList = ArrayList() + public func holdAndWriteCallback(callback: Any): ResourceId { + let resourceId = ResourceHolder.instance().registerAndHold(callback) + this.heldResources.add(resourceId) + this.writeInt32(resourceId) + this.writePointer(0) + this.writePointer(0) + this.writePointer(0) + this.writePointer(0) + return resourceId + } + public func holdAndWriteCallback(callback: Any, hold: KPointer, release: KPointer, call: KPointer, callSync: KPointer): ResourceId { + let resourceId = ResourceHolder.instance().registerAndHold(callback) + this.heldResources.add(resourceId) + this.writeInt32(resourceId) + this.writePointer(hold) + this.writePointer(release) + this.writePointer(call) + this.writePointer(callSync) + return resourceId + } + public func writeFunction(value: Any): Unit { + // TODO + } + private func setBytes(position: Int64, value: T): Unit where T <: LittleEndianOrder{ + var arr = Array(100, repeat: 0) + let n = value.writeLittleEndian(arr) + this.checkCapacity(n) + for (i in 0..n) { + this.buffer[this.position + i] = arr[i] + } + this.position += n + } + public func writeTag(tag: Int32): Unit { + this.setBytes(this.position, tag) + } + public func writeNumber(value: ?Float32): Unit { + if (let Some(value) <- value) { + if(value == Float32(Int32(value))) { + this.writeNumber(Int32(value)) + } else { + this.setBytes(this.position, Tag.FLOAT32.value) + this.setBytes(this.position, value) + } + } + else { + this.buffer[Int64(this.position)] = UInt8(RuntimeType.UNDEFINED.ordinal) + this.position++ + } + } + public func writeNumber(value: ?Float64): Unit { + if (let Some(value) <- value) { + if(value == Float64(Int32(value))) { + this.writeNumber(Int32(value)) + } else { + this.setBytes(this.position, Tag.FLOAT32.value) + this.setBytes(this.position, Float32(value)) + } + } + else { + this.buffer[Int64(this.position)] = UInt8(RuntimeType.UNDEFINED.ordinal) + this.position++ + } + } + public func writeNumber(value: ?Int32): Unit { + if (let Some(value) <- value) { + this.setBytes(this.position, Tag.INT32.value) + this.setBytes(this.position, value) + } + else { + this.buffer[Int64(this.position)] = UInt8(RuntimeType.UNDEFINED.ordinal) + this.position++ + } + } + public func writeNumber(value: ?Int64): Unit { + if (let Some(value) <- value) { + this.setBytes(this.position, Tag.INT32.value) + this.setBytes(this.position, Int32(value)) + } + else { + this.buffer[Int64(this.position)] = UInt8(RuntimeType.UNDEFINED.ordinal) + this.position++ + } + } + public func writeInt8(value: Int8): Unit { + this.setBytes(this.position, value) + } + public func writeInt8(value: Int32): Unit { + this.setBytes(this.position, Int8(value)) + } + public func writeInt32(value: Int32): Unit { + this.setBytes(this.position, Int32(value)) + } + public func writeInt64(value: Int64): Unit { + this.setBytes(this.position, Int64(value)) + } + public func writeFloat32(value: Float32): Unit { + this.setBytes(this.position, value) + } + public func writePointer(ptr: UInt64): Unit { + this.setBytes(this.position, ptr) + } + public func writeBoolean(value: ?Bool): Unit { + this.checkCapacity(1) + if(let Some(value) <- value) { + this.setBytes(this.position, value) + } + else { + this.buffer[Int64(this.position)] = UInt8(RuntimeType.UNDEFINED.ordinal) + this.position++ + } + } + public func writeMaterialized(value: Object): Unit { + // TODO + } + public func writeCallbackResource(resource: CallbackResource) { + this.writeInt32(resource.resourceId) + this.writePointer(resource.hold) + this.writePointer(resource.release) + } + public func writeString(value: String): Unit { + this.checkCapacity(4 + value.size * 4 + 1) // length, data + this.writeInt32(Int32(value.size + 1)) + for (i in 0..value.size) { + this.setBytes(this.position, value[i]) + } + this.writeInt8(Int8(0)) + } + public func writeBuffer(buffer: Array) { + let resourceId = ResourceHolder.instance().registerAndHold(buffer) + this.writeCallbackResource(CallbackResource(resourceId, 0, 0)) + unsafe { + let ptr = acquireArrayRawData(buffer).pointer + this.writePointer(UInt64(ptr.toUIntNative())) + this.writeInt64(buffer.size) + } + } +} + +public open class DateCustomSerializer <: CustomSerializer { + public DateCustomSerializer() { + super(["Date"]) + } + public func serialize(serializer: SerializerBase, value: Ark_CustomObject, kind: String): Unit { + serializer.writeString("{}") + } +} + +public open class Ark_CustomObject { + init() { + SerializerBase.registerCustomSerializer(DateCustomSerializer()) + } +} diff --git a/koala-wrapper/koalaui/interop/src/cangjie/Tag.cj b/koala-wrapper/koalaui/interop/src/cangjie/Tag.cj new file mode 100644 index 000000000..621a1fd57 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cangjie/Tag.cj @@ -0,0 +1,29 @@ +/* + * 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. + */ +package Interop + +public open class Tag { + public static var UNDEFINED: Tag = Tag(101) + public static var INT32: Tag = Tag(102) + public static var FLOAT32: Tag = Tag(103) + public static var STRING: Tag = Tag(104) + public static var LENGTH: Tag = Tag(105) + public static var RESOURCE: Tag = Tag(106) + public static var OBJECT: Tag = Tag(107) + public var value: Int8 + Tag (arg0: Int8) { + value = arg0 + } +} diff --git a/koala-wrapper/koalaui/interop/src/cangjie/cjpm.toml b/koala-wrapper/koalaui/interop/src/cangjie/cjpm.toml new file mode 100644 index 000000000..d29229886 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cangjie/cjpm.toml @@ -0,0 +1,12 @@ +[dependencies] +[package] + cjc-version = "0.56.4" + compile-option = "" + description = "config file for cj build" + link-option = "" + name = "Interop" + output-type = "static" + src-dir = "." + target-dir = "./build/cj" + version = "1.0.0" + package-configuration = {} diff --git a/koala-wrapper/koalaui/interop/src/cpp/DeserializerBase.h b/koala-wrapper/koalaui/interop/src/cpp/DeserializerBase.h new file mode 100644 index 000000000..e09c40524 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/DeserializerBase.h @@ -0,0 +1,650 @@ +/* + * 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 _DESERIALIZER_BASE_H_ +#define _DESERIALIZER_BASE_H_ + +#include +#include +#include +#include +#include +#include + +#include "interop-types.h" +#include "interop-logging.h" + +void holdManagedCallbackResource(InteropInt32); +void releaseManagedCallbackResource(InteropInt32); + +#ifdef __arm__ +#define KOALA_NO_UNALIGNED_ACCESS 1 +#endif + +inline const char *tagName(InteropTag tag) +{ + switch (tag) + { + case InteropTag::INTEROP_TAG_UNDEFINED: + return "UNDEFINED"; + case InteropTag::INTEROP_TAG_INT32: + return "INT32"; + case InteropTag::INTEROP_TAG_FLOAT32: + return "FLOAT32"; + case InteropTag::INTEROP_TAG_LENGTH: + return "LENGTH"; + case InteropTag::INTEROP_TAG_RESOURCE: + return "RESOURCE"; + case InteropTag::INTEROP_TAG_STRING: + return "STRING"; + case InteropTag::INTEROP_TAG_OBJECT: + return "OBJECT"; + } + INTEROP_FATAL("Fatal error"); +} + +inline const char *tagNameExact(InteropTag tag) +{ + switch (tag) + { + case InteropTag::INTEROP_TAG_UNDEFINED: + return "INTEROP_TAG_UNDEFINED"; + case InteropTag::INTEROP_TAG_INT32: + return "INTEROP_TAG_INT32"; + case InteropTag::INTEROP_TAG_FLOAT32: + return "INTEROP_TAG_FLOAT32"; + case InteropTag::INTEROP_TAG_LENGTH: + return "INTEROP_TAG_LENGTH"; + case InteropTag::INTEROP_TAG_RESOURCE: + return "INTEROP_TAG_RESOURCE"; + case InteropTag::INTEROP_TAG_STRING: + return "INTEROP_TAG_STRING"; + case InteropTag::INTEROP_TAG_OBJECT: + return "INTEROP_TAG_OBJECT"; + } + INTEROP_FATAL("Fatal error"); +} + +inline InteropFunction makeArkFunctionFromId(InteropInt32 id) { + InteropFunction result; + result.id = id; + return result; +} + +inline const char *getUnitName(int value) +{ + switch (value) + { + case 0: + return "px"; + case 1: + return "vp"; + case 2: + return "fp"; + case 3: + return "%"; + case 4: + return "lpx"; + default: + return ""; + } +} + +inline void parseDimension(const InteropString &string, InteropLength *result) +{ + char *suffixPtr = nullptr; + float value = std::strtof(string.chars, &suffixPtr); + + if (!suffixPtr || suffixPtr == string.chars) + { + // not a numeric value + result->unit = -1; + return; + } + result->value = value; + if (suffixPtr[0] == '\0' || (suffixPtr[0] == 'v' && suffixPtr[1] == 'p')) + { + result->unit = 1; + } + else if (suffixPtr[0] == '%') + { + result->unit = 3; + } + else if (suffixPtr[0] == 'p' && suffixPtr[1] == 'x') + { + result->unit = 0; + } + else if (suffixPtr[0] == 'l' && suffixPtr[1] == 'p' && suffixPtr[2] == 'x') + { + result->unit = 4; + } + else if (suffixPtr[0] == 'f' && suffixPtr[1] == 'p') + { + result->unit = 2; + } + else + { + result->unit = -1; + } +} + +template +inline void convertor(T value) = delete; + +// TODO: restore full printing! +template +inline void WriteToString(std::string *result, T value) = delete; + +template <> +inline void WriteToString(std::string *result, const InteropEmpty &value) +{ + result->append("{"); + result->append(".dummy=" + std::to_string(value.dummy)); + result->append("}"); +} + +struct Error +{ + std::string message; + Error(const std::string &message) : message(message) {} +}; + +template <> +inline void WriteToString(std::string *result, InteropTag value) +{ + result->append(".tag="); + result->append(tagName(value)); +} + +template <> +inline void WriteToString(std::string *result, InteropNativePointer value) +{ + result->append("0x" + std::to_string((uint64_t)value)); +} + +template <> +inline void WriteToString(std::string *result, InteropNodeHandle value) +{ + result->append("0x" + std::to_string((uint64_t)value)); +} + +template <> +inline void WriteToString(std::string *result, InteropFunction value) +{ + result->append("{"); + result->append(".id=" + std::to_string(value.id)); + result->append("}"); +} + +template <> +inline void WriteToString(std::string *result, const InteropFunction* value) +{ + result->append("{"); + result->append(".id=" + std::to_string(value->id)); + result->append("}"); +} + +template <> +inline void WriteToString(std::string *result, const InteropMaterialized *value) +{ + char hex[20]; + std::snprintf(hex, sizeof(hex), "0x%llx", (long long)value->ptr); + result->append("\""); + result->append("Materialized "); + result->append(hex); + result->append("\""); +} + +// TODO: generate! +template<> +inline void WriteToString(std::string *result, const InteropCallbackResource *value) +{ + result->append("{"); + result->append(".resourceId=" + std::to_string(value->resourceId)); + result->append(", .hold=0"); + result->append(", .release=0"); + result->append("}"); +} + +class DeserializerBase; + +template <> +inline void WriteToString(std::string *result, InteropUndefined value) +{ + result->append("{}"); +} +template <> +inline void WriteToString(std::string *result, const InteropUndefined *value) +{ + result->append("{}"); +} +template <> +inline void WriteToString(std::string *result, InteropVoid value) +{ + result->append("{}"); +} +template <> +inline void WriteToString(std::string *result, const InteropVoid *value) +{ + result->append("{}"); +} +template <> +inline void WriteToString(std::string *result, const InteropCustomObject *value) +{ + if (strcmp(value->kind, "NativeErrorFunction") == 0) + { + result->append("() => {} /* TBD: Function*/"); + return; + } + result->append("{"); + result->append(".kind=\""); + result->append(value->kind); + result->append("\"}"); +} + +struct CustomDeserializer +{ + virtual ~CustomDeserializer() {} + virtual bool supports(const std::string &kind) { return false; } + virtual InteropCustomObject deserialize(DeserializerBase *deserializer, const std::string &kind) + { + InteropCustomObject result; + strcpy(result.kind, "error"); + return result; + } + CustomDeserializer *next = nullptr; +}; + +class DeserializerBase +{ +protected: + uint8_t *data; + int32_t length; + int32_t position; + std::vector toClean; + + static CustomDeserializer *customDeserializers; + +public: + DeserializerBase(uint8_t *data, int32_t length) + : data(data), length(length), position(0) {} + + ~DeserializerBase() + { + for (auto data : toClean) + { + free(data); + } + } + + static void registerCustomDeserializer(CustomDeserializer *deserializer) + { + if (DeserializerBase::customDeserializers == nullptr) + { + DeserializerBase::customDeserializers = deserializer; + } + else + { + auto *current = DeserializerBase::customDeserializers; + while (current->next != nullptr) + current = current->next; + current->next = deserializer; + } + } + + template + void resizeArray(T *array, int32_t length) + { + void *value = nullptr; + if (length > 0) + { + value = malloc(length * sizeof(E)); + memset(value, 0, length * sizeof(E)); + toClean.push_back(value); + } + array->length = length; + array->array = reinterpret_cast(value); + } + + template + void resizeMap(T *map, int32_t length) + { + void *keys = nullptr; + void *values = nullptr; + if (length > 0) + { + keys = malloc(length * sizeof(K)); + memset(keys, 0, length * sizeof(K)); + toClean.push_back(keys); + + values = malloc(length * sizeof(V)); + memset(values, 0, length * sizeof(V)); + toClean.push_back(values); + } + map->size = length; + map->keys = reinterpret_cast(keys); + map->values = reinterpret_cast(values); + } + + int32_t currentPosition() const { return this->position; } + + void check(int32_t count) + { + if (position + count > length) { + fprintf(stderr, "Incorrect serialized data, check for %d, buffer %d position %d\n", count, length, position); + assert(false); + abort(); + } + } + + InteropCustomObject readCustomObject(std::string kind) + { + auto *current = DeserializerBase::customDeserializers; + while (current) + { + if (current->supports(kind)) + return current->deserialize(this, kind); + current = current->next; + } + LOGE("Unsupported custom deserialization for %s\n", kind.c_str()); + auto tag = readTag(); + if (tag == INTEROP_TAG_UNDEFINED) LOGE("Undefined interop tag"); + // Skip undefined tag!. + InteropCustomObject result; + strcpy(result.kind, "Error"); + strcat(result.kind, kind.c_str()); + return result; + } + + InteropCallbackResource readCallbackResource() { + InteropCallbackResource result = {}; + result.resourceId = readInt32(); + result.hold = reinterpret_cast(readPointerOrDefault(reinterpret_cast(holdManagedCallbackResource))); + result.release = reinterpret_cast(readPointerOrDefault(reinterpret_cast(releaseManagedCallbackResource))); + return result; + } + + int8_t readInt8() + { + check(1); + int8_t value = *(data + position); + position += 1; + return value; + } + InteropTag readTag() + { + return (InteropTag)readInt8(); + } + InteropBoolean readBoolean() + { + check(1); + int8_t value = *(data + position); + position += 1; + return value; + } + InteropInt32 readInt32() + { + check(4); +#ifdef KOALA_NO_UNALIGNED_ACCESS + InteropInt32 value; + memcpy(&value, data + position, 4); +#else + auto value = *(InteropInt32 *)(data + position); +#endif + position += 4; + return value; + } + InteropInt64 readInt64() + { + check(8); +#ifdef KOALA_NO_UNALIGNED_ACCESS + InteropInt64 value; + memcpy(&value, data + position, 4); +#else + auto value = *(InteropInt64 *)(data + position); +#endif + position += 8; + return value; + } + InteropUInt64 readUInt64() + { + check(8); +#ifdef KOALA_NO_UNALIGNED_ACCESS + InteropInt64 value; + memcpy(&value, data + position, 4); +#else + auto value = *(InteropUInt64 *)(data + position); +#endif + position += 8; + return value; + } + InteropFloat32 readFloat32() + { + check(4); +#ifdef KOALA_NO_UNALIGNED_ACCESS + InteropFloat32 value; + memcpy(&value, data + position, 4); +#else + auto value = *(InteropFloat32 *)(data + position); +#endif + position += 4; + return value; + } + InteropNativePointer readPointer() + { + check(8); +#ifdef KOALA_NO_UNALIGNED_ACCESS + int64_t value = 0; + memcpy(&value, data + position, 8); +#else + int64_t value = *(int64_t *)(data + position); +#endif + position += 8; + return reinterpret_cast(value); + } + InteropNativePointer readPointerOrDefault(InteropNativePointer defaultValue) + { + const InteropNativePointer value = this->readPointer(); + return value ? value : defaultValue; + } + InteropNumber readNumber() + { + check(5); + InteropNumber result; + result.tag = readTag(); + if (result.tag == InteropTag::INTEROP_TAG_INT32) + { + result.i32 = readInt32(); + } + else if (result.tag == InteropTag::INTEROP_TAG_FLOAT32) + { + result.f32 = readFloat32(); + } + else + { + INTEROP_FATAL("Fatal error"); + } + return result; + } + InteropBuffer readBuffer() + { + InteropCallbackResource resource = readCallbackResource(); + InteropNativePointer data = readPointer(); + InteropInt64 length = readInt64(); + return InteropBuffer { resource, (void*)data, length }; + } + + // TODO: produce them with prefix in generator. + InteropLength readLength() + { + InteropLength result = {}; + result.unit = 1; + result.type = readInt8(); + switch (result.type) + { + case INTEROP_RUNTIME_OBJECT: + { + result.resource = readInt32(); + break; + } + case INTEROP_RUNTIME_STRING: + { + InteropString string = readString(); + parseDimension(string, &result); + break; + } + case INTEROP_RUNTIME_NUMBER: + { + result.value = readFloat32(); + break; + } + default: + { + INTEROP_FATAL("Fatal error"); + } + } + return result; + } + + InteropString readString() + { + InteropString result; + InteropInt32 length = readInt32(); + check(length); + // We refer to string data in-place. + result.chars = (const char *)(data + position); + result.length = length - 1; + this->position += length; + return result; + } + + InteropFunction readFunction() + { + InteropFunction result; + result.id = readInt32(); + return result; + } + + InteropMaterialized readMaterialized() + { + InteropMaterialized result; + result.ptr = readPointer(); + return result; + } + + InteropUndefined readUndefined() + { + return InteropUndefined(); + } +}; +template <> +inline void WriteToString(std::string *result, InteropBoolean value) +{ + result->append(value ? "true" : "false"); +} +template <> +inline void WriteToString(std::string *result, InteropInt32 value) +{ + result->append(std::to_string(value)); +} +template <> +inline void WriteToString(std::string *result, const InteropInt32* value) +{ + result->append(std::to_string(*value)); +} +template <> +inline void WriteToString(std::string *result, InteropInt64 value) +{ + result->append(std::to_string(value)); +} +template <> +inline void WriteToString(std::string *result, InteropUInt32 value) +{ + result->append(std::to_string(value)); +} +template <> +inline void WriteToString(std::string *result, InteropFloat32 value) +{ +#if (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && (__MAC_OS_X_VERSION_MAX_ALLOWED < 130300L)) + // to_chars() is not available on older macOS. + char buf[20]; + snprintf(buf, sizeof buf, "%f", value); + result->append(buf); +#else + std::string storage; + storage.resize(20); + // We use to_chars() to avoid locale issues. + auto rc = std::to_chars(storage.data(), storage.data() + storage.size(), value); + storage.resize(rc.ptr - storage.data()); + result->append(storage); +#endif +} +template <> +inline void WriteToString(std::string* result, const InteropBuffer* value) { + result->append("{.data=nullptr, .length="); + result->append(std::to_string(value->length)); + result->append("}"); +} +template <> +inline void WriteToString(std::string* result, InteropBuffer value) { + result->append("{.data=nullptr, .length="); + result->append(std::to_string(value.length)); + result->append("}"); +} +template <> +inline void WriteToString(std::string *result, const InteropString *value) +{ + result->append("{"); + if (value->chars) { + result->append(".chars=\""); + result->append(value->chars); + result->append("\""); + } else { + result->append(".chars=\"\""); + } + result->append(", .length="); + WriteToString(result, value->length); + result->append("}"); +} + +template <> +inline void WriteToString(std::string *result, const InteropNumber *value) +{ + result->append("{.tag=" + std::to_string(value->tag) + ", "); + + if (value->tag == INTEROP_TAG_FLOAT32) + { + std::string valueString; + result->append(".f32="); + WriteToString(result, value->f32); + } else { + result->append(".i32=" + std::to_string(value->i32)); + } + + result->append("}"); +} + +template <> +inline void WriteToString(std::string *result, const InteropLength *value) +{ + result->append("{"); + result->append(".type=" + std::to_string(value->type)); + result->append(", .value="); + WriteToString(result, value->value); + result->append(", .unit=" + std::to_string(value->unit)); + result->append(", .resource=" + std::to_string(value->resource)); + result->append("}"); +} + +#endif // _DESERIALIZER_BASE_H_ diff --git a/koala-wrapper/koalaui/interop/src/cpp/SerializerBase.h b/koala-wrapper/koalaui/interop/src/cpp/SerializerBase.h new file mode 100644 index 000000000..f6cce0fae --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/SerializerBase.h @@ -0,0 +1,264 @@ +/* + * 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 _SERIALIZER_BASE_H +#define _SERIALIZER_BASE_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "callback-resource.h" +#include "interop-types.h" +#include "koala-types.h" + +#ifdef __arm__ +#define KOALA_NO_UNALIGNED_ACCESS 1 +#endif + +template +inline InteropRuntimeType runtimeType(const T& value) = delete; + +template <> +inline InteropRuntimeType runtimeType(const InteropCustomObject& value) { + return INTEROP_RUNTIME_OBJECT; +} + +template <> +inline InteropRuntimeType runtimeType(const InteropMaterialized& value) { + return INTEROP_RUNTIME_OBJECT; +} + +static const std::size_t buffer_size = 1024 * 1024; // 1 MB +static std::size_t offset = 0; +alignas(std::max_align_t) static char buffer[buffer_size]; + +template +T* allocArray(const std::array& ref) { + std::size_t space = sizeof(buffer) - offset; + void* ptr = buffer + offset; + void* aligned_ptr = std::align(alignof(T), sizeof(T) * size, ptr, space); + assert(aligned_ptr != nullptr && "Insufficient space or alignment failed!"); + offset = (char*)aligned_ptr + sizeof(T) * size - buffer; + T* array = reinterpret_cast(aligned_ptr); + for (size_t i = 0; i < size; ++i) { + new (&array[i]) T(ref[i]); + } + return array; +} + +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)); + memcpy(newData, data, position); + free(data); + data = newData; + } +public: + SerializerBase(CallbackResourceHolder* resourceHolder = nullptr): + position(0), ownData(true), resourceHolder(resourceHolder) { + this->dataLength = 256; + this->data = reinterpret_cast(malloc(this->dataLength)); + } + + SerializerBase(uint8_t* data, uint32_t dataLength, CallbackResourceHolder* resourceHolder = nullptr): + data(data), dataLength(dataLength), position(0), ownData(false), resourceHolder(resourceHolder) { + } + + virtual ~SerializerBase() { + if (ownData) { + free(data); + } + } + + SerializerBase(const SerializerBase&) = delete; + SerializerBase& operator=(const SerializerBase&) = delete; + + void* release() { + ownData = false; + return data; + } + int length() { + return position; + } + + inline void check(int more) { + if (position + more > dataLength) { + if (ownData) { + resize(dataLength * 3 / 2 + 2); + } else { + fprintf(stderr, "Buffer overrun: %d > %d\n", position + more, dataLength); + assert(false); + } + } + } + + void writeInt8(InteropInt8 value) { + check(1); + *((InteropInt8*)(data + position)) = value; + position += 1; + } + + void writeInt32(InteropInt32 value) { + check(4); +#ifdef KOALA_NO_UNALIGNED_ACCESS + memcpy(data + position, &value, 4); +#else + *((InteropInt32*)(data + position)) = value; +#endif + position += 4; + } + + void writeInt64(InteropInt64 value) { + check(8); +#ifdef KOALA_NO_UNALIGNED_ACCESS + memcpy(data + position, &value, 8); +#else + *((InteropInt64*)(data + position)) = value; +#endif + position += 8; + } + + void writeUInt64(InteropUInt64 value) { + check(8); +#ifdef KOALA_NO_UNALIGNED_ACCESS + memcpy(data + position, &value, 8); +#else + *((InteropUInt64*)(data + position)) = value; +#endif + position += 8; + } + + void writeFloat32(InteropFloat32 value) { + check(8); +#ifdef KOALA_NO_UNALIGNED_ACCESS + memcpy(data + position, &value, 4); +#else + *((InteropFloat32*)(data + position)) = value; +#endif + position += 4; + } + + void writePointer(InteropNativePointer value) { + check(8); +#ifdef KOALA_NO_UNALIGNED_ACCESS + memcpy(data + position, &value, 8); +#else + *((int64_t*)(data + position)) = reinterpret_cast(value); +#endif + position += 8; + } + + void writeFunction(InteropFunction value) { + // TODO: ignored, remove! + writeInt32(0x666); + } + + 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); + strcpy((char*)(data + position), value.chars); + position += value.length + 1; + } + + void writeBoolean(InteropBoolean value) { + writeInt8(value); + } + + void writeLength(InteropLength value) { + InteropRuntimeType tag = (InteropRuntimeType) value.type; + writeInt8(tag); + switch (tag) { + case INTEROP_RUNTIME_NUMBER: + writeFloat32(value.value); + break; + case INTEROP_RUNTIME_OBJECT: + writeInt32(value.resource); + break; + case INTEROP_RUNTIME_STRING: { + char buf[64]; + std::string suffix; + switch (value.unit) { + case 0: suffix = "px"; break; + case 1: suffix = "vp"; break; + case 2: suffix = "fp"; break; + case 3: suffix = "%"; break; + case 4: suffix = "lpx"; break; + } + snprintf(buf, 64, "%.8f%s", value.value, suffix.c_str()); + InteropString str = { buf, (InteropInt32) strlen(buf) }; + writeString(str); + break; + } + default: + break; + } + } + + 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 writeCustomObject(std::string type, InteropCustomObject value) { + // TODO implement + } + + void writeBuffer(InteropBuffer buffer) { + writeCallbackResource(buffer.resource); + writePointer((void*)buffer.data); + writeInt64(buffer.length); + } + + KInteropReturnBuffer toReturnBuffer() { + if (this->ownData) { + KInteropReturnBuffer buffer {this->length(), this->release(), [](KNativePointer data, KInt length) { free(data); }}; + // TODO fix memory issues + return buffer; + } else { + return {this->length(), this->data, nullptr}; + } + } +}; + +#endif // _SERIALIZER_BASE_H \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/ani/ani.h b/koala-wrapper/koalaui/interop/src/cpp/ani/ani.h new file mode 100644 index 000000000..3adbe2416 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ani/ani.h @@ -0,0 +1,9062 @@ +/** + * 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 __ANI_H__ +#define __ANI_H__ +// NOLINTBEGIN + +#ifdef __cplusplus +#include +#include +#include +#else +#include +#include +#include +#endif + +#define ANI_VERSION_1 1 + +#define ANI_FALSE 0 +#define ANI_TRUE 1 + +typedef size_t ani_size; + +// Primitive types: +typedef uint8_t ani_boolean; +typedef uint32_t ani_char; +typedef int8_t ani_byte; +typedef int16_t ani_short; +typedef int32_t ani_int; +typedef int64_t ani_long; +typedef float ani_float; +typedef double ani_double; + +// Reference types: +#ifdef __cplusplus +class __ani_ref {}; +class __ani_module : public __ani_ref {}; +class __ani_namespace : public __ani_ref {}; +class __ani_object : public __ani_ref {}; +class __ani_fn_object : public __ani_object {}; +class __ani_enum_value : public __ani_object {}; +class __ani_error : public __ani_object {}; +class __ani_promise : public __ani_object {}; +class __ani_tuple_value : public __ani_object {}; +class __ani_type : public __ani_object {}; +class __ani_arraybuffer : public __ani_object {}; +class __ani_string : public __ani_object {}; +class __ani_stringliteral : public __ani_string {}; +class __ani_class : public __ani_type {}; +class __ani_enum : public __ani_type {}; +class __ani_tuple : public __ani_type {}; +class __ani_fixedarray : public __ani_object {}; +class __ani_fixedarray_boolean : public __ani_fixedarray {}; +class __ani_fixedarray_char : public __ani_fixedarray {}; +class __ani_fixedarray_byte : public __ani_fixedarray {}; +class __ani_fixedarray_short : public __ani_fixedarray {}; +class __ani_fixedarray_int : public __ani_fixedarray {}; +class __ani_fixedarray_long : public __ani_fixedarray {}; +class __ani_fixedarray_float : public __ani_fixedarray {}; +class __ani_fixedarray_double : public __ani_fixedarray {}; +class __ani_fixedarray_ref : public __ani_fixedarray {}; +typedef __ani_ref *ani_ref; +typedef __ani_module *ani_module; +typedef __ani_namespace *ani_namespace; +typedef __ani_object *ani_object; +typedef __ani_fn_object *ani_fn_object; +typedef __ani_enum_value *ani_enum_value; +typedef __ani_error *ani_error; +typedef __ani_promise *ani_promise; +typedef __ani_tuple_value *ani_tuple_value; +typedef __ani_type *ani_type; +typedef __ani_arraybuffer *ani_arraybuffer; +typedef __ani_string *ani_string; +typedef __ani_stringliteral *ani_stringliteral; +typedef __ani_class *ani_class; +typedef __ani_enum *ani_enum; +typedef __ani_tuple *ani_tuple; +typedef __ani_fixedarray *ani_fixedarray; +typedef __ani_fixedarray_boolean *ani_fixedarray_boolean; +typedef __ani_fixedarray_char *ani_fixedarray_char; +typedef __ani_fixedarray_byte *ani_fixedarray_byte; +typedef __ani_fixedarray_short *ani_fixedarray_short; +typedef __ani_fixedarray_int *ani_fixedarray_int; +typedef __ani_fixedarray_long *ani_fixedarray_long; +typedef __ani_fixedarray_float *ani_fixedarray_float; +typedef __ani_fixedarray_double *ani_fixedarray_double; +typedef __ani_fixedarray_ref *ani_fixedarray_ref; +#else // __cplusplus +struct __ani_ref; +typedef struct __ani_ref *ani_ref; +typedef ani_ref ani_module; +typedef ani_ref ani_namespace; +typedef ani_ref ani_object; +typedef ani_object ani_fn_object; +typedef ani_object ani_enum_value; +typedef ani_object ani_error; +typedef ani_object ani_promise; +typedef ani_object ani_tuple_value; +typedef ani_object ani_type; +typedef ani_object ani_arraybuffer; +typedef ani_object ani_string; +typedef ani_string ani_stringliteral; +typedef ani_type ani_class; +typedef ani_type ani_enum; +typedef ani_type ani_tuple; +typedef ani_object ani_fixedarray; +typedef ani_fixedarray ani_fixedarray_boolean; +typedef ani_fixedarray ani_fixedarray_char; +typedef ani_fixedarray ani_fixedarray_byte; +typedef ani_fixedarray ani_fixedarray_short; +typedef ani_fixedarray ani_fixedarray_int; +typedef ani_fixedarray ani_fixedarray_long; +typedef ani_fixedarray ani_fixedarray_float; +typedef ani_fixedarray ani_fixedarray_double; +typedef ani_fixedarray ani_fixedarray_ref; +#endif // __cplusplus + +struct __ani_gref; +typedef struct __ani_gref *ani_gref; + +struct __ani_wref; +typedef struct __ani_wref *ani_wref; + +struct __ani_variable; +typedef struct __ani_variable *ani_variable; + +struct __ani_function; +typedef struct __ani_function *ani_function; + +struct __ani_field; +typedef struct __ani_field *ani_field; + +struct __ani_static_field; +typedef struct __ani_satic_field *ani_static_field; + +struct __ani_property; +typedef struct __ani_property *ani_property; + +struct __ani_method; +typedef struct __ani_method *ani_method; + +struct __ani_static_method; +typedef struct __ani_static_method *ani_static_method; + +struct __ani_cls_slot; +typedef struct __ani_cls_slot *ani_cls_slot; + +typedef void (*ani_finalizer)(void *data, void *hint); + +typedef enum { + ANI_KIND_BOOLEAN, + ANI_KIND_CHAR, + ANI_KIND_BYTE, + ANI_KIND_SHORT, + ANI_KIND_INT, + ANI_KIND_LONG, + ANI_KIND_FLOAT, + ANI_KIND_DOUBLE, + ANI_KIND_REF, +} ani_kind; + +typedef union { + ani_boolean z; + ani_char c; + ani_byte b; + ani_short s; + ani_int i; + ani_long l; + ani_float f; + ani_double d; + ani_ref r; +} ani_value; + +typedef struct { + const char *name; + const char *signature; + const void *pointer; +} ani_native_function; + +#ifdef __cplusplus +typedef struct __ani_vm ani_vm; +typedef struct __ani_env ani_env; +#else +typedef const struct __ani_vm_api *ani_vm; +typedef const struct __ani_interaction_api *ani_env; +#endif + +typedef enum { + ANI_OK, + ANI_ERROR, + ANI_INVALID_ARGS, + ANI_INVALID_TYPE, + ANI_INVALID_DESCRIPTOR, + ANI_PENDING_ERROR, + ANI_NOT_FOUND, + ANI_ALREADY_BINDED, + ANI_OUT_OF_REF, + ANI_OUT_OF_MEMORY, + ANI_OUT_OF_RANGE, + ANI_BUFFER_TO_SMALL, + // NOTE: Add necessary status codes +} ani_status; + +struct __ani_vm_api { + void *reserved0; + void *reserved1; + void *reserved2; + void *reserved3; + + ani_status (*DestroyVM)(ani_vm *vm); + ani_status (*GetEnv)(ani_vm *vm, uint32_t version, ani_env **result); + ani_status (*AttachThread)(ani_vm *vm, void *params, ani_env **result); + ani_status (*DetachThread)(ani_vm *vm); +}; + +typedef struct { + const char *option; + void *option_data; +} ani_vm_option; + +#define ANI_EXPORT __attribute__((visibility("default"))) + +#ifdef __cplusplus +extern "C" { +#endif + +ANI_EXPORT ani_status ANI_CreateVM(uint32_t version, size_t nr_options, const ani_vm_option *options, ani_vm **result); +ANI_EXPORT ani_status ANI_GetCreatedVMs(ani_vm **vms_buffer, ani_size vms_buffer_length, ani_size *result); + +// Prototypes of exported functions for a shared library. +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result); +ANI_EXPORT ani_status ANI_Destructor(ani_vm *vm); + +#ifdef __cplusplus +} +#endif + +struct __ani_interaction_api { + void *reserved0; + void *reserved1; + void *reserved2; + void *reserved3; + + /** + * @brief Retrieves the version information. + * + * This function retrieves the version information and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[out] result A pointer to a variable where the version information will be stored. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*GetVersion)(ani_env *env, uint32_t *result); + + /** + * @brief Retrieves the Virtual Machine (VM) instance. + * + * This function retrieves the VM instance and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[out] result A pointer to the VM instance to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*GetVM)(ani_env *env, ani_vm **result); + + /** + * @brief Checks if a reference is an object. + * + * This function determines whether the specified reference represents an object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is an object, false otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsObject)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a functional object. + * + * This function determines whether the specified reference represents a functional object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is a functional object, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFunctionalObject)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is an enum. + * + * This function determines whether the specified reference represents an enum. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is an enum, false otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsEnum)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a tuple. + * + * This function determines whether the specified reference represents a tuple. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is a tuple, false otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsTuple)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a string. + * + * This function determines whether the specified reference represents a string. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is a string, false otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsString)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a string literal. + * + * This function determines whether the specified reference represents a string literal. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is a string literal, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsStringLiteral)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array. + * + * This function determines whether the specified reference represents a fixed array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is a fixed array, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of booleans. + * + * This function determines whether the specified reference represents a fixed array of booleans. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is a fixed array of booleans, + * false otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Boolean)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of chars. + * + * This function determines whether the specified reference represents a fixed array of chars. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the char result (true if the reference is a fixed array of chars, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Char)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of bytes. + * + * This function determines whether the specified reference represents a fixed array of bytes. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the byte result (true if the reference is a fixed array of bytes, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Byte)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of shorts. + * + * This function determines whether the specified reference represents a fixed array of shorts. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the short result (true if the reference is a fixed array of shorts, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Short)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of integers. + * + * This function determines whether the specified reference represents a fixed array of integers. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the integer result (true if the reference is a fixed array of integers, + * false otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Int)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of longs. + * + * This function determines whether the specified reference represents a fixed array of longs. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the long result (true if the reference is a fixed array of longs, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Long)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of floats. + * + * This function determines whether the specified reference represents a fixed array of floats. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the float result (true if the reference is a fixed array of floats, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Float)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of doubles. + * + * This function determines whether the specified reference represents a fixed array of doubles. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the double result (true if the reference is a fixed array of doubles, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Double)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is a fixed array of references. + * + * This function determines whether the specified reference represents a fixed array of references. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to store the boolean result (true if the reference is a fixed array of references, + * false otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsFixedArray_Ref)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Creates a new object of a specified class using a constructor method. + * + * This function creates a new object of the given class and calls the specified constructor method with variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class of the object to create. + * @param[in] method The constructor method to invoke. + * @param[in] ... Variadic arguments to pass to the constructor method. + * @param[out] result A pointer to store the object return value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_New)(ani_env *env, ani_class cls, ani_method method, ani_object *result, ...); + + /** + * @brief Creates a new object of a specified class using a constructor method (array-based). + * + * This function creates a new object of the given class and calls the specified constructor method with arguments + * provided in an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class of the object to create. + * @param[in] method The constructor method to invoke. + * @param[in] args An array of arguments to pass to the constructor method. + * @param[out] result A pointer to store the object return value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_New_A)(ani_env *env, ani_class cls, ani_method method, ani_object *result, + const ani_value *args); + + /** + * @brief Creates a new object of a specified class using a constructor method (variadic arguments). + * + * This function creates a new object of the given class and calls the specified constructor method with a `va_list` + * of arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class of the object to create. + * @param[in] method The constructor method to invoke. + * @param[in] args A `va_list` of arguments to pass to the constructor method. + * @param[out] result A pointer to store the object return value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_New_V)(ani_env *env, ani_class cls, ani_method method, ani_object *result, va_list args); + + /** + * @brief Retrieves the type of a given object. + * + * This function retrieves the type of the specified object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object whose type is to be retrieved. + * @param[out] result A pointer to store the retrieved type. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetType)(ani_env *env, ani_object object, ani_type *result); + + /** + * @brief Checks if an object is an instance of a specified type. + * + * This function checks whether the given object is an instance of the specified type. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object to check. + * @param[in] type The type to compare against. + * @param[out] result A pointer to store the boolean result (true if the object is an instance of the type, false + * otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_InstanceOf)(ani_env *env, ani_object object, ani_type type, ani_boolean *result); + + /** + * @brief Checks if two objects are the same. + * + * This function compares two objects to determine if they refer to the same instance. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object1 The first object to compare. + * @param[in] object2 The second object to compare. + * @param[out] result A pointer to store the boolean result (true if the objects are the same, false otherwise). + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_IsSame)(ani_env *env, ani_object object1, ani_object object2, ani_boolean *result); + + /** + * @brief Retrieves the superclass of a specified type. + * + * This function retrieves the superclass of a given type and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] type The type for which to retrieve the superclass. + * @param[out] result A pointer to the superclass to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Type_GetSuperClass)(ani_env *env, ani_type type, ani_class *result); + + /** + * @brief Determines if one type is assignable from another. + * + * This function checks if a type is assignable from another and stores the result in the output parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] from_type The source type. + * @param[in] to_type The target type. + * @param[out] result A pointer to a boolean indicating assignability. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Type_IsAssignableFrom)(ani_env *env, ani_type from_type, ani_type to_type, ani_boolean *result); + + /** + * @brief Finds a module by its descriptor. + * + * This function locates a module based on its descriptor and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] module_descriptor The descriptor of the module to find. + * @param[out] result A pointer to the module to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FindModule)(ani_env *env, const char *module_descriptor, ani_module *result); + + /** + * @brief Finds a namespace by its descriptor. + * + * This function locates a namespace based on its descriptor and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] namespace_descriptor The descriptor of the namespace to find. + * @param[out] result A pointer to the namespace to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FindNamespace)(ani_env *env, const char *namespace_descriptor, ani_namespace *result); + + /** + * @brief Finds a class by its descriptor. + * + * This function locates a class based on its descriptor and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] class_descriptor The descriptor of the class to find. + * @param[out] result A pointer to the class to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FindClass)(ani_env *env, const char *class_descriptor, ani_class *result); + + /** + * @brief Finds an enum by its descriptor. + * + * This function locates an enum based on its descriptor and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] enum_descriptor The descriptor of the enum to find. + * @param[out] result A pointer to the enum to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FindEnum)(ani_env *env, const char *enum_descriptor, ani_enum *result); + + /** + * @brief Finds a tuple by its descriptor. + * + * This function locates a tuple based on its descriptor and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_descriptor The descriptor of the tuple to find. + * @param[out] result A pointer to the tuple to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FindTuple)(ani_env *env, const char *tuple_descriptor, ani_tuple *result); + + /** + * @brief Finds a function by its descriptor. + * + * This function locates a function based on its descriptor and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] function_descriptor The descriptor of the function to find. + * @param[out] result A pointer to the function to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FindFunction)(ani_env *env, const char *function_descriptor, ani_function *result); + + /** + * @brief Finds a variable by its descriptor. + * + * This function locates a variable based on its descriptor and stores it in the result parameter. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable_descriptor The descriptor of the variable to find. + * @param[out] result A pointer to the variable to be populated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FindVariable)(ani_env *env, const char *variable_descriptor, ani_variable *result); + + /** + * @brief Finds a namespace within a module by its descriptor. + * + * This function locates a namespace within the specified module based on its descriptor. + * + * @param[in] env A pointer to the environment structure. + * @param[in] module The module to search within. + * @param[in] namespace_descriptor The descriptor of the namespace to find. + * @param[out] result A pointer to the namespace object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Module_FindNamespace)(ani_env *env, ani_module module, const char *namespace_descriptor, + ani_namespace *result); + + /** + * @brief Finds a class within a module by its descriptor. + * + * This function locates a class within the specified module based on its descriptor. + * + * @param[in] env A pointer to the environment structure. + * @param[in] module The module to search within. + * @param[in] class_descriptor The descriptor of the class to find. + * @param[out] result A pointer to the class object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Module_FindClass)(ani_env *env, ani_module module, const char *class_descriptor, ani_class *result); + + /** + * @brief Finds an enum within a module by its descriptor. + * + * This function locates an enum within the specified module based on its descriptor. + * + * @param[in] env A pointer to the environment structure. + * @param[in] module The module to search within. + * @param[in] enum_descriptor The descriptor of the enum to find. + * @param[out] result A pointer to the enum object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Module_FindEnum)(ani_env *env, ani_module module, const char *enum_descriptor, ani_enum *result); + + /** + * @brief Finds a function within a module by its name and signature. + * + * This function locates a function within the specified module based on its name and signature. + * + * @param[in] env A pointer to the environment structure. + * @param[in] module The module to search within. + * @param[in] name The name of the function to retrieve. + * @param[in] signature The signature of the function to retrieve. + * @param[out] result A pointer to the function object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Module_FindFunction)(ani_env *env, ani_module module, const char *name, const char *signature, + ani_function *result); + + /** + * @brief Finds a variable within a module by its descriptor. + * + * This function locates a variable within the specified module based on its descriptor. + * + * @param[in] env A pointer to the environment structure. + * @param[in] module The module to search within. + * @param[in] variable_descriptor The descriptor of the variable to find. + * @param[out] result A pointer to the variable object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Module_FindVariable)(ani_env *env, ani_module module, const char *variable_descriptor, + ani_variable *result); + + /** + * @brief Finds a namespace within another namespace by its descriptor. + * + * This function locates a namespace within the specified parent namespace based on its descriptor. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ns The parent namespace to search within. + * @param[in] namespace_descriptor The descriptor of the namespace to find. + * @param[out] result A pointer to the namespace object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Namespace_FindNamespace)(ani_env *env, ani_namespace ns, const char *namespace_descriptor, + ani_namespace *result); + + /** + * @brief Finds a class within a namespace by its descriptor. + * + * This function locates a class within the specified namespace based on its descriptor. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ns The namespace to search within. + * @param[in] class_descriptor The descriptor of the class to find. + * @param[out] result A pointer to the class object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Namespace_FindClass)(ani_env *env, ani_namespace ns, const char *class_descriptor, ani_class *result); + + /** + * @brief Finds an enum within a namespace by its descriptor. + * + * This function locates an enum within the specified namespace based on its descriptor. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ns The namespace to search within. + * @param[in] enum_descriptor The descriptor of the enum to find. + * @param[out] result A pointer to the enum object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Namespace_FindEnum)(ani_env *env, ani_namespace ns, const char *enum_descriptor, ani_enum *result); + + /** + * @brief Finds a function within a namespace by its name and signature. + * + * This function locates a function within the specified namespace based on its name and signature. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ns The namespace to search within. + * @param[in] name The name of the function to retrieve. + * @param[in] signature The signature of the function to retrieve. + * @param[out] result A pointer to the function object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Namespace_FindFunction)(ani_env *env, ani_namespace ns, const char *name, const char *signature, + ani_function *result); + + /** + * @brief Finds a variable within a namespace by its descriptor. + * + * This function locates a variable within the specified namespace based on its descriptor. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ns The namespace to search within. + * @param[in] variable_descriptor The descriptor of the variable to find. + * @param[out] result A pointer to the variable object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Namespace_FindVariable)(ani_env *env, ani_namespace ns, const char *variable_descriptor, + ani_variable *result); + + /** + * @brief Binds native functions to a module. + * + * This function binds an array of native functions to the specified module. + * + * @param[in] env A pointer to the environment structure. + * @param[in] module The module to which the native functions will be bound. + * @param[in] functions A pointer to an array of native functions to bind. + * @param[in] nr_functions The number of native functions in the array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Module_BindNativeFunctions)(ani_env *env, ani_module module, const ani_native_function *functions, + ani_size nr_functions); + + /** + * @brief Binds native functions to a namespace. + * + * This function binds an array of native functions to the specified namespace. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ns The namespace to which the native functions will be bound. + * @param[in] functions A pointer to an array of native functions to bind. + * @param[in] nr_functions The number of native functions in the array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Namespace_BindNativeFunctions)(ani_env *env, ani_namespace ns, const ani_native_function *functions, + ani_size nr_functions); + + /** + * @brief Binds native methods to a class. + * + * This function binds an array of native methods to the specified class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to which the native methods will be bound. + * @param[in] methods A pointer to an array of native methods to bind. + * @param[in] nr_methods The number of native methods in the array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_BindNativeMethods)(ani_env *env, ani_class cls, const ani_native_function *methods, + ani_size nr_methods); + + /** + * @brief Deletes a local reference. + * + * This function deletes a specified local reference to free up resources. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to be deleted. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_Delete)(ani_env *env, ani_ref ref); + + /** + * @brief Ensures enough local references are available. + * + * This function checks and ensures that the specified number of local references can be created. + * + * @param[in] env A pointer to the environment structure. + * @param[in] nr_refs The number of local references to ensure availability for. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*EnsureEnoughReferences)(ani_env *env, ani_size nr_refs); + + /** + * @brief Creates a new local scope for references. + * + * This function creates a local scope for references with a specified capacity. + * + * @param[in] env A pointer to the environment structure. + * @param[in] nr_refs The maximum number of references that can be created in this scope. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*CreateLocalScope)(ani_env *env, ani_size nr_refs); + + /** + * @brief Destroys the current local scope. + * + * This function destroys the current local scope and frees all references within it. + * + * @param[in] env A pointer to the environment structure. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*DestroyLocalScope)(ani_env *env); + + /** + * @brief Creates a new escape local scope. + * + * This function creates a local scope for references with escape functionality, allowing objects to escape this + * scope. + * + * @param[in] env A pointer to the environment structure. + * @param[in] nr_refs The maximum number of references that can be created in this scope. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*CreateEscapeLocalScope)(ani_env *env, ani_size nr_refs); + + /** + * @brief Destroys the current escape local scope. + * + * This function destroys the current escape local scope and allows escaping references to be retrieved. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to be escaped from the current scope. + * @param[out] result A pointer to the resulting reference that has escaped the scope. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*DestroyEscapeLocalScope)(ani_env *env, ani_ref ref, ani_ref *result); + + /** + * @brief Throws an error. + * + * This function throws the specified error in the current environment. + * + * @param[in] env A pointer to the environment structure. + * @param[in] err The error to throw. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*ThrowError)(ani_env *env, ani_error err); + + /** + * @brief Checks if there are unhandled errors. + * + * This function determines if there are unhandled errors in the current environment. + * + * @param[in] env A pointer to the environment structure. + * @param[out] result A pointer to a boolean indicating if unhandled errors exist. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*ExistUnhandledError)(ani_env *env, ani_boolean *result); + + /** + * @brief Retrieves the current unhandled error. + * + * This function fetches the unhandled error in the environment. + * + * @param[in] env A pointer to the environment structure. + * @param[out] result A pointer to store the unhandled error. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*GetUnhandledError)(ani_env *env, ani_error *result); + + /** + * @brief Resets the current error state. + * + * This function clears the error state in the current environment. + * + * @param[in] env A pointer to the environment structure. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*ResetError)(ani_env *env); + + /** + * @brief Provides a description of the current error. + * + * This function prints the stack trace or other debug information for the current error. + * + * @param[in] env A pointer to the environment structure. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*DescribeError)(ani_env *env); // NOTE: Print stacktrace for debugging? + + /** + * @brief Aborts execution with a message. + * + * This function terminates execution with the specified error message. + * + * @param[in] env A pointer to the environment structure. + * @param[in] message The error message to display on termination. + * @return Does not return; the process terminates. + */ + ani_status (*Abort)(ani_env *env, const char *message); + + /** + * @brief Retrieves a null reference. + * + * This function provides a null reference in the specified result. + * + * @param[in] env A pointer to the environment structure. + * @param[out] result A pointer to store the null reference. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*GetNull)(ani_env *env, ani_ref *result); + + /** + * @brief Retrieves an undefined reference. + * + * This function provides an undefined reference in the specified result. + * + * @param[in] env A pointer to the environment structure. + * @param[out] result A pointer to store the undefined reference. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*GetUndefined)(ani_env *env, ani_ref *result); + + /** + * @brief Checks if a reference is null. + * + * This function determines if the specified reference is null. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to a boolean indicating if the reference is null. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsNull)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is undefined. + * + * This function determines if the specified reference is undefined. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to a boolean indicating if the reference is undefined. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsUndefined)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Checks if a reference is nullish value (null or undefined). + * + * This function determines if the specified reference is either null or undefined. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The reference to check. + * @param[out] result A pointer to a boolean indicating if the reference is nullish value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_IsNullishValue)(ani_env *env, ani_ref ref, ani_boolean *result); + + /** + * @brief Compares two references for equality. + * + * This function checks if two references are equal. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref0 The first reference to compare. + * @param[in] ref1 The second reference to compare. + * @param[out] result A pointer to a boolean indicating if the references are equal. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_Equals)(ani_env *env, ani_ref ref0, ani_ref ref1, ani_boolean *result); + + /** + * @brief Compares two references for strict equality. + * + * This function checks if two references are strictly equal. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref0 The first reference to compare. + * @param[in] ref1 The second reference to compare. + * @param[out] result A pointer to a boolean indicating if the references are strictly equal. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reference_StrictEquals)(ani_env *env, ani_ref ref0, ani_ref ref1, ani_boolean *result); + + /** + * @brief Creates a new UTF-16 string. + * + * This function creates a new string from the provided UTF-16 encoded data. + * + * @param[in] env A pointer to the environment structure. + * @param[in] utf16_string A pointer to the UTF-16 encoded string data. + * @param[in] utf16_size The size of the UTF-16 string in code units. + * @param[out] result A pointer to store the created string. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_NewUTF16)(ani_env *env, const uint16_t *utf16_string, ani_size utf16_size, ani_string *result); + + /** + * @brief Retrieves the size of a UTF-16 string. + * + * This function retrieves the size (in code units) of the specified UTF-16 string. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The UTF-16 string to measure. + * @param[out] result A pointer to store the size of the string. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_GetUTF16Size)(ani_env *env, ani_string string, ani_size *result); + + /** + * @brief Retrieves the UTF-16 encoded data of a string. + * + * This function copies the UTF-16 encoded data of the string into the provided buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string to retrieve data from. + * @param[out] utf16_buffer A buffer to store the UTF-16 encoded data. + * @param[in] utf16_buffer_size The size of the buffer in code units. + * @param[out] result A pointer to store the number of code units written. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_GetUTF16)(ani_env *env, ani_string string, uint16_t *utf16_buffer, ani_size utf16_buffer_size, + ani_size *result); + + /** + * @brief Retrieves a substring of a UTF-16 string. + * + * This function copies a portion of the UTF-16 string into the provided buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string to retrieve data from. + * @param[in] substr_offset The starting offset of the substring. + * @param[in] substr_size The size of the substring in code units. + * @param[out] utf16_buffer A buffer to store the substring. + * @param[in] utf16_buffer_size The size of the buffer in code units. + * @param[out] result A pointer to store the number of code units written. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_GetUTF16SubString)(ani_env *env, ani_string string, ani_size substr_offset, + ani_size substr_size, uint16_t *utf16_buffer, ani_size utf16_buffer_size, + ani_size *result); + + /** + * @brief Creates a new UTF-8 string. + * + * This function creates a new string from the provided UTF-8 encoded data. + * + * @param[in] env A pointer to the environment structure. + * @param[in] utf8_string A pointer to the UTF-8 encoded string data. + * @param[in] utf8_size The size of the UTF-8 string in bytes. + * @param[out] result A pointer to store the created string. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_NewUTF8)(ani_env *env, const char *utf8_string, ani_size utf8_size, ani_string *result); + + /** + * @brief Retrieves the size of a UTF-8 string. + * + * This function retrieves the size (in bytes) of the specified UTF-8 string. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The UTF-8 string to measure. + * @param[out] result A pointer to store the size of the string. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_GetUTF8Size)(ani_env *env, ani_string string, ani_size *result); + + /** + * @brief Retrieves the UTF-8 encoded data of a string. + * + * This function copies the UTF-8 encoded data of the string into the provided buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string to retrieve data from. + * @param[out] utf8_buffer A buffer to store the UTF-8 encoded data. + * @param[in] utf8_buffer_size The size of the buffer in bytes. + * @param[out] result A pointer to store the number of bytes written. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_GetUTF8)(ani_env *env, ani_string string, char *utf8_buffer, ani_size utf8_buffer_size, + ani_size *result); + + /** + * @brief Retrieves a substring of a UTF-8 string. + * + * This function copies a portion of the UTF-8 string into the provided buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string to retrieve data from. + * @param[in] substr_offset The starting offset of the substring. + * @param[in] substr_size The size of the substring in bytes. + * @param[out] utf8_buffer A buffer to store the substring. + * @param[in] utf8_buffer_size The size of the buffer in bytes. + * @param[out] result A pointer to store the number of bytes written. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_GetUTF8SubString)(ani_env *env, ani_string string, ani_size substr_offset, ani_size substr_size, + char *utf8_buffer, ani_size utf8_buffer_size, ani_size *result); + + /** + * @brief Retrieves critical information about a string. + * + * This function retrieves the type and data of a string for critical operations. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string to analyze. + * @param[out] result_string_type A pointer to store the type of the string (e.g., UTF-16 or UTF-8). + * @param[out] result_data A pointer to the raw string data. + * @param[out] result_size A pointer to the size of the string data. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_GetCritical)(ani_env *env, ani_string string, uint32_t *result_string_type, + const void **result_data, + ani_size *result_size); // result_string_type - string type utf16/utf8, etc? + + /** + * @brief Releases critical string data. + * + * This function releases the raw string data retrieved using `String_GetCritical`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string whose data was retrieved. + * @param[in] data A pointer to the raw data to release. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*String_ReleaseCritical)(ani_env *env, ani_string string, const void *data); + + /** + * @brief Creates a new UTF-16 string literal. + * + * This function creates a new string literal from the provided UTF-16 encoded data. + * + * @param[in] env A pointer to the environment structure. + * @param[in] utf16_string A pointer to the UTF-16 encoded string data. + * @param[in] utf16_size The size of the UTF-16 string in code units. + * @param[out] result A pointer to store the created string literal. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_NewUTF16)(ani_env *env, const uint16_t *utf16_string, ani_size utf16_size, + ani_stringliteral *result); + + /** + * @brief Retrieves the size of a UTF-16 string literal. + * + * This function retrieves the size (in code units) of the specified UTF-16 string literal. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The UTF-16 string literal to measure. + * @param[out] result A pointer to store the size of the string literal. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_GetUTF16Size)(ani_env *env, ani_stringliteral string, ani_size *result); + + /** + * @brief Retrieves the UTF-16 encoded data of a string literal. + * + * This function copies the UTF-16 encoded data of the string literal into the provided buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string literal to retrieve data from. + * @param[out] utf16_buffer A buffer to store the UTF-16 encoded data. + * @param[in] utf16_buffer_size The size of the buffer in code units. + * @param[out] result A pointer to store the number of code units written. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_GetUTF16)(ani_env *env, ani_stringliteral string, uint16_t *utf16_buffer, + ani_size utf16_buffer_size, ani_size *result); + + /** + * @brief Retrieves a substring of a UTF-16 string literal. + * + * This function copies a portion of the UTF-16 string literal into the provided buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string literal to retrieve data from. + * @param[in] substr_offset The starting offset of the substring. + * @param[in] substr_size The size of the substring in code units. + * @param[out] utf16_buffer A buffer to store the substring. + * @param[in] utf16_buffer_size The size of the buffer in code units. + * @param[out] result A pointer to store the number of code units written. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_GetUTF16SubString)(ani_env *env, ani_stringliteral string, ani_size substr_offset, + ani_size substr_size, uint16_t *utf16_buffer, + ani_size utf16_buffer_size, ani_size *result); + + /** + * @brief Creates a new UTF-8 string literal. + * + * This function creates a new string literal from the provided UTF-8 encoded data. + * + * @param[in] env A pointer to the environment structure. + * @param[in] utf8_string A pointer to the UTF-8 encoded string data. + * @param[in] size The size of the UTF-8 string in bytes. + * @param[out] result A pointer to store the created string literal. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_NewUTF8)(ani_env *env, const char *utf8_string, ani_size size, + ani_stringliteral *result); + + /** + * @brief Retrieves the size of a UTF-8 string literal. + * + * This function retrieves the size (in bytes) of the specified UTF-8 string literal. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The UTF-8 string literal to measure. + * @param[out] result A pointer to store the size of the string literal. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_GetUTF8Size)(ani_env *env, ani_stringliteral string, ani_size *result); + + /** + * @brief Retrieves the UTF-8 encoded data of a string literal. + * + * This function copies the UTF-8 encoded data of the string literal into the provided buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string literal to retrieve data from. + * @param[out] utf8_buffer A buffer to store the UTF-8 encoded data. + * @param[in] utf8_buffer_size The size of the buffer in bytes. + * @param[out] result A pointer to store the number of bytes written. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_GetUTF8)(ani_env *env, ani_stringliteral string, char *utf8_buffer, + ani_size utf8_buffer_size, ani_size *result); + + /** + * @brief Retrieves a substring of a UTF-8 string literal. + * + * This function copies a portion of the UTF-8 string literal into the provided buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string literal to retrieve data from. + * @param[in] substr_offset The starting offset of the substring. + * @param[in] substr_size The size of the substring in bytes. + * @param[out] utf8_buffer A buffer to store the substring. + * @param[in] utf8_buffer_size The size of the buffer in bytes. + * @param[out] result A pointer to store the number of bytes written. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_GetUTF8SubString)(ani_env *env, ani_stringliteral string, ani_size substr_offset, + ani_size substr_size, char *utf8_buffer, ani_size utf8_buffer_size, + ani_size *result); + + /** + * @brief Retrieves critical information about a string literal. + * + * This function retrieves the type and data of a string literal for critical operations. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string literal to analyze. + * @param[out] result_string_type A pointer to store the type of the string literal (e.g., UTF-16 or UTF-8). + * @param[out] result_data A pointer to the raw string literal data. + * @param[out] result_size A pointer to the size of the string literal data. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_GetCritical)( + ani_env *env, ani_stringliteral string, uint32_t *result_string_type, const void **result_data, + ani_size *result_size); // result_string_type - string type utf16/utf8, etc? + + /** + * @brief Releases critical string literal data. + * + * This function releases the raw string literal data retrieved using `StringLiteral_GetCritical`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] string The string literal whose data was retrieved. + * @param[in] data A pointer to the raw data to release. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*StringLiteral_ReleaseCritical)(ani_env *env, ani_stringliteral string, const void *data); + + /** + * @brief Retrieves the length of a fixed array. + * + * This function retrieves the length of the specified fixed array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array whose length is to be retrieved. + * @param[out] result A pointer to store the length of the array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetLength)(ani_env *env, ani_fixedarray array, ani_size *result); + + /** + * @brief Creates a new fixed array of booleans. + * + * This function creates a new fixed array of the specified length for boolean values. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[out] result A pointer to store the created fixed array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Boolean)(ani_env *env, ani_size length, ani_fixedarray_boolean *result); + + /** + * @brief Creates a new fixed array of characters. + * + * This function creates a new fixed array of the specified length for character values. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[out] result A pointer to store the created fixed array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Char)(ani_env *env, ani_size length, ani_fixedarray_char *result); + + /** + * @brief Creates a new fixed array of bytes. + * + * This function creates a new fixed array of the specified length for byte values. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[out] result A pointer to store the created fixed array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Byte)(ani_env *env, ani_size length, ani_fixedarray_byte *result); + + /** + * @brief Creates a new fixed array of shorts. + * + * This function creates a new fixed array of the specified length for short integer values. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[out] result A pointer to store the created fixed array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Short)(ani_env *env, ani_size length, ani_fixedarray_short *result); + + /** + * @brief Creates a new fixed array of integers. + * + * This function creates a new fixed array of the specified length for integer values. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[out] result A pointer to store the created fixed array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Int)(ani_env *env, ani_size length, ani_fixedarray_int *result); + + /** + * @brief Creates a new fixed array of long integers. + * + * This function creates a new fixed array of the specified length for long integer values. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[out] result A pointer to store the created fixed array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Long)(ani_env *env, ani_size length, ani_fixedarray_long *result); + + /** + * @brief Creates a new fixed array of floats. + * + * This function creates a new fixed array of the specified length for float values. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[out] result A pointer to store the created fixed array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Float)(ani_env *env, ani_size length, ani_fixedarray_float *result); + + /** + * @brief Creates a new fixed array of doubles. + * + * This function creates a new fixed array of the specified length for double values. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[out] result A pointer to store the created fixed array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Double)(ani_env *env, ani_size length, ani_fixedarray_double *result); + + /** + * @brief Retrieves a region of boolean values from a fixed array. + * + * This function retrieves a portion of the specified boolean fixed array into a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to retrieve values from. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to retrieve. + * @param[out] native_buffer A buffer to store the retrieved boolean values. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetRegion_Boolean)(ani_env *env, ani_fixedarray_boolean array, ani_size offset, + ani_size length, ani_boolean *native_buffer); + + /** + * @brief Retrieves a region of character values from a fixed array. + * + * This function retrieves a portion of the specified character fixed array into a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to retrieve values from. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to retrieve. + * @param[out] native_buffer A buffer to store the retrieved character values. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetRegion_Char)(ani_env *env, ani_fixedarray_char array, ani_size offset, ani_size length, + ani_char *native_buffer); + + /** + * @brief Retrieves a region of byte values from a fixed array. + * + * This function retrieves a portion of the specified byte fixed array into a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to retrieve values from. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to retrieve. + * @param[out] native_buffer A buffer to store the retrieved byte values. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetRegion_Byte)(ani_env *env, ani_fixedarray_byte array, ani_size offset, ani_size length, + ani_byte *native_buffer); + + /** + * @brief Retrieves a region of short values from a fixed array. + * + * This function retrieves a portion of the specified short fixed array into a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to retrieve values from. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to retrieve. + * @param[out] native_buffer A buffer to store the retrieved short values. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetRegion_Short)(ani_env *env, ani_fixedarray_short array, ani_size offset, ani_size length, + ani_short *native_buffer); + + /** + * @brief Retrieves a region of integer values from a fixed array. + * + * This function retrieves a portion of the specified integer fixed array into a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to retrieve values from. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to retrieve. + * @param[out] native_buffer A buffer to store the retrieved integer values. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetRegion_Int)(ani_env *env, ani_fixedarray_int array, ani_size offset, ani_size length, + ani_int *native_buffer); + + /** + * @brief Retrieves a region of long integer values from a fixed array. + * + * This function retrieves a portion of the specified long integer fixed array into a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to retrieve values from. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to retrieve. + * @param[out] native_buffer A buffer to store the retrieved long integer values. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetRegion_Long)(ani_env *env, ani_fixedarray_long array, ani_size offset, ani_size length, + ani_long *native_buffer); + + /** + * @brief Retrieves a region of float values from a fixed array. + * + * This function retrieves a portion of the specified float fixed array into a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to retrieve values from. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to retrieve. + * @param[out] native_buffer A buffer to store the retrieved float values. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetRegion_Float)(ani_env *env, ani_fixedarray_float array, ani_size offset, ani_size length, + ani_float *native_buffer); + + /** + * @brief Retrieves a region of double values from a fixed array. + * + * This function retrieves a portion of the specified double fixed array into a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to retrieve values from. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to retrieve. + * @param[out] native_buffer A buffer to store the retrieved double values. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_GetRegion_Double)(ani_env *env, ani_fixedarray_double array, ani_size offset, + ani_size length, ani_double *native_buffer); + + /** + * @brief Sets a region of boolean values in a fixed array. + * + * This function sets a portion of the specified boolean fixed array using a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to set values in. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to set. + * @param[in] native_buffer A buffer containing the boolean values to set. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_SetRegion_Boolean)(ani_env *env, ani_fixedarray_boolean array, ani_size offset, + ani_size length, const ani_boolean *native_buffer); + + /** + * @brief Sets a region of character values in a fixed array. + * + * This function sets a portion of the specified character fixed array using a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to set values in. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to set. + * @param[in] native_buffer A buffer containing the character values to set. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_SetRegion_Char)(ani_env *env, ani_fixedarray_char array, ani_size offset, ani_size length, + const ani_char *native_buffer); + + /** + * @brief Sets a region of byte values in a fixed array. + * + * This function sets a portion of the specified byte fixed array using a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to set values in. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to set. + * @param[in] native_buffer A buffer containing the byte values to set. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_SetRegion_Byte)(ani_env *env, ani_fixedarray_byte array, ani_size offset, ani_size length, + const ani_byte *native_buffer); + + /** + * @brief Sets a region of short values in a fixed array. + * + * This function sets a portion of the specified short fixed array using a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to set values in. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to set. + * @param[in] native_buffer A buffer containing the short values to set. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_SetRegion_Short)(ani_env *env, ani_fixedarray_short array, ani_size offset, ani_size length, + const ani_short *native_buffer); + + /** + * @brief Sets a region of integer values in a fixed array. + * + * This function sets a portion of the specified integer fixed array using a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to set values in. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to set. + * @param[in] native_buffer A buffer containing the integer values to set. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_SetRegion_Int)(ani_env *env, ani_fixedarray_int array, ani_size offset, ani_size length, + const ani_int *native_buffer); + + /** + * @brief Sets a region of long integer values in a fixed array. + * + * This function sets a portion of the specified long integer fixed array using a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to set values in. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to set. + * @param[in] native_buffer A buffer containing the long integer values to set. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_SetRegion_Long)(ani_env *env, ani_fixedarray_long array, ani_size offset, ani_size length, + const ani_long *native_buffer); + + /** + * @brief Sets a region of float values in a fixed array. + * + * This function sets a portion of the specified float fixed array using a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to set values in. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to set. + * @param[in] native_buffer A buffer containing the float values to set. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_SetRegion_Float)(ani_env *env, ani_fixedarray_float array, ani_size offset, ani_size length, + const ani_float *native_buffer); + + /** + * @brief Sets a region of double values in a fixed array. + * + * This function sets a portion of the specified double fixed array using a native buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array to set values in. + * @param[in] offset The starting offset of the region. + * @param[in] length The number of elements to set. + * @param[in] native_buffer A buffer containing the double values to set. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_SetRegion_Double)(ani_env *env, ani_fixedarray_double array, ani_size offset, + ani_size length, const ani_double *native_buffer); + + /** + * @brief Pins a fixed array in memory. + * + * This function pins a fixed array of primitive types in memory to ensure it is not moved by the garbage collector. + * + * @param[in] env A pointer to the environment structure. + * @param[in] primitive_array The fixed array to pin. + * @param[out] result A pointer to store the memory address of the pinned array. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_Pin)(ani_env *env, ani_fixedarray primitive_array, void **result); + + /** + * @brief Unpins a fixed array in memory. + * + * This function unpins a previously pinned fixed array, allowing it to be moved by the garbage collector. + * + * @param[in] env A pointer to the environment structure. + * @param[in] primitive_array The fixed array to unpin. + * @param[in] data A pointer to the pinned memory that was previously retrieved. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_Unpin)(ani_env *env, ani_fixedarray primitive_array, void *data); + + /** + * @brief Creates a new fixed array of references. + * + * This function creates a new fixed array of references, optionally initializing it with an array of references. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array to be created. + * @param[in] initial_array An optional array of references to initialize the fixed array. Can be null. + * @param[out] result A pointer to store the created fixed array of references. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_New_Ref)(ani_env *env, ani_size length, ani_ref *initial_array, ani_fixedarray_ref *result); + + /** + * @brief Sets a reference at a specific index in a fixed array. + * + * This function sets the value of a reference at the specified index in the fixed array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array of references to modify. + * @param[in] index The index at which to set the reference. + * @param[in] ref The reference to set at the specified index. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_Set_Ref)(ani_env *env, ani_fixedarray_ref array, ani_size index, ani_ref ref); + + /** + * @brief Retrieves a reference from a specific index in a fixed array. + * + * This function retrieves the value of a reference at the specified index in the fixed array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] array The fixed array of references to query. + * @param[in] index The index from which to retrieve the reference. + * @param[out] result A pointer to store the retrieved reference. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FixedArray_Get_Ref)(ani_env *env, ani_fixedarray_ref array, ani_size index, ani_ref *result); + + /** + * @brief Retrieves an enum value by its name. + * + * This function retrieves an enum value associated with the specified name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] enm The enum to search within. + * @param[in] name The name of the enum value to retrieve. + * @param[out] result A pointer to store the retrieved enum value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Enum_GetEnumValueByName)(ani_env *env, ani_enum enm, const char *name, ani_enum_value *result); + + /** + * @brief Retrieves an enum value by its index. + * + * This function retrieves an enum value located at the specified index. + * + * @param[in] env A pointer to the environment structure. + * @param[in] enm The enum to search within. + * @param[in] index The index of the enum value to retrieve. + * @param[out] result A pointer to store the retrieved enum value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Enum_GetEnumValueByIndex)(ani_env *env, ani_enum enm, ani_size index, ani_enum_value *result); + + /** + * @brief Retrieves the enum associated with an enum value. + * + * This function retrieves the enum to which the specified enum value belongs. + * + * @param[in] env A pointer to the environment structure. + * @param[in] enum_value The enum value whose associated enum is to be retrieved. + * @param[out] result A pointer to store the retrieved enum. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*EnumValue_GetEnum)(ani_env *env, ani_enum_value enum_value, ani_enum *result); + + /** + * @brief Retrieves the underlying value of an enum value. + * + * This function retrieves the object representing the value of the specified enum value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] enum_value The enum value whose underlying value is to be retrieved. + * @param[out] result A pointer to store the retrieved object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*EnumValue_GetValue)(ani_env *env, ani_enum_value enum_value, ani_object *result); + + /** + * @brief Retrieves the name of an enum value. + * + * This function retrieves the name associated with the specified enum value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] enum_value The enum value whose name is to be retrieved. + * @param[out] result A pointer to store the retrieved name. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*EnumValue_GetName)(ani_env *env, ani_enum_value enum_value, ani_string *result); + + /** + * @brief Retrieves the index of an enum value. + * + * This function retrieves the index of the specified enum value within its enum. + * + * @param[in] env A pointer to the environment structure. + * @param[in] enum_value The enum value whose index is to be retrieved. + * @param[out] result A pointer to store the retrieved index. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*EnumValue_GetIndex)(ani_env *env, ani_enum_value enum_value, ani_size *result); + + /** + * @brief Invokes a functional object. + * + * This function invokes a functional object (e.g., a function or callable object) with the specified arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The functional object to invoke. + * @param[in] argc The number of arguments being passed to the functional object. + * @param[in] argv A pointer to an array of references representing the arguments. Can be null if `argc` is 0. + * @param[out] result A pointer to store the result of the invocation. Can be null if the functional object does not + * return a value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*FunctionalObject_Call)(ani_env *env, ani_fn_object fn, ani_size argc, ani_ref *argv, ani_ref *result); + + /** + * @brief Sets a boolean value to a variable. + * + * This function assigns a boolean value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The boolean value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Boolean)(ani_env *env, ani_variable variable, ani_boolean value); + + /** + * @brief Sets a character value to a variable. + * + * This function assigns a character value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The character value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Char)(ani_env *env, ani_variable variable, ani_char value); + + /** + * @brief Sets a byte value to a variable. + * + * This function assigns a byte value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The byte value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Byte)(ani_env *env, ani_variable variable, ani_byte value); + + /** + * @brief Sets a short value to a variable. + * + * This function assigns a short integer value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The short integer value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Short)(ani_env *env, ani_variable variable, ani_short value); + + /** + * @brief Sets an integer value to a variable. + * + * This function assigns an integer value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The integer value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Int)(ani_env *env, ani_variable variable, ani_int value); + + /** + * @brief Sets a long value to a variable. + * + * This function assigns a long integer value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The long integer value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Long)(ani_env *env, ani_variable variable, ani_long value); + + /** + * @brief Sets a float value to a variable. + * + * This function assigns a float value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The float value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Float)(ani_env *env, ani_variable variable, ani_float value); + + /** + * @brief Sets a double value to a variable. + * + * This function assigns a double value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The double value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Double)(ani_env *env, ani_variable variable, ani_double value); + + /** + * @brief Sets a reference value to a variable. + * + * This function assigns a reference value to the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to modify. + * @param[in] value The reference value to assign to the variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_SetValue_Ref)(ani_env *env, ani_variable variable, ani_ref value); + + /** + * @brief Retrieves a boolean value from a variable. + * + * This function fetches a boolean value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved boolean value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Boolean)(ani_env *env, ani_variable variable, ani_boolean *result); + + /** + * @brief Retrieves a character value from a variable. + * + * This function fetches a character value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved character value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Char)(ani_env *env, ani_variable variable, ani_char *result); + + /** + * @brief Retrieves a byte value from a variable. + * + * This function fetches a byte value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved byte value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Byte)(ani_env *env, ani_variable variable, ani_byte *result); + + /** + * @brief Retrieves a short value from a variable. + * + * This function fetches a short integer value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved short integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Short)(ani_env *env, ani_variable variable, ani_short *result); + + /** + * @brief Retrieves an integer value from a variable. + * + * This function fetches an integer value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Int)(ani_env *env, ani_variable variable, ani_int *result); + + /** + * @brief Retrieves a long value from a variable. + * + * This function fetches a long integer value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved long integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Long)(ani_env *env, ani_variable variable, ani_long *result); + + /** + * @brief Retrieves a float value from a variable. + * + * This function fetches a float value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved float value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Float)(ani_env *env, ani_variable variable, ani_float *result); + + /** + * @brief Retrieves a double value from a variable. + * + * This function fetches a double value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved double value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Double)(ani_env *env, ani_variable variable, ani_double *result); + + /** + * @brief Retrieves a reference value from a variable. + * + * This function fetches a reference value from the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to query. + * @param[out] result A pointer to store the retrieved reference value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Variable_GetValue_Ref)(ani_env *env, ani_variable variable, ani_ref *result); + + /** + * @brief Calls a function and retrieves a boolean result. + * + * This function calls the specified function with variadic arguments and retrieves a boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Boolean)(ani_env *env, ani_function fn, ani_boolean *result, ...); + + /** + * @brief Calls a function and retrieves a boolean result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves a boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Boolean_A)(ani_env *env, ani_function fn, ani_boolean *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves a boolean result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves a boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Boolean_V)(ani_env *env, ani_function fn, ani_boolean *result, va_list args); + + /** + * @brief Calls a function and retrieves a character result. + * + * This function calls the specified function with variadic arguments and retrieves a character result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the character result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Char)(ani_env *env, ani_function fn, ani_char *result, ...); + + /** + * @brief Calls a function and retrieves a character result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves a character result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the character result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Char_A)(ani_env *env, ani_function fn, ani_char *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves a character result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves a character + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the character result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Char_V)(ani_env *env, ani_function fn, ani_char *result, va_list args); + + /** + * @brief Calls a function and retrieves a byte result. + * + * This function calls the specified function with variadic arguments and retrieves a byte result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the byte result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Byte)(ani_env *env, ani_function fn, ani_byte *result, ...); + + /** + * @brief Calls a function and retrieves a byte result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves a byte result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the byte result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Byte_A)(ani_env *env, ani_function fn, ani_byte *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves a byte result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves a byte result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the byte result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Byte_V)(ani_env *env, ani_function fn, ani_byte *result, va_list args); + + /** + * @brief Calls a function and retrieves a short result. + * + * This function calls the specified function with variadic arguments and retrieves a short result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the short result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Short)(ani_env *env, ani_function fn, ani_short *result, ...); + + /** + * @brief Calls a function and retrieves a short result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves a short result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the short result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Short_A)(ani_env *env, ani_function fn, ani_short *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves a short result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves a short result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the short result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Short_V)(ani_env *env, ani_function fn, ani_short *result, va_list args); + + /** + * @brief Calls a function and retrieves an integer result. + * + * This function calls the specified function with variadic arguments and retrieves an integer result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the integer result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Int)(ani_env *env, ani_function fn, ani_int *result, ...); + + /** + * @brief Calls a function and retrieves an integer result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves an integer result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the integer result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Int_A)(ani_env *env, ani_function fn, ani_int *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves an integer result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves an integer + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the integer result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Int_V)(ani_env *env, ani_function fn, ani_int *result, va_list args); + + /** + * @brief Calls a function and retrieves a long result. + * + * This function calls the specified function with variadic arguments and retrieves a long result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the long result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Long)(ani_env *env, ani_function fn, ani_long *result, ...); + + /** + * @brief Calls a function and retrieves a long result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves a long result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the long result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Long_A)(ani_env *env, ani_function fn, ani_long *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves a long result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves a long result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the long result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Long_V)(ani_env *env, ani_function fn, ani_long *result, va_list args); + + /** + * @brief Calls a function and retrieves a float result. + * + * This function calls the specified function with variadic arguments and retrieves a float result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the float result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Float)(ani_env *env, ani_function fn, ani_float *result, ...); + + /** + * @brief Calls a function and retrieves a float result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves a float result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the float result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Float_A)(ani_env *env, ani_function fn, ani_float *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves a float result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves a float result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the float result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Float_V)(ani_env *env, ani_function fn, ani_float *result, va_list args); + + /** + * @brief Calls a function and retrieves a double result. + * + * This function calls the specified function with variadic arguments and retrieves a double result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the double result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Double)(ani_env *env, ani_function fn, ani_double *result, ...); + + /** + * @brief Calls a function and retrieves a double result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves a double result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the double result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Double_A)(ani_env *env, ani_function fn, ani_double *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves a double result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves a double result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the double result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Double_V)(ani_env *env, ani_function fn, ani_double *result, va_list args); + + /** + * @brief Calls a function and retrieves a reference result. + * + * This function calls the specified function with variadic arguments and retrieves a reference result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the reference result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Ref)(ani_env *env, ani_function fn, ani_ref *result, ...); + + /** + * @brief Calls a function and retrieves a reference result (array-based). + * + * This function calls the specified function with arguments provided in an array and retrieves a reference result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the reference result. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Ref_A)(ani_env *env, ani_function fn, ani_ref *result, const ani_value *args); + + /** + * @brief Calls a function and retrieves a reference result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and retrieves a reference + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[out] result A pointer to store the reference result. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Ref_V)(ani_env *env, ani_function fn, ani_ref *result, va_list args); + + /** + * @brief Calls a function without returning a result. + * + * This function calls the specified function with variadic arguments and does not return a result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Void)(ani_env *env, ani_function fn, ...); + + /** + * @brief Calls a function without returning a result (array-based). + * + * This function calls the specified function with arguments provided in an array and does not return a result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[in] args A pointer to an array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Void_A)(ani_env *env, ani_function fn, const ani_value *args); + + /** + * @brief Calls a function without returning a result (variadic arguments). + * + * This function calls the specified function with arguments provided in a `va_list` and does not return a result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The function to call. + * @param[in] args A `va_list` containing the arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Function_Call_Void_V)(ani_env *env, ani_function fn, va_list args); + + /** + * @brief Retrieves the partial class representation. + * + * This function retrieves the partial class representation of the specified class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[out] result A pointer to store the partial class representation. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetPartial)(ani_env *env, ani_class cls, ani_class *result); + + /** + * @brief Retrieves the required class representation. + * + * This function retrieves the required class representation of the specified class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[out] result A pointer to store the required class representation. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetRequired)(ani_env *env, ani_class cls, ani_class *result); + + /** + * @brief Retrieves a field from the class. + * + * This function retrieves the specified field by name from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] name The name of the field to retrieve. + * @param[out] result A pointer to store the retrieved field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetField)(ani_env *env, ani_class cls, const char *name, ani_field *result); + + /** + * @brief Retrieves a static field from the class. + * + * This function retrieves the specified static field by name from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved static field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField)(ani_env *env, ani_class cls, const char *name, ani_static_field *result); + + /** + * @brief Retrieves a method from the class. + * + * This function retrieves the specified method by name and signature from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] name The name of the method to retrieve. + * @param[in] signature The signature of the method to retrieve. + * @param[out] result A pointer to store the retrieved method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetMethod)(ani_env *env, ani_class cls, const char *name, const char *signature, + ani_method *result); + + /** + * @brief Retrieves a static method from the class. + * + * This function retrieves the specified static method by name and signature from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] name The name of the static method to retrieve. + * @param[in] signature The signature of the static method to retrieve. + * @param[out] result A pointer to store the retrieved static method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticMethod)(ani_env *env, ani_class cls, const char *name, const char *signature, + ani_static_method *result); + + /** + * @brief Retrieves a property from the class. + * + * This function retrieves the specified property by name from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] name The name of the property to retrieve. + * @param[out] result A pointer to store the retrieved property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetProperty)(ani_env *env, ani_class cls, const char *name, ani_property *result); + + /** + * @brief Retrieves the setter method of a property from the class. + * + * This function retrieves the setter method for the specified property by name from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] name The name of the property whose setter is to be retrieved. + * @param[out] result A pointer to store the retrieved setter method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetSetter)(ani_env *env, ani_class cls, const char *name, ani_method *result); + + /** + * @brief Retrieves the getter method of a property from the class. + * + * This function retrieves the getter method for the specified property by name from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] name The name of the property whose getter is to be retrieved. + * @param[out] result A pointer to store the retrieved getter method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetGetter)(ani_env *env, ani_class cls, const char *name, ani_method *result); + + /** + * @brief Retrieves the indexable getter method from the class. + * + * This function retrieves the indexable getter method for the specified signature from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] signature The signature of the indexable getter to retrieve. + * @param[out] result A pointer to store the retrieved indexable getter method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetIndexableGetter)(ani_env *env, ani_class cls, const char *signature, ani_method *result); + + /** + * @brief Retrieves the indexable setter method from the class. + * + * This function retrieves the indexable setter method for the specified signature from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[in] signature The signature of the indexable setter to retrieve. + * @param[out] result A pointer to store the retrieved indexable setter method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetIndexableSetter)(ani_env *env, ani_class cls, const char *signature, ani_method *result); + + /** + * @brief Retrieves the iterator method from the class. + * + * This function retrieves the iterator method from the specified class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class to query. + * @param[out] result A pointer to store the retrieved iterator method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetIterator)(ani_env *env, ani_class cls, ani_method *result); + + /** + * @brief Retrieves a boolean value from a static field of a class. + * + * This function retrieves the boolean value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved boolean value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Boolean)(ani_env *env, ani_class cls, ani_static_field field, + ani_boolean *result); + + /** + * @brief Retrieves a character value from a static field of a class. + * + * This function retrieves the character value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved character value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Char)(ani_env *env, ani_class cls, ani_static_field field, ani_char *result); + + /** + * @brief Retrieves a byte value from a static field of a class. + * + * This function retrieves the byte value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved byte value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Byte)(ani_env *env, ani_class cls, ani_static_field field, ani_byte *result); + + /** + * @brief Retrieves a short value from a static field of a class. + * + * This function retrieves the short value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved short value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Short)(ani_env *env, ani_class cls, ani_static_field field, ani_short *result); + + /** + * @brief Retrieves an integer value from a static field of a class. + * + * This function retrieves the integer value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Int)(ani_env *env, ani_class cls, ani_static_field field, ani_int *result); + + /** + * @brief Retrieves a long value from a static field of a class. + * + * This function retrieves the long value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved long value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Long)(ani_env *env, ani_class cls, ani_static_field field, ani_long *result); + + /** + * @brief Retrieves a float value from a static field of a class. + * + * This function retrieves the float value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved float value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Float)(ani_env *env, ani_class cls, ani_static_field field, ani_float *result); + + /** + * @brief Retrieves a double value from a static field of a class. + * + * This function retrieves the double value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved double value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Double)(ani_env *env, ani_class cls, ani_static_field field, ani_double *result); + + /** + * @brief Retrieves a reference value from a static field of a class. + * + * This function retrieves the reference value of the specified static field from the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to retrieve. + * @param[out] result A pointer to store the retrieved reference value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticField_Ref)(ani_env *env, ani_class cls, ani_static_field field, ani_ref *result); + + /** + * @brief Sets a boolean value to a static field of a class. + * + * This function assigns a boolean value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The boolean value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Boolean)(ani_env *env, ani_class cls, ani_static_field field, ani_boolean value); + + /** + * @brief Sets a character value to a static field of a class. + * + * This function assigns a character value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The character value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Char)(ani_env *env, ani_class cls, ani_static_field field, ani_char value); + + /** + * @brief Sets a byte value to a static field of a class. + * + * This function assigns a byte value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The byte value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Byte)(ani_env *env, ani_class cls, ani_static_field field, ani_byte value); + + /** + * @brief Sets a short value to a static field of a class. + * + * This function assigns a short value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The short value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Short)(ani_env *env, ani_class cls, ani_static_field field, ani_short value); + + /** + * @brief Sets an integer value to a static field of a class. + * + * This function assigns an integer value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The integer value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Int)(ani_env *env, ani_class cls, ani_static_field field, ani_int value); + + /** + * @brief Sets a long value to a static field of a class. + * + * This function assigns a long value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The long value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Long)(ani_env *env, ani_class cls, ani_static_field field, ani_long value); + + /** + * @brief Sets a float value to a static field of a class. + * + * This function assigns a float value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The float value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Float)(ani_env *env, ani_class cls, ani_static_field field, ani_float value); + + /** + * @brief Sets a double value to a static field of a class. + * + * This function assigns a double value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The double value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Double)(ani_env *env, ani_class cls, ani_static_field field, ani_double value); + + /** + * @brief Sets a reference value to a static field of a class. + * + * This function assigns a reference value to the specified static field of the given class. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to modify. + * @param[in] value The reference value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticField_Ref)(ani_env *env, ani_class cls, ani_static_field field, ani_ref value); + + /** + * @brief Retrieves a boolean value from a static field of a class by its name. + * + * This function retrieves the boolean value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved boolean value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Boolean)(ani_env *env, ani_class cls, const char *name, + ani_boolean *result); + + /** + * @brief Retrieves a character value from a static field of a class by its name. + * + * This function retrieves the character value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved character value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Char)(ani_env *env, ani_class cls, const char *name, ani_char *result); + + /** + * @brief Retrieves a byte value from a static field of a class by its name. + * + * This function retrieves the byte value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved byte value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Byte)(ani_env *env, ani_class cls, const char *name, ani_byte *result); + + /** + * @brief Retrieves a short value from a static field of a class by its name. + * + * This function retrieves the short value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved short value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Short)(ani_env *env, ani_class cls, const char *name, ani_short *result); + + /** + * @brief Retrieves an integer value from a static field of a class by its name. + * + * This function retrieves the integer value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Int)(ani_env *env, ani_class cls, const char *name, ani_int *result); + + /** + * @brief Retrieves a long value from a static field of a class by its name. + * + * This function retrieves the long value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved long value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Long)(ani_env *env, ani_class cls, const char *name, ani_long *result); + + /** + * @brief Retrieves a float value from a static field of a class by its name. + * + * This function retrieves the float value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved float value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Float)(ani_env *env, ani_class cls, const char *name, ani_float *result); + + /** + * @brief Retrieves a double value from a static field of a class by its name. + * + * This function retrieves the double value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved double value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Double)(ani_env *env, ani_class cls, const char *name, ani_double *result); + + /** + * @brief Retrieves a reference value from a static field of a class by its name. + * + * This function retrieves the reference value of the specified static field from the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to retrieve. + * @param[out] result A pointer to store the retrieved reference value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_GetStaticFieldByName_Ref)(ani_env *env, ani_class cls, const char *name, ani_ref *result); + + /** + * @brief Sets a boolean value to a static field of a class by its name. + * + * This function assigns a boolean value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The boolean value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Boolean)(ani_env *env, ani_class cls, const char *name, ani_boolean value); + + /** + * @brief Sets a character value to a static field of a class by its name. + * + * This function assigns a character value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The character value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Char)(ani_env *env, ani_class cls, const char *name, ani_char value); + + /** + * @brief Sets a byte value to a static field of a class by its name. + * + * This function assigns a byte value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The byte value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Byte)(ani_env *env, ani_class cls, const char *name, ani_byte value); + + /** + * @brief Sets a short value to a static field of a class by its name. + * + * This function assigns a short value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The short value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Short)(ani_env *env, ani_class cls, const char *name, ani_short value); + + /** + * @brief Sets an integer value to a static field of a class by its name. + * + * This function assigns an integer value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The integer value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Int)(ani_env *env, ani_class cls, const char *name, ani_int value); + + /** + * @brief Sets a long value to a static field of a class by its name. + * + * This function assigns a long value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The long value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Long)(ani_env *env, ani_class cls, const char *name, ani_long value); + + /** + * @brief Sets a float value to a static field of a class by its name. + * + * This function assigns a float value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The float value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Float)(ani_env *env, ani_class cls, const char *name, ani_float value); + + /** + * @brief Sets a double value to a static field of a class by its name. + * + * This function assigns a double value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The double value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Double)(ani_env *env, ani_class cls, const char *name, ani_double value); + + /** + * @brief Sets a reference value to a static field of a class by its name. + * + * This function assigns a reference value to the specified static field of the given class by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] name The name of the static field to modify. + * @param[in] value The reference value to assign. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_SetStaticFieldByName_Ref)(ani_env *env, ani_class cls, const char *name, ani_ref value); + + /** + * @brief Calls a static method with a boolean return type. + * + * This function calls the specified static method of a class and retrieves a boolean result using variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Boolean)(ani_env *env, ani_class cls, ani_static_method method, + ani_boolean *result, ...); + + /** + * @brief Calls a static method with a boolean return type (array-based). + * + * This function calls the specified static method of a class and retrieves a boolean result using arguments from an + * array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Boolean_A)(ani_env *env, ani_class cls, ani_static_method method, + ani_boolean *result, const ani_value *args); + + /** + * @brief Calls a static method with a boolean return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves a boolean result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Boolean_V)(ani_env *env, ani_class cls, ani_static_method method, + ani_boolean *result, va_list args); + + /** + * @brief Calls a static method with a character return type. + * + * This function calls the specified static method of a class and retrieves a character result using variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the character result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Char)(ani_env *env, ani_class cls, ani_static_method method, ani_char *result, + ...); + + /** + * @brief Calls a static method with a character return type (array-based). + * + * This function calls the specified static method of a class and retrieves a character result using arguments from + * an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the character result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Char_A)(ani_env *env, ani_class cls, ani_static_method method, ani_char *result, + const ani_value *args); + + /** + * @brief Calls a static method with a character return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves a character result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the character result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Char_V)(ani_env *env, ani_class cls, ani_static_method method, ani_char *result, + va_list args); + + /** + * @brief Calls a static method with a byte return type. + * + * This function calls the specified static method of a class and retrieves a byte result using variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the byte result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Byte)(ani_env *env, ani_class cls, ani_static_method method, ani_byte *result, + ...); + + /** + * @brief Calls a static method with a byte return type (array-based). + * + * This function calls the specified static method of a class and retrieves a byte result using arguments from an + * array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the byte result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Byte_A)(ani_env *env, ani_class cls, ani_static_method method, ani_byte *result, + const ani_value *args); + + /** + * @brief Calls a static method with a byte return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves a byte result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the byte result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Byte_V)(ani_env *env, ani_class cls, ani_static_method method, ani_byte *result, + va_list args); + + /** + * @brief Calls a static method with a short return type. + * + * This function calls the specified static method of a class and retrieves a short result using variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the short result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Short)(ani_env *env, ani_class cls, ani_static_method method, ani_short *result, + ...); + + /** + * @brief Calls a static method with a short return type (array-based). + * + * This function calls the specified static method of a class and retrieves a short result using arguments from an + * array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the short result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Short_A)(ani_env *env, ani_class cls, ani_static_method method, + ani_short *result, const ani_value *args); + + /** + * @brief Calls a static method with a short return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves a short result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the short result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Short_V)(ani_env *env, ani_class cls, ani_static_method method, + ani_short *result, va_list args); + + /** + * @brief Calls a static method with an integer return type. + * + * This function calls the specified static method of a class and retrieves an integer result using variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the integer result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Int)(ani_env *env, ani_class cls, ani_static_method method, ani_int *result, + ...); + + /** + * @brief Calls a static method with an integer return type (array-based). + * + * This function calls the specified static method of a class and retrieves an integer result using arguments from + * an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the integer result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Int_A)(ani_env *env, ani_class cls, ani_static_method method, ani_int *result, + const ani_value *args); + + /** + * @brief Calls a static method with an integer return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves an integer result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the integer result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Int_V)(ani_env *env, ani_class cls, ani_static_method method, ani_int *result, + va_list args); + + /** + * @brief Calls a static method with a long return type. + * + * This function calls the specified static method of a class and retrieves a long result using variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the long result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Long)(ani_env *env, ani_class cls, ani_static_method method, ani_long *result, + ...); + + /** + * @brief Calls a static method with a long return type (array-based). + * + * This function calls the specified static method of a class and retrieves a long result using arguments from an + * array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the long result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Long_A)(ani_env *env, ani_class cls, ani_static_method method, ani_long *result, + const ani_value *args); + + /** + * @brief Calls a static method with a long return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves a long result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the long result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Long_V)(ani_env *env, ani_class cls, ani_static_method method, ani_long *result, + va_list args); + + /** + * @brief Calls a static method with a float return type. + * + * This function calls the specified static method of a class and retrieves a float result using variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the float result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Float)(ani_env *env, ani_class cls, ani_static_method method, ani_float *result, + ...); + + /** + * @brief Calls a static method with a float return type (array-based). + * + * This function calls the specified static method of a class and retrieves a float result using arguments from an + * array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the float result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Float_A)(ani_env *env, ani_class cls, ani_static_method method, + ani_float *result, const ani_value *args); + + /** + * @brief Calls a static method with a float return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves a float result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the float result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Float_V)(ani_env *env, ani_class cls, ani_static_method method, + ani_float *result, va_list args); + + /** + * @brief Calls a static method with a double return type. + * + * This function calls the specified static method of a class and retrieves a double result using variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the double result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Double)(ani_env *env, ani_class cls, ani_static_method method, + ani_double *result, ...); + + /** + * @brief Calls a static method with a double return type (array-based). + * + * This function calls the specified static method of a class and retrieves a double result using arguments from an + * array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the double result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Double_A)(ani_env *env, ani_class cls, ani_static_method method, + ani_double *result, const ani_value *args); + + /** + * @brief Calls a static method with a double return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves a double result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the double result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Double_V)(ani_env *env, ani_class cls, ani_static_method method, + ani_double *result, va_list args); + + /** + * @brief Calls a static method with a reference return type. + * + * This function calls the specified static method of a class and retrieves a reference result using variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the reference result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Ref)(ani_env *env, ani_class cls, ani_static_method method, ani_ref *result, + ...); + + /** + * @brief Calls a static method with a reference return type (array-based). + * + * This function calls the specified static method of a class and retrieves a reference result using arguments from + * an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the reference result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Ref_A)(ani_env *env, ani_class cls, ani_static_method method, ani_ref *result, + const ani_value *args); + + /** + * @brief Calls a static method with a reference return type (variadic arguments). + * + * This function calls the specified static method of a class and retrieves a reference result using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[out] result A pointer to store the reference result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Ref_V)(ani_env *env, ani_class cls, ani_static_method method, ani_ref *result, + va_list args); + + /** + * @brief Calls a static method with no return value. + * + * This function calls the specified static method of a class using variadic arguments. The method does not return a + * value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Void)(ani_env *env, ani_class cls, ani_static_method method, ...); + + /** + * @brief Calls a static method with no return value (array-based). + * + * This function calls the specified static method of a class using arguments from an array. The method does not + * return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Void_A)(ani_env *env, ani_class cls, ani_static_method method, + const ani_value *args); + + /** + * @brief Calls a static method with no return value (variadic arguments). + * + * This function calls the specified static method of a class using a `va_list`. The method does not return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to call. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethod_Void_V)(ani_env *env, ani_class cls, ani_static_method method, va_list args); + + /** + * @brief Calls a static method by name with a boolean return type. + * + * This function calls the specified static method of a class by its name and retrieves a boolean result using + * variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Boolean)(ani_env *env, ani_class cls, const char *name, + ani_boolean *result, ...); + + /** + * @brief Calls a static method by name with a boolean return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a boolean result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Boolean_A)(ani_env *env, ani_class cls, const char *name, + ani_boolean *result, const ani_value *args); + + /** + * @brief Calls a static method by name with a boolean return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a boolean result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the boolean result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Boolean_V)(ani_env *env, ani_class cls, const char *name, + ani_boolean *result, va_list args); + + /** + * @brief Calls a static method by name with a char return type. + * + * This function calls the specified static method of a class by its name and retrieves a char result using variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the char result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Char)(ani_env *env, ani_class cls, const char *name, ani_char *result, + ...); + + /** + * @brief Calls a static method by name with a char return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a char result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the char result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Char_A)(ani_env *env, ani_class cls, const char *name, ani_char *result, + const ani_value *args); + + /** + * @brief Calls a static method by name with a char return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a char result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the char result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Char_V)(ani_env *env, ani_class cls, const char *name, ani_char *result, + va_list args); + + /** + * @brief Calls a static method by name with a byte return type. + * + * This function calls the specified static method of a class by its name and retrieves a byte result using variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the byte result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Byte)(ani_env *env, ani_class cls, const char *name, ani_byte *result, + ...); + + /** + * @brief Calls a static method by name with a byte return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a byte result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the byte result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Byte_A)(ani_env *env, ani_class cls, const char *name, ani_byte *result, + const ani_value *args); + + /** + * @brief Calls a static method by name with a byte return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a byte result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the byte result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Byte_V)(ani_env *env, ani_class cls, const char *name, ani_byte *result, + va_list args); + + /** + * @brief Calls a static method by name with a short return type. + * + * This function calls the specified static method of a class by its name and retrieves a short result using + * variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the short result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Short)(ani_env *env, ani_class cls, const char *name, ani_short *result, + ...); + + /** + * @brief Calls a static method by name with a short return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a short result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the short result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Short_A)(ani_env *env, ani_class cls, const char *name, ani_short *result, + const ani_value *args); + + /** + * @brief Calls a static method by name with a short return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a short result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the short result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Short_V)(ani_env *env, ani_class cls, const char *name, ani_short *result, + va_list args); + + /** + * @brief Calls a static method by name with a integer return type. + * + * This function calls the specified static method of a class by its name and retrieves a integer result using + * variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the integer result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Int)(ani_env *env, ani_class cls, const char *name, ani_int *result, ...); + + /** + * @brief Calls a static method by name with a integer return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a integer result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the integer result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Int_A)(ani_env *env, ani_class cls, const char *name, ani_int *result, + const ani_value *args); + + /** + * @brief Calls a static method by name with a integer return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a integer result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the integer result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Int_V)(ani_env *env, ani_class cls, const char *name, ani_int *result, + va_list args); + + /** + * @brief Calls a static method by name with a long return type. + * + * This function calls the specified static method of a class by its name and retrieves a long result using variadic + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the long result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Long)(ani_env *env, ani_class cls, const char *name, ani_long *result, + ...); + + /** + * @brief Calls a static method by name with a long return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a long result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the long result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Long_A)(ani_env *env, ani_class cls, const char *name, ani_long *result, + const ani_value *args); + + /** + * @brief Calls a static method by name with a long return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a long result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the long result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Long_V)(ani_env *env, ani_class cls, const char *name, ani_long *result, + va_list args); + + /** + * @brief Calls a static method by name with a float return type. + * + * This function calls the specified static method of a class by its name and retrieves a float result using + * variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the float result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Float)(ani_env *env, ani_class cls, const char *name, ani_float *result, + ...); + + /** + * @brief Calls a static method by name with a float return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a float result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the float result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Float_A)(ani_env *env, ani_class cls, const char *name, ani_float *result, + const ani_value *args); + + /** + * @brief Calls a static method by name with a float return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a float result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the float result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Float_V)(ani_env *env, ani_class cls, const char *name, ani_float *result, + va_list args); + + /** + * @brief Calls a static method by name with a double return type. + * + * This function calls the specified static method of a class by its name and retrieves a double result using + * variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the double result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Double)(ani_env *env, ani_class cls, const char *name, ani_double *result, + ...); + + /** + * @brief Calls a static method by name with a double return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a double result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the double result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Double_A)(ani_env *env, ani_class cls, const char *name, + ani_double *result, const ani_value *args); + + /** + * @brief Calls a static method by name with a double return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a double result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the double result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Double_V)(ani_env *env, ani_class cls, const char *name, + ani_double *result, va_list args); + + /** + * @brief Calls a static method by name with a reference return type. + * + * This function calls the specified static method of a class by its name and retrieves a reference result using + * variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the reference result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Ref)(ani_env *env, ani_class cls, const char *name, ani_ref *result, ...); + + /** + * @brief Calls a static method by name with a reference return type (array-based). + * + * This function calls the specified static method of a class by its name and retrieves a reference result using + * arguments from an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the reference result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Ref_A)(ani_env *env, ani_class cls, const char *name, ani_ref *result, + const ani_value *args); + + /** + * @brief Calls a static method by name with a reference return type (variadic arguments). + * + * This function calls the specified static method of a class by its name and retrieves a reference result using a + * `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[out] result A pointer to store the reference result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Ref_V)(ani_env *env, ani_class cls, const char *name, ani_ref *result, + va_list args); + + /** + * @brief Calls a static method by name with no return value. + * + * This function calls the specified static method of a class by its name using variadic arguments. The method does + * not return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Void)(ani_env *env, ani_class cls, const char *name, ...); + + /** + * @brief Calls a static method by name with no return value (array-based). + * + * This function calls the specified static method of a class by its name using arguments from an array. The method + * does not return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Void_A)(ani_env *env, ani_class cls, const char *name, + const ani_value *args); + + /** + * @brief Calls a static method by name with no return value (variadic arguments). + * + * This function calls the specified static method of a class by its name using a `va_list`. The method does not + * return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] name The name of the static method to call. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Class_CallStaticMethodByName_Void_V)(ani_env *env, ani_class cls, const char *name, va_list args); + + /** + * @brief Retrieves a boolean value from a field of an object. + * + * This function retrieves the boolean value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the boolean value from. + * @param[out] result A pointer to store the retrieved boolean value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Boolean)(ani_env *env, ani_object object, ani_field field, ani_boolean *result); + + /** + * @brief Retrieves a char value from a field of an object. + * + * This function retrieves the char value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the char value from. + * @param[out] result A pointer to store the retrieved char value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Char)(ani_env *env, ani_object object, ani_field field, ani_char *result); + + /** + * @brief Retrieves a byte value from a field of an object. + * + * This function retrieves the byte value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the byte value from. + * @param[out] result A pointer to store the retrieved byte value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Byte)(ani_env *env, ani_object object, ani_field field, ani_byte *result); + + /** + * @brief Retrieves a short value from a field of an object. + * + * This function retrieves the short value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the short value from. + * @param[out] result A pointer to store the retrieved short value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Short)(ani_env *env, ani_object object, ani_field field, ani_short *result); + + /** + * @brief Retrieves a integer value from a field of an object. + * + * This function retrieves the integer value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the integer value from. + * @param[out] result A pointer to store the retrieved integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Int)(ani_env *env, ani_object object, ani_field field, ani_int *result); + + /** + * @brief Retrieves a long value from a field of an object. + * + * This function retrieves the long value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the long value from. + * @param[out] result A pointer to store the retrieved long value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Long)(ani_env *env, ani_object object, ani_field field, ani_long *result); + + /** + * @brief Retrieves a float value from a field of an object. + * + * This function retrieves the float value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the float value from. + * @param[out] result A pointer to store the retrieved float value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Float)(ani_env *env, ani_object object, ani_field field, ani_float *result); + + /** + * @brief Retrieves a double value from a field of an object. + * + * This function retrieves the double value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the double value from. + * @param[out] result A pointer to store the retrieved double value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Double)(ani_env *env, ani_object object, ani_field field, ani_double *result); + + /** + * @brief Retrieves a reference value from a field of an object. + * + * This function retrieves the reference value of the specified field from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to retrieve the reference value from. + * @param[out] result A pointer to store the retrieved reference value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetField_Ref)(ani_env *env, ani_object object, ani_field field, ani_ref *result); + + /** + * @brief Sets a boolean value to a field of an object. + * + * This function assigns a boolean value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the boolean value to. + * @param[in] value The boolean value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Boolean)(ani_env *env, ani_object object, ani_field field, ani_boolean value); + + /** + * @brief Sets a char value to a field of an object. + * + * This function assigns a char value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the char value to. + * @param[in] value The char value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Char)(ani_env *env, ani_object object, ani_field field, ani_char value); + + /** + * @brief Sets a byte value to a field of an object. + * + * This function assigns a byte value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the byte value to. + * @param[in] value The byte value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Byte)(ani_env *env, ani_object object, ani_field field, ani_byte value); + + /** + * @brief Sets a short value to a field of an object. + * + * This function assigns a short value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the short value to. + * @param[in] value The short value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Short)(ani_env *env, ani_object object, ani_field field, ani_short value); + + /** + * @brief Sets a integer value to a field of an object. + * + * This function assigns a integer value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the integer value to. + * @param[in] value The integer value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Int)(ani_env *env, ani_object object, ani_field field, ani_int value); + + /** + * @brief Sets a long value to a field of an object. + * + * This function assigns a long value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the long value to. + * @param[in] value The long value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Long)(ani_env *env, ani_object object, ani_field field, ani_long value); + + /** + * @brief Sets a float value to a field of an object. + * + * This function assigns a float value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the float value to. + * @param[in] value The float value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Float)(ani_env *env, ani_object object, ani_field field, ani_float value); + + /** + * @brief Sets a double value to a field of an object. + * + * This function assigns a double value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the double value to. + * @param[in] value The double value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Double)(ani_env *env, ani_object object, ani_field field, ani_double value); + + /** + * @brief Sets a reference value to a field of an object. + * + * This function assigns a reference value to the specified field of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] field The field to set the reference value to. + * @param[in] value The reference value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetField_Ref)(ani_env *env, ani_object object, ani_field field, ani_ref value); + + /** + * @brief Retrieves a boolean value from a field of an object by its name. + * + * This function retrieves the boolean value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the boolean value from. + * @param[out] result A pointer to store the retrieved boolean value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Boolean)(ani_env *env, ani_object object, const char *name, ani_boolean *result); + + /** + * @brief Retrieves a char value from a field of an object by its name. + * + * This function retrieves the char value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the char value from. + * @param[out] result A pointer to store the retrieved char value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Char)(ani_env *env, ani_object object, const char *name, ani_char *result); + + /** + * @brief Retrieves a byte value from a field of an object by its name. + * + * This function retrieves the byte value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the byte value from. + * @param[out] result A pointer to store the retrieved byte value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Byte)(ani_env *env, ani_object object, const char *name, ani_byte *result); + + /** + * @brief Retrieves a short value from a field of an object by its name. + * + * This function retrieves the short value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the short value from. + * @param[out] result A pointer to store the retrieved short value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Short)(ani_env *env, ani_object object, const char *name, ani_short *result); + + /** + * @brief Retrieves a integer value from a field of an object by its name. + * + * This function retrieves the integer value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the integer value from. + * @param[out] result A pointer to store the retrieved integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Int)(ani_env *env, ani_object object, const char *name, ani_int *result); + + /** + * @brief Retrieves a long value from a field of an object by its name. + * + * This function retrieves the long value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the long value from. + * @param[out] result A pointer to store the retrieved long value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Long)(ani_env *env, ani_object object, const char *name, ani_long *result); + + /** + * @brief Retrieves a float value from a field of an object by its name. + * + * This function retrieves the float value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the float value from. + * @param[out] result A pointer to store the retrieved float value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Float)(ani_env *env, ani_object object, const char *name, ani_float *result); + + /** + * @brief Retrieves a double value from a field of an object by its name. + * + * This function retrieves the double value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the double value from. + * @param[out] result A pointer to store the retrieved double value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Double)(ani_env *env, ani_object object, const char *name, ani_double *result); + + /** + * @brief Retrieves a reference value from a field of an object by its name. + * + * This function retrieves the reference value of the specified field from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to retrieve the reference value from. + * @param[out] result A pointer to store the retrieved reference value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetFieldByName_Ref)(ani_env *env, ani_object object, const char *name, ani_ref *result); + + /** + * @brief Sets a boolean value to a field of an object by its name. + * + * This function assigns a boolean value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the boolean value to. + * @param[in] value The boolean value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Boolean)(ani_env *env, ani_object object, const char *name, ani_boolean value); + + /** + * @brief Sets a char value to a field of an object by its name. + * + * This function assigns a char value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the char value to. + * @param[in] value The char value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Char)(ani_env *env, ani_object object, const char *name, ani_char value); + + /** + * @brief Sets a byte value to a field of an object by its name. + * + * This function assigns a byte value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the byte value to. + * @param[in] value The byte value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Byte)(ani_env *env, ani_object object, const char *name, ani_byte value); + + /** + * @brief Sets a short value to a field of an object by its name. + * + * This function assigns a short value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the short value to. + * @param[in] value The short value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Short)(ani_env *env, ani_object object, const char *name, ani_short value); + + /** + * @brief Sets a integer value to a field of an object by its name. + * + * This function assigns a integer value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the integer value to. + * @param[in] value The integer value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Int)(ani_env *env, ani_object object, const char *name, ani_int value); + + /** + * @brief Sets a long value to a field of an object by its name. + * + * This function assigns a long value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the long value to. + * @param[in] value The long value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Long)(ani_env *env, ani_object object, const char *name, ani_long value); + + /** + * @brief Sets a float value to a field of an object by its name. + * + * This function assigns a float value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the float value to. + * @param[in] value The float value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Float)(ani_env *env, ani_object object, const char *name, ani_float value); + + /** + * @brief Sets a double value to a field of an object by its name. + * + * This function assigns a double value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the double value to. + * @param[in] value The double value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Double)(ani_env *env, ani_object object, const char *name, ani_double value); + + /** + * @brief Sets a reference value to a field of an object by its name. + * + * This function assigns a reference value to the specified field of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the field. + * @param[in] name The name of the field to set the reference value to. + * @param[in] value The reference value to assign to the field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetFieldByName_Ref)(ani_env *env, ani_object object, const char *name, ani_ref value); + + /** + * @brief Retrieves a boolean value from a property of an object. + * + * This function retrieves the boolean value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the boolean value from. + * @param[out] result A pointer to store the retrieved boolean value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Boolean)(ani_env *env, ani_object object, ani_property property, + ani_boolean *result); + + /** + * @brief Retrieves a char value from a property of an object. + * + * This function retrieves the char value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the char value from. + * @param[out] result A pointer to store the retrieved char value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Char)(ani_env *env, ani_object object, ani_property property, ani_char *result); + + /** + * @brief Retrieves a byte value from a property of an object. + * + * This function retrieves the byte value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the byte value from. + * @param[out] result A pointer to store the retrieved byte value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Byte)(ani_env *env, ani_object object, ani_property property, ani_byte *result); + + /** + * @brief Retrieves a short value from a property of an object. + * + * This function retrieves the short value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the short value from. + * @param[out] result A pointer to store the retrieved short value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Short)(ani_env *env, ani_object object, ani_property property, ani_short *result); + + /** + * @brief Retrieves a integer value from a property of an object. + * + * This function retrieves the integer value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the integer value from. + * @param[out] result A pointer to store the retrieved integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Int)(ani_env *env, ani_object object, ani_property property, ani_int *result); + + /** + * @brief Retrieves a long value from a property of an object. + * + * This function retrieves the long value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the long value from. + * @param[out] result A pointer to store the retrieved long value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Long)(ani_env *env, ani_object object, ani_property property, ani_long *result); + + /** + * @brief Retrieves a float value from a property of an object. + * + * This function retrieves the float value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the float value from. + * @param[out] result A pointer to store the retrieved float value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Float)(ani_env *env, ani_object object, ani_property property, ani_float *result); + + /** + * @brief Retrieves a double value from a property of an object. + * + * This function retrieves the double value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the double value from. + * @param[out] result A pointer to store the retrieved double value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Double)(ani_env *env, ani_object object, ani_property property, ani_double *result); + + /** + * @brief Retrieves a reference value from a property of an object. + * + * This function retrieves the reference value of the specified property from the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to retrieve the reference value from. + * @param[out] result A pointer to store the retrieved reference value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetProperty_Ref)(ani_env *env, ani_object object, ani_property property, ani_ref *result); + + /** + * @brief Sets a boolean value to a property of an object. + * + * This function assigns a boolean value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the boolean value to. + * @param[in] value The boolean value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Boolean)(ani_env *env, ani_object object, ani_property property, ani_boolean value); + + /** + * @brief Sets a char value to a property of an object. + * + * This function assigns a char value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the char value to. + * @param[in] value The char value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Char)(ani_env *env, ani_object object, ani_property property, ani_char value); + + /** + * @brief Sets a byte value to a property of an object. + * + * This function assigns a byte value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the byte value to. + * @param[in] value The byte value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Byte)(ani_env *env, ani_object object, ani_property property, ani_byte value); + + /** + * @brief Sets a short value to a property of an object. + * + * This function assigns a short value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the short value to. + * @param[in] value The short value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Short)(ani_env *env, ani_object object, ani_property property, ani_short value); + + /** + * @brief Sets a integer value to a property of an object. + * + * This function assigns a integer value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the integer value to. + * @param[in] value The integer value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Int)(ani_env *env, ani_object object, ani_property property, ani_int value); + + /** + * @brief Sets a long value to a property of an object. + * + * This function assigns a long value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the long value to. + * @param[in] value The long value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Long)(ani_env *env, ani_object object, ani_property property, ani_long value); + + /** + * @brief Sets a float value to a property of an object. + * + * This function assigns a float value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the float value to. + * @param[in] value The float value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Float)(ani_env *env, ani_object object, ani_property property, ani_float value); + + /** + * @brief Sets a double value to a property of an object. + * + * This function assigns a double value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the double value to. + * @param[in] value The double value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Double)(ani_env *env, ani_object object, ani_property property, ani_double value); + + /** + * @brief Sets a reference value to a property of an object. + * + * This function assigns a reference value to the specified property of the given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] property The property to set the reference value to. + * @param[in] value The reference value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetProperty_Ref)(ani_env *env, ani_object object, ani_property property, ani_ref value); + + /** + * @brief Retrieves a boolean value from a property of an object by its name. + * + * This function retrieves the boolean value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the boolean value from. + * @param[out] result A pointer to store the retrieved boolean value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Boolean)(ani_env *env, ani_object object, const char *name, + ani_boolean *result); + + /** + * @brief Retrieves a char value from a property of an object by its name. + * + * This function retrieves the char value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the char value from. + * @param[out] result A pointer to store the retrieved char value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Char)(ani_env *env, ani_object object, const char *name, ani_char *result); + + /** + * @brief Retrieves a byte value from a property of an object by its name. + * + * This function retrieves the byte value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the byte value from. + * @param[out] result A pointer to store the retrieved byte value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Byte)(ani_env *env, ani_object object, const char *name, ani_byte *result); + + /** + * @brief Retrieves a short value from a property of an object by its name. + * + * This function retrieves the short value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the short value from. + * @param[out] result A pointer to store the retrieved short value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Short)(ani_env *env, ani_object object, const char *name, ani_short *result); + + /** + * @brief Retrieves a integer value from a property of an object by its name. + * + * This function retrieves the integer value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the integer value from. + * @param[out] result A pointer to store the retrieved integer value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Int)(ani_env *env, ani_object object, const char *name, ani_int *result); + + /** + * @brief Retrieves a long value from a property of an object by its name. + * + * This function retrieves the long value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the long value from. + * @param[out] result A pointer to store the retrieved long value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Long)(ani_env *env, ani_object object, const char *name, ani_long *result); + + /** + * @brief Retrieves a float value from a property of an object by its name. + * + * This function retrieves the float value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the float value from. + * @param[out] result A pointer to store the retrieved float value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Float)(ani_env *env, ani_object object, const char *name, ani_float *result); + + /** + * @brief Retrieves a double value from a property of an object by its name. + * + * This function retrieves the double value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the double value from. + * @param[out] result A pointer to store the retrieved double value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Double)(ani_env *env, ani_object object, const char *name, + ani_double *result); + + /** + * @brief Retrieves a reference value from a property of an object by its name. + * + * This function retrieves the reference value of the specified property from the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to retrieve the reference value from. + * @param[out] result A pointer to store the retrieved reference value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_GetPropertyByName_Ref)(ani_env *env, ani_object object, const char *name, ani_ref *result); + + /** + * @brief Sets a boolean value to a property of an object by its name. + * + * This function assigns a boolean value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the boolean value to. + * @param[in] value The boolean value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Boolean)(ani_env *env, ani_object object, const char *name, + ani_boolean value); + + /** + * @brief Sets a char value to a property of an object by its name. + * + * This function assigns a char value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the char value to. + * @param[in] value The char value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Char)(ani_env *env, ani_object object, const char *name, ani_char value); + + /** + * @brief Sets a byte value to a property of an object by its name. + * + * This function assigns a byte value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the byte value to. + * @param[in] value The byte value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Byte)(ani_env *env, ani_object object, const char *name, ani_byte value); + + /** + * @brief Sets a short value to a property of an object by its name. + * + * This function assigns a short value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the short value to. + * @param[in] value The short value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Short)(ani_env *env, ani_object object, const char *name, ani_short value); + + /** + * @brief Sets a integer value to a property of an object by its name. + * + * This function assigns a integer value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the integer value to. + * @param[in] value The integer value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Int)(ani_env *env, ani_object object, const char *name, ani_int value); + + /** + * @brief Sets a long value to a property of an object by its name. + * + * This function assigns a long value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the long value to. + * @param[in] value The long value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Long)(ani_env *env, ani_object object, const char *name, ani_long value); + + /** + * @brief Sets a float value to a property of an object by its name. + * + * This function assigns a float value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the float value to. + * @param[in] value The float value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Float)(ani_env *env, ani_object object, const char *name, ani_float value); + + /** + * @brief Sets a double value to a property of an object by its name. + * + * This function assigns a double value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the double value to. + * @param[in] value The double value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Double)(ani_env *env, ani_object object, const char *name, ani_double value); + + /** + * @brief Sets a reference value to a property of an object by its name. + * + * This function assigns a reference value to the specified property of the given object by its name. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object containing the property. + * @param[in] name The name of the property to set the reference value to. + * @param[in] value The reference value to assign to the property. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_SetPropertyByName_Ref)(ani_env *env, ani_object object, const char *name, ani_ref value); + + /** + * @brief Calls a method on an object and retrieves a boolean return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the boolean return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Boolean)(ani_env *env, ani_object object, ani_method method, ani_boolean *result, + ...); + + /** + * @brief Calls a method on an object and retrieves a boolean return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a + * boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the boolean return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Boolean_A)(ani_env *env, ani_object object, ani_method method, ani_boolean *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a boolean return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the boolean return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Boolean_V)(ani_env *env, ani_object object, ani_method method, ani_boolean *result, + va_list args); + + /** + * @brief Calls a method on an object and retrieves a char return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a char result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the char return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Char)(ani_env *env, ani_object object, ani_method method, ani_char *result, ...); + + /** + * @brief Calls a method on an object and retrieves a char return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a char + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the char return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Char_A)(ani_env *env, ani_object object, ani_method method, ani_char *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a char return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a char result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the char return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Char_V)(ani_env *env, ani_object object, ani_method method, ani_char *result, + va_list args); + + /** + * @brief Calls a method on an object and retrieves a byte return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a byte result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the byte return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Byte)(ani_env *env, ani_object object, ani_method method, ani_byte *result, ...); + + /** + * @brief Calls a method on an object and retrieves a byte return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a byte + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the byte return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Byte_A)(ani_env *env, ani_object object, ani_method method, ani_byte *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a byte return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a byte result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the byte return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Byte_V)(ani_env *env, ani_object object, ani_method method, ani_byte *result, + va_list args); + + /** + * @brief Calls a method on an object and retrieves a short return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a short result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the short return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Short)(ani_env *env, ani_object object, ani_method method, ani_short *result, ...); + + /** + * @brief Calls a method on an object and retrieves a short return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a short + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the short return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Short_A)(ani_env *env, ani_object object, ani_method method, ani_short *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a short return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a short result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the short return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Short_V)(ani_env *env, ani_object object, ani_method method, ani_short *result, + va_list args); + + /** + * @brief Calls a method on an object and retrieves a integer return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a integer result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the integer return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Int)(ani_env *env, ani_object object, ani_method method, ani_int *result, ...); + + /** + * @brief Calls a method on an object and retrieves a integer return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a + * integer result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the integer return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Int_A)(ani_env *env, ani_object object, ani_method method, ani_int *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a integer return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a integer result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the integer return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Int_V)(ani_env *env, ani_object object, ani_method method, ani_int *result, + va_list args); + + /** + * @brief Calls a method on an object and retrieves a long return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a long result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the long return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Long)(ani_env *env, ani_object object, ani_method method, ani_long *result, ...); + + /** + * @brief Calls a method on an object and retrieves a long return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a long + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the long return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Long_A)(ani_env *env, ani_object object, ani_method method, ani_long *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a long return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a long result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the long return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Long_V)(ani_env *env, ani_object object, ani_method method, ani_long *result, + va_list args); + + /** + * @brief Calls a method on an object and retrieves a float return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a float result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the float return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Float)(ani_env *env, ani_object object, ani_method method, ani_float *result, ...); + + /** + * @brief Calls a method on an object and retrieves a float return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a float + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the float return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Float_A)(ani_env *env, ani_object object, ani_method method, ani_float *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a float return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a float result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the float return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Float_V)(ani_env *env, ani_object object, ani_method method, ani_float *result, + va_list args); + + /** + * @brief Calls a method on an object and retrieves a double return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a double result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the double return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Double)(ani_env *env, ani_object object, ani_method method, ani_double *result, ...); + + /** + * @brief Calls a method on an object and retrieves a double return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a double + * result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the double return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Double_A)(ani_env *env, ani_object object, ani_method method, ani_double *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a double return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a double result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the double return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Double_V)(ani_env *env, ani_object object, ani_method method, ani_double *result, + va_list args); + + /** + * @brief Calls a method on an object and retrieves a reference return value. + * + * This function calls the specified method of an object using variadic arguments and retrieves a reference result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the reference return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Ref)(ani_env *env, ani_object object, ani_method method, ani_ref *result, ...); + + /** + * @brief Calls a method on an object and retrieves a reference return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array and retrieves a + * reference result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the reference return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Ref_A)(ani_env *env, ani_object object, ani_method method, ani_ref *result, + const ani_value *args); + + /** + * @brief Calls a method on an object and retrieves a reference return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list` and retrieves a reference result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[out] result A pointer to store the reference return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Ref_V)(ani_env *env, ani_object object, ani_method method, ani_ref *result, + va_list args); + + /** + * @brief Calls a method on an object with no return value. + * + * This function calls the specified method of an object using variadic arguments. The method does not return a + * value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Void)(ani_env *env, ani_object object, ani_method method, ...); + + /** + * @brief Calls a method on an object with no return value (array-based). + * + * This function calls the specified method of an object using arguments provided in an array. The method does not + * return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Void_A)(ani_env *env, ani_object object, ani_method method, const ani_value *args); + + /** + * @brief Calls a method on an object with no return value (variadic arguments). + * + * This function calls the specified method of an object using a `va_list`. The method does not return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] method The method to call. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethod_Void_V)(ani_env *env, ani_object object, ani_method method, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a boolean return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the boolean return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Boolean)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_boolean *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a boolean return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the boolean return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Boolean_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_boolean *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a boolean return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * boolean result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the boolean return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Boolean_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_boolean *result, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a char return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a char result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the char return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Char)(ani_env *env, ani_object object, const char *name, const char *signature, + ani_char *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a char return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a char result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the char return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Char_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_char *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a char return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * char result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the char return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Char_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_char *result, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a byte return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a byte result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the byte return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Byte)(ani_env *env, ani_object object, const char *name, const char *signature, + ani_byte *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a byte return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a byte result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the byte return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Byte_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_byte *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a byte return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * byte result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the byte return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Byte_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_byte *result, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a short return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a short result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the short return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Short)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_short *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a short return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a short result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the short return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Short_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_short *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a short return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * short result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the short return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Short_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_short *result, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a integer return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a integer result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the integer return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Int)(ani_env *env, ani_object object, const char *name, const char *signature, + ani_int *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a integer return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a integer result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the integer return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Int_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_int *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a integer return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * integer result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the integer return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Int_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_int *result, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a long return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a long result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the long return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Long)(ani_env *env, ani_object object, const char *name, const char *signature, + ani_long *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a long return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a long result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the long return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Long_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_long *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a long return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * long result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the long return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Long_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_long *result, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a float return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a float result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the float return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Float)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_float *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a float return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a float result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the float return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Float_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_float *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a float return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * float result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the float return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Float_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_float *result, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a double return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a double result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the double return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Double)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_double *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a double return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a double result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the double return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Double_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_double *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a double return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * double result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the double return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Double_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_double *result, va_list args); + + /** + * @brief Calls a method by name on an object and retrieves a reference return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments and + * retrieves a reference result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the reference return value. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Ref)(ani_env *env, ani_object object, const char *name, const char *signature, + ani_ref *result, ...); + + /** + * @brief Calls a method by name on an object and retrieves a reference return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array and retrieves a reference result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the reference return value. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Ref_A)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_ref *result, const ani_value *args); + + /** + * @brief Calls a method by name on an object and retrieves a reference return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list` and retrieves a + * reference result. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[out] result A pointer to store the reference return value. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Ref_V)(ani_env *env, ani_object object, const char *name, + const char *signature, ani_ref *result, va_list args); + + /** + * @brief Calls a method by name on an object with no return value. + * + * This function calls the specified method by its name and signature on an object using variadic arguments. The + * method does not return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Void)(ani_env *env, ani_object object, const char *name, const char *signature, + ...); + + /** + * @brief Calls a method by name on an object with no return value (array-based). + * + * This function calls the specified method by its name and signature on an object using arguments provided in an + * array. The method does not return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Void_A)(ani_env *env, ani_object object, const char *name, + const char *signature, const ani_value *args); + + /** + * @brief Calls a method by name on an object with no return value (variadic arguments). + * + * This function calls the specified method by its name and signature on an object using a `va_list`. The method + * does not return a value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] object The object on which the method is to be called. + * @param[in] name The name of the method to call. + * @param[in] signature The signature of the method to call. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Object_CallMethodByName_Void_V)(ani_env *env, ani_object object, const char *name, + const char *signature, va_list args); + + /** + * @brief Creates a new tuple value. + * + * This function creates a new value for the specified tuple using variadic arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple The tuple for which to create a new value. + * @param[out] result A pointer to store the new tuple value. + * @param[in] ... Variadic arguments to initialize the tuple value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Tuple_NewTupleValue)(ani_env *env, ani_tuple tuple, ani_tuple_value *result, ...); + + /** + * @brief Creates a new tuple value (array-based). + * + * This function creates a new value for the specified tuple using arguments provided in an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple The tuple for which to create a new value. + * @param[out] result A pointer to store the new tuple value. + * @param[in] args An array of arguments to initialize the tuple value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Tuple_NewTupleValue_A)(ani_env *env, ani_tuple tuple, ani_tuple_value *result, const ani_value *args); + + /** + * @brief Creates a new tuple value (variadic arguments). + * + * This function creates a new value for the specified tuple using a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple The tuple for which to create a new value. + * @param[out] result A pointer to store the new tuple value. + * @param[in] args A `va_list` of arguments to initialize the tuple value. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Tuple_NewTupleValue_V)(ani_env *env, ani_tuple tuple, ani_tuple_value *result, va_list args); + + /** + * @brief Retrieves the number of items in a tuple. + * + * This function retrieves the total number of items in the specified tuple. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple The tuple whose number of items is to be retrieved. + * @param[out] result A pointer to store the number of items. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Tuple_GetNumberOfItems)(ani_env *env, ani_tuple tuple, ani_size *result); + + /** + * @brief Retrieves the kind of an item in a tuple. + * + * This function retrieves the kind of the item at the specified index in the tuple. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple The tuple containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the kind of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Tuple_GetItemKind)(ani_env *env, ani_tuple tuple, ani_size index, ani_kind *result); + + /** + * @brief Retrieves the type of an item in a tuple. + * + * This function retrieves the type of the item at the specified index in the tuple. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple The tuple containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the type of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Tuple_GetItemType)(ani_env *env, ani_tuple tuple, ani_size index, ani_type *result); + + /** + * @brief Retrieves the tuple associated with a tuple value. + * + * This function retrieves the tuple that corresponds to the specified tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] value The tuple value to query. + * @param[out] result A pointer to store the associated tuple. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetTuple)(ani_env *env, ani_tuple_value value, ani_tuple *result); + + /** + * @brief Retrieves a boolean item from a tuple value. + * + * This function retrieves the boolean value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the boolean value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Boolean)(ani_env *env, ani_tuple_value tuple_value, ani_size index, + ani_boolean *result); + + /** + * @brief Retrieves a char item from a tuple value. + * + * This function retrieves the char value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the char value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Char)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_char *result); + + /** + * @brief Retrieves a byte item from a tuple value. + * + * This function retrieves the byte value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the byte value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Byte)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_byte *result); + + /** + * @brief Retrieves a short item from a tuple value. + * + * This function retrieves the short value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the short value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Short)(ani_env *env, ani_tuple_value tuple_value, ani_size index, + ani_short *result); + + /** + * @brief Retrieves a integer item from a tuple value. + * + * This function retrieves the integer value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the integer value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Int)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_int *result); + + /** + * @brief Retrieves a long item from a tuple value. + * + * This function retrieves the long value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the long value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Long)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_long *result); + + /** + * @brief Retrieves a float item from a tuple value. + * + * This function retrieves the float value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the float value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Float)(ani_env *env, ani_tuple_value tuple_value, ani_size index, + ani_float *result); + + /** + * @brief Retrieves a double item from a tuple value. + * + * This function retrieves the double value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the double value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Double)(ani_env *env, ani_tuple_value tuple_value, ani_size index, + ani_double *result); + + /** + * @brief Retrieves a reference item from a tuple value. + * + * This function retrieves the reference value of the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[out] result A pointer to store the reference value of the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_GetItem_Ref)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_ref *result); + + /** + * @brief Sets a boolean value to an item in a tuple value. + * + * This function assigns a boolean value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The boolean value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Boolean)(ani_env *env, ani_tuple_value tuple_value, ani_size index, + ani_boolean value); + + /** + * @brief Sets a char value to an item in a tuple value. + * + * This function assigns a char value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The char value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Char)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_char value); + + /** + * @brief Sets a byte value to an item in a tuple value. + * + * This function assigns a byte value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The byte value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Byte)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_byte value); + + /** + * @brief Sets a short value to an item in a tuple value. + * + * This function assigns a short value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The short value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Short)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_short value); + + /** + * @brief Sets a integer value to an item in a tuple value. + * + * This function assigns a integer value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The integer value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Int)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_int value); + + /** + * @brief Sets a long value to an item in a tuple value. + * + * This function assigns a long value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The long value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Long)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_long value); + + /** + * @brief Sets a float value to an item in a tuple value. + * + * This function assigns a float value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The float value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Float)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_float value); + + /** + * @brief Sets a double value to an item in a tuple value. + * + * This function assigns a double value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The double value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Double)(ani_env *env, ani_tuple_value tuple_value, ani_size index, + ani_double value); + + /** + * @brief Sets a reference value to an item in a tuple value. + * + * This function assigns a reference value to the item at the specified index in the tuple value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] tuple_value The tuple value containing the item. + * @param[in] index The index of the item. + * @param[in] value The reference value to assign to the item. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*TupleValue_SetItem_Ref)(ani_env *env, ani_tuple_value tuple_value, ani_size index, ani_ref value); + + /** + * @brief Creates a global reference. + * + * This function creates a global reference from a local reference. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The local reference to convert to a global reference. + * @param[out] result A pointer to store the created global reference. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*GlobalReference_Create)(ani_env *env, ani_ref ref, ani_gref *result); + + /** + * @brief Deletes a global reference. + * + * This function deletes the specified global reference, releasing all associated resources. + * + * @param[in] env A pointer to the environment structure. + * @param[in] gref The global reference to delete. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*GlobalReference_Delete)(ani_env *env, ani_gref gref); + + /** + * @brief Creates a weak reference. + * + * This function creates a weak reference from a local reference. + * + * @param[in] env A pointer to the environment structure. + * @param[in] ref The local reference to convert to a weak reference. + * @param[out] result A pointer to store the created weak reference. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*WeakReference_Create)(ani_env *env, ani_ref ref, ani_wref *result); + + /** + * @brief Deletes a weak reference. + * + * This function deletes the specified weak reference, releasing all associated resources. + * + * @param[in] env A pointer to the environment structure. + * @param[in] wref The weak reference to delete. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*WeakReference_Delete)(ani_env *env, ani_wref wref); + + /** + * @brief Retrieves the local reference associated with a weak reference. + * + * This function retrieves the local reference that corresponds to the specified weak reference. + * + * @param[in] env A pointer to the environment structure. + * @param[in] wref The weak reference to query. + * @param[out] result A pointer to store the retrieved local reference. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*WeakReference_GetReference)(ani_env *env, ani_wref wref, ani_ref *result); + + /** + * @brief Creates a new array buffer. + * + * This function creates a new array buffer with the specified length and returns a pointer to the allocated data. + * + * @param[in] env A pointer to the environment structure. + * @param[in] length The length of the array buffer in bytes. + * @param[out] data_result A pointer to store the allocated data of the array buffer. + * @param[out] arraybuffer_result A pointer to store the created array buffer object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*CreateArrayBuffer)(ani_env *env, size_t length, void **data_result, + ani_arraybuffer *arraybuffer_result); + + /** + * @brief Creates a new array buffer using external data. + * + * This function creates an array buffer that uses external data. The provided finalizer will be called when the + * array buffer is no longer needed. + * + * @param[in] env A pointer to the environment structure. + * @param[in] external_data A pointer to the external data to be used by the array buffer. + * @param[in] length The length of the external data in bytes. + * @param[in] finalizer A callback function to be called when the array buffer is finalized. + * @param[in] hint A user-defined hint to be passed to the finalizer. + * @param[out] result A pointer to store the created array buffer object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*CreateArrayBufferExternal)(ani_env *env, void *external_data, size_t length, ani_finalizer finalizer, + void *hint, ani_arraybuffer *result); + + /** + * @brief Retrieves information about an array buffer. + * + * This function retrieves the data pointer and length of the specified array buffer. + * + * @param[in] env A pointer to the environment structure. + * @param[in] arraybuffer The array buffer to query. + * @param[out] data_result A pointer to store the data of the array buffer. + * @param[out] length_result A pointer to store the length of the array buffer in bytes. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*ArrayBuffer_GetInfo)(ani_env *env, ani_arraybuffer arraybuffer, void **data_result, + size_t *length_result); + + /** + * @brief Converts an object to a method. + * + * This function extracts the method information from a given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] method The object representing the method. + * @param[out] result A pointer to store the extracted method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_FromMethod)(ani_env *env, ani_object method, ani_method *result); + + /** + * @brief Converts a method to an object. + * + * This function creates an object representing the specified method. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the method. + * @param[in] method The method to convert. + * @param[out] result A pointer to store the created object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_ToMethod)(ani_env *env, ani_class cls, ani_method method, ani_object *result); + + /** + * @brief Converts an object to a field. + * + * This function extracts the field information from a given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] field The object representing the field. + * @param[out] result A pointer to store the extracted field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_FromField)(ani_env *env, ani_object field, ani_field *result); + + /** + * @brief Converts a field to an object. + * + * This function creates an object representing the specified field. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the field. + * @param[in] field The field to convert. + * @param[out] result A pointer to store the created object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_ToField)(ani_env *env, ani_class cls, ani_field field, ani_object *result); + + /** + * @brief Converts an object to a static method. + * + * This function extracts the static method information from a given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] method The object representing the static method. + * @param[out] result A pointer to store the extracted static method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_FromStaticMethod)(ani_env *env, ani_object method, ani_static_method *result); + + /** + * @brief Converts a static method to an object. + * + * This function creates an object representing the specified static method. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static method. + * @param[in] method The static method to convert. + * @param[out] result A pointer to store the created object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_ToStaticMethod)(ani_env *env, ani_class cls, ani_static_method method, ani_object *result); + + /** + * @brief Converts an object to a static field. + * + * This function extracts the static field information from a given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] field The object representing the static field. + * @param[out] result A pointer to store the extracted static field. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_FromStaticField)(ani_env *env, ani_object field, ani_static_field *result); + + /** + * @brief Converts a static field to an object. + * + * This function creates an object representing the specified static field. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class containing the static field. + * @param[in] field The static field to convert. + * @param[out] result A pointer to store the created object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_ToStaticField)(ani_env *env, ani_class cls, ani_static_field field, ani_object *result); + + /** + * @brief Converts an object to a function. + * + * This function extracts the function information from a given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] function The object representing the function. + * @param[out] result A pointer to store the extracted function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_FromFunction)(ani_env *env, ani_object function, ani_function *result); + + /** + * @brief Converts a function to an object. + * + * This function creates an object representing the specified function. + * + * @param[in] env A pointer to the environment structure. + * @param[in] function The function to convert. + * @param[out] result A pointer to store the created object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_ToFunction)(ani_env *env, ani_function function, ani_object *result); + + /** + * @brief Converts an object to a variable. + * + * This function extracts the variable information from a given object. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The object representing the variable. + * @param[out] result A pointer to store the extracted variable. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_FromVariable)(ani_env *env, ani_object variable, ani_variable *result); + + /** + * @brief Converts a variable to an object. + * + * This function creates an object representing the specified variable. + * + * @param[in] env A pointer to the environment structure. + * @param[in] variable The variable to convert. + * @param[out] result A pointer to store the created object. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Reflection_ToVariable)(ani_env *env, ani_variable variable, ani_object *result); + + /** + * @brief Registers a new coroutine-local storage slot. + * + * This function registers a new coroutine-local storage (CLS) slot with an optional initial data, finalizer, and + * hint. + * + * @param[in] env A pointer to the environment structure. + * @param[in] initial_data A pointer to the initial data to associate with the slot. Can be null. + * @param[in] finalizer A callback function to finalize and clean up the data when it is no longer needed. + * @param[in] hint A user-defined pointer that is passed to the finalizer. Can be null. + * @param[out] result A pointer to store the created CLS slot. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*CLS_Register)(ani_env *env, void *initial_data, ani_finalizer finalizer, void *hint, + ani_cls_slot *result); + + /** + * @brief Unregisters a coroutine-local storage slot. + * + * This function unregisters a previously registered CLS slot, releasing its resources. + * + * @param[in] env A pointer to the environment structure. + * @param[in] slot The CLS slot to unregister. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*CLS_Unregister)(ani_env *env, ani_cls_slot slot); + + /** + * @brief Sets data for a CLS slot. + * + * This function associates the specified data with the given CLS slot. + * + * @param[in] env A pointer to the environment structure. + * @param[in] slot The CLS slot to set data for. + * @param[in] data A pointer to the data to associate with the slot. Can be null. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*CLS_SetData)(ani_env *env, ani_cls_slot slot, void *data); + + /** + * @brief Retrieves data from a CLS slot. + * + * This function retrieves the data associated with the given CLS slot. + * + * @param[in] env A pointer to the environment structure. + * @param[in] slot The CLS slot to retrieve data from. + * @param[out] result A pointer to store the retrieved data. Can be null if no data is associated. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*CLS_GetData)(ani_env *env, ani_cls_slot slot, void **result); + + /** + * @brief Launches a coroutine using a functional object. + * + * This function starts a coroutine that executes the specified functional object with the given arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] fn The functional object to execute. + * @param[in] argc The number of arguments to pass to the functional object. + * @param[in] argv An array of arguments to pass to the functional object. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchFunctionalObject)(ani_env *env, ani_fn_object fn, ani_size argc, ani_ref *argv, + ani_promise *result); + + /** + * @brief Launches a coroutine using a function with variadic arguments. + * + * This function starts a coroutine that executes the specified function with the given arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] function The function to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] ... Variadic arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchFunction)(ani_env *env, ani_function function, ani_promise *result, ...); + + /** + * @brief Launches a coroutine using a function with array-based arguments. + * + * This function starts a coroutine that executes the specified function using arguments provided in an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] function The function to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] args An array of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchFunction_A)(ani_env *env, ani_function function, ani_promise *result, + const ani_value *args); + + /** + * @brief Launches a coroutine using a function with variadic arguments in a `va_list`. + * + * This function starts a coroutine that executes the specified function using arguments provided in a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] function The function to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] args A `va_list` of arguments to pass to the function. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchFunction_V)(ani_env *env, ani_function function, ani_promise *result, va_list args); + + /** + * @brief Launches a coroutine using an object method with variadic arguments. + * + * This function starts a coroutine that executes the specified method on the given object with the provided + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] self The object on which the method is to be executed. + * @param[in] function The method to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] ... Variadic arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchMethod)(ani_env *env, ani_object self, ani_function function, ani_promise *result, + ...); + + /** + * @brief Launches a coroutine using an object method with array-based arguments. + * + * This function starts a coroutine that executes the specified method on the given object using arguments provided + * in an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] self The object on which the method is to be executed. + * @param[in] function The method to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] args An array of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchMethod_A)(ani_env *env, ani_object self, ani_function function, ani_promise *result, + const ani_value *args); + + /** + * @brief Launches a coroutine using an object method with variadic arguments in a `va_list`. + * + * This function starts a coroutine that executes the specified method on the given object using arguments provided + * in a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] self The object on which the method is to be executed. + * @param[in] function The method to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] args A `va_list` of arguments to pass to the method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchMethod_V)(ani_env *env, ani_object self, ani_function function, ani_promise *result, + va_list args); + + /** + * @brief Launches a coroutine using a static method with variadic arguments. + * + * This function starts a coroutine that executes the specified static method on the given class with the provided + * arguments. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class on which the static method is to be executed. + * @param[in] function The static method to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] ... Variadic arguments to pass to the static method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchStaticMethod)(ani_env *env, ani_class cls, ani_function function, ani_promise *result, + ...); + + /** + * @brief Launches a coroutine using a static method with array-based arguments. + * + * This function starts a coroutine that executes the specified static method on the given class using arguments + * provided in an array. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class on which the static method is to be executed. + * @param[in] function The static method to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] args An array of arguments to pass to the static method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchStaticMethod_A)(ani_env *env, ani_class cls, ani_function function, + ani_promise *result, const ani_value *args); + + /** + * @brief Launches a coroutine using a static method with variadic arguments in a `va_list`. + * + * This function starts a coroutine that executes the specified static method on the given class using arguments + * provided in a `va_list`. + * + * @param[in] env A pointer to the environment structure. + * @param[in] cls The class on which the static method is to be executed. + * @param[in] function The static method to execute. + * @param[out] result A pointer to store the promise representing the coroutine's result. + * @param[in] args A `va_list` of arguments to pass to the static method. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_LaunchStaticMethod_V)(ani_env *env, ani_class cls, ani_function function, + ani_promise *result, va_list args); + + /** + * @brief Awaits the completion of a promise and retrieves a boolean result. + * + * This function waits for the specified promise to complete and retrieves its result as a boolean value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the boolean result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Boolean)(ani_env *env, ani_promise promise, ani_boolean value); + + /** + * @brief Awaits the completion of a promise and retrieves a char result. + * + * This function waits for the specified promise to complete and retrieves its result as a char value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the char result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Char)(ani_env *env, ani_promise promise, ani_char value); + + /** + * @brief Awaits the completion of a promise and retrieves a byte result. + * + * This function waits for the specified promise to complete and retrieves its result as a byte value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the byte result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Byte)(ani_env *env, ani_promise promise, ani_byte value); + + /** + * @brief Awaits the completion of a promise and retrieves a short result. + * + * This function waits for the specified promise to complete and retrieves its result as a short value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the short result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Short)(ani_env *env, ani_promise promise, ani_short value); + + /** + * @brief Awaits the completion of a promise and retrieves a integer result. + * + * This function waits for the specified promise to complete and retrieves its result as a integer value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the integer result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Int)(ani_env *env, ani_promise promise, ani_int value); + + /** + * @brief Awaits the completion of a promise and retrieves a long result. + * + * This function waits for the specified promise to complete and retrieves its result as a long value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the long result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Long)(ani_env *env, ani_promise promise, ani_long value); + + /** + * @brief Awaits the completion of a promise and retrieves a float result. + * + * This function waits for the specified promise to complete and retrieves its result as a float value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the float result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Float)(ani_env *env, ani_promise promise, ani_float value); + + /** + * @brief Awaits the completion of a promise and retrieves a double result. + * + * This function waits for the specified promise to complete and retrieves its result as a double value. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the double result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Double)(ani_env *env, ani_promise promise, ani_double value); + + /** + * @brief Awaits the completion of a promise and retrieves a reference result. + * + * This function waits for the specified promise to complete and retrieves its result as a reference. + * + * @param[in] env A pointer to the environment structure. + * @param[in] promise The promise to await. + * @param[out] value A pointer to store the reference result of the promise. + * @return Returns a status code of type `ani_status` indicating success or failure. + */ + ani_status (*Coroutine_Await_Ref)(ani_env *env, ani_promise promise, ani_ref value); +}; + +// C++ API +struct __ani_vm { + const struct __ani_vm_api *c_api; + +#ifdef __cplusplus + ani_status DestroyVM() + { + return c_api->DestroyVM(this); + } + ani_status GetEnv(uint32_t version, ani_env **result) + { + return c_api->GetEnv(this, version, result); + } + ani_status AttachThread(void *params, ani_env **result) + { + return c_api->AttachThread(this, params, result); + } + ani_status DetachThread() + { + return c_api->DetachThread(this); + } +#endif // __cplusplus +}; + +struct __ani_env { + const struct __ani_interaction_api *c_api; + +#ifdef __cplusplus + ani_status GetVersion(uint32_t *result) + { + return c_api->GetVersion(this, result); + } + ani_status GetVM(ani_vm **result) + { + return c_api->GetVM(this, result); + } + ani_status Reference_IsObject(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsObject(this, ref, result); + } + ani_status Reference_IsFunctionalObject(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFunctionalObject(this, ref, result); + } + ani_status Reference_IsEnum(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsEnum(this, ref, result); + } + ani_status Reference_IsTuple(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsTuple(this, ref, result); + } + ani_status Reference_IsString(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsString(this, ref, result); + } + ani_status Reference_IsStringLiteral(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsStringLiteral(this, ref, result); + } + ani_status Reference_IsFixedArray(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray(this, ref, result); + } + ani_status Reference_IsFixedArray_Boolean(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Boolean(this, ref, result); + } + ani_status Reference_IsFixedArray_Char(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Char(this, ref, result); + } + ani_status Reference_IsFixedArray_Byte(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Byte(this, ref, result); + } + ani_status Reference_IsFixedArray_Short(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Short(this, ref, result); + } + ani_status Reference_IsFixedArray_Int(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Int(this, ref, result); + } + ani_status Reference_IsFixedArray_Long(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Long(this, ref, result); + } + ani_status Reference_IsFixedArray_Float(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Float(this, ref, result); + } + ani_status Reference_IsFixedArray_Double(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Double(this, ref, result); + } + ani_status Reference_IsFixedArray_Ref(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsFixedArray_Ref(this, ref, result); + } + ani_status Object_New(ani_class cls, ani_method method, ani_object *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_New_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Object_New_A(ani_class cls, ani_method method, ani_object *result, const ani_value *args) + { + return c_api->Object_New_A(this, cls, method, result, args); + } + ani_status Object_New_V(ani_class cls, ani_method method, ani_object *result, va_list args) + { + return c_api->Object_New_V(this, cls, method, result, args); + } + ani_status Object_GetType(ani_object object, ani_type *result) + { + return c_api->Object_GetType(this, object, result); + } + ani_status Object_InstanceOf(ani_object object, ani_type type, ani_boolean *result) + { + return c_api->Object_InstanceOf(this, object, type, result); + } + ani_status Object_IsSame(ani_object object1, ani_object object2, ani_boolean *result) + { + return c_api->Object_IsSame(this, object1, object2, result); + } + ani_status Type_GetSuperClass(ani_type type, ani_class *result) + { + return c_api->Type_GetSuperClass(this, type, result); + } + ani_status Type_IsAssignableFrom(ani_type from_type, ani_type to_type, ani_boolean *result) + { + return c_api->Type_IsAssignableFrom(this, from_type, to_type, result); + } + ani_status FindModule(const char *module_descriptor, ani_module *result) + { + return c_api->FindModule(this, module_descriptor, result); + } + ani_status FindNamespace(const char *namespace_descriptor, ani_namespace *result) + { + return c_api->FindNamespace(this, namespace_descriptor, result); + } + ani_status FindClass(const char *class_descriptor, ani_class *result) + { + return c_api->FindClass(this, class_descriptor, result); + } + ani_status FindEnum(const char *enum_descriptor, ani_enum *result) + { + return c_api->FindEnum(this, enum_descriptor, result); + } + ani_status FindTuple(const char *tuple_descriptor, ani_tuple *result) + { + return c_api->FindTuple(this, tuple_descriptor, result); + } + ani_status FindFunction(const char *function_descriptor, ani_function *result) + { + return c_api->FindFunction(this, function_descriptor, result); + } + ani_status FindVariable(const char *variable_descriptor, ani_variable *result) + { + return c_api->FindVariable(this, variable_descriptor, result); + } + ani_status Module_FindNamespace(ani_module module, const char *namespace_descriptor, ani_namespace *result) + { + return c_api->Module_FindNamespace(this, module, namespace_descriptor, result); + } + ani_status Module_FindClass(ani_module module, const char *class_descriptor, ani_class *result) + { + return c_api->Module_FindClass(this, module, class_descriptor, result); + } + ani_status Module_FindEnum(ani_module module, const char *enum_descriptor, ani_enum *result) + { + return c_api->Module_FindEnum(this, module, enum_descriptor, result); + } + ani_status Module_FindFunction(ani_module module, const char *name, const char *signature, ani_function *result) + { + return c_api->Module_FindFunction(this, module, name, signature, result); + } + ani_status Module_FindVariable(ani_module module, const char *variable_descriptor, ani_variable *result) + { + return c_api->Module_FindVariable(this, module, variable_descriptor, result); + } + ani_status Namespace_FindNamespace(ani_namespace ns, const char *namespace_descriptor, ani_namespace *result) + { + return c_api->Namespace_FindNamespace(this, ns, namespace_descriptor, result); + } + ani_status Namespace_FindClass(ani_namespace ns, const char *class_descriptor, ani_class *result) + { + return c_api->Namespace_FindClass(this, ns, class_descriptor, result); + } + ani_status Namespace_FindEnum(ani_namespace ns, const char *enum_descriptor, ani_enum *result) + { + return c_api->Namespace_FindEnum(this, ns, enum_descriptor, result); + } + ani_status Namespace_FindFunction(ani_namespace ns, const char *name, const char *signature, ani_function *result) + { + return c_api->Namespace_FindFunction(this, ns, name, signature, result); + } + ani_status Namespace_FindVariable(ani_namespace ns, const char *variable_descriptor, ani_variable *result) + { + return c_api->Namespace_FindVariable(this, ns, variable_descriptor, result); + } + ani_status Module_BindNativeFunctions(ani_module module, const ani_native_function *functions, + ani_size nr_functions) + { + return c_api->Module_BindNativeFunctions(this, module, functions, nr_functions); + } + ani_status Namespace_BindNativeFunctions(ani_namespace ns, const ani_native_function *functions, + ani_size nr_functions) + { + return c_api->Namespace_BindNativeFunctions(this, ns, functions, nr_functions); + } + ani_status Class_BindNativeMethods(ani_class cls, const ani_native_function *methods, ani_size nr_methods) + { + return c_api->Class_BindNativeMethods(this, cls, methods, nr_methods); + } + ani_status Reference_Delete(ani_ref ref) + { + return c_api->Reference_Delete(this, ref); + } + ani_status EnsureEnoughReferences(ani_size nr_refs) + { + return c_api->EnsureEnoughReferences(this, nr_refs); + } + ani_status CreateLocalScope(ani_size nr_refs) + { + return c_api->CreateLocalScope(this, nr_refs); + } + ani_status DestroyLocalScope() + { + return c_api->DestroyLocalScope(this); + } + ani_status CreateEscapeLocalScope(ani_size nr_refs) + { + return c_api->CreateEscapeLocalScope(this, nr_refs); + } + ani_status DestroyEscapeLocalScope(ani_ref ref, ani_ref *result) + { + return c_api->DestroyEscapeLocalScope(this, ref, result); + } + ani_status ThrowError(ani_error err) + { + return c_api->ThrowError(this, err); + } + ani_status ExistUnhandledError(ani_boolean *result) + { + return c_api->ExistUnhandledError(this, result); + } + ani_status GetUnhandledError(ani_error *result) + { + return c_api->GetUnhandledError(this, result); + } + ani_status ResetError() + { + return c_api->ResetError(this); + } + ani_status DescribeError() + { + return c_api->DescribeError(this); + } + ani_status Abort(const char *message) + { + return c_api->Abort(this, message); + } + ani_status GetNull(ani_ref *result) + { + return c_api->GetNull(this, result); + } + ani_status GetUndefined(ani_ref *result) + { + return c_api->GetUndefined(this, result); + } + ani_status Reference_IsNull(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsNull(this, ref, result); + } + ani_status Reference_IsUndefined(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsUndefined(this, ref, result); + } + ani_status Reference_IsNullishValue(ani_ref ref, ani_boolean *result) + { + return c_api->Reference_IsNullishValue(this, ref, result); + } + ani_status Reference_Equals(ani_ref ref0, ani_ref ref1, ani_boolean *result) + { + return c_api->Reference_Equals(this, ref0, ref1, result); + } + ani_status Reference_StrictEquals(ani_ref ref0, ani_ref ref1, ani_boolean *result) + { + return c_api->Reference_StrictEquals(this, ref0, ref1, result); + } + ani_status String_NewUTF16(const uint16_t *utf16_string, ani_size utf16_size, ani_string *result) + { + return c_api->String_NewUTF16(this, utf16_string, utf16_size, result); + } + ani_status String_GetUTF16Size(ani_string string, ani_size *result) + { + return c_api->String_GetUTF16Size(this, string, result); + } + ani_status String_GetUTF16(ani_string string, uint16_t *utf16_buffer, ani_size utf16_buffer_size, ani_size *result) + { + return c_api->String_GetUTF16(this, string, utf16_buffer, utf16_buffer_size, result); + } + ani_status String_GetUTF16SubString(ani_string string, ani_size substr_offset, ani_size substr_size, + uint16_t *utf16_buffer, ani_size utf16_buffer_size, ani_size *result) + { + return c_api->String_GetUTF16SubString(this, string, substr_offset, substr_size, utf16_buffer, + utf16_buffer_size, result); + } + ani_status String_NewUTF8(const char *utf8_string, ani_size utf8_size, ani_string *result) + { + return c_api->String_NewUTF8(this, utf8_string, utf8_size, result); + } + ani_status String_GetUTF8Size(ani_string string, ani_size *result) + { + return c_api->String_GetUTF8Size(this, string, result); + } + ani_status String_GetUTF8(ani_string string, char *utf8_buffer, ani_size utf8_buffer_size, ani_size *result) + { + return c_api->String_GetUTF8(this, string, utf8_buffer, utf8_buffer_size, result); + } + ani_status String_GetUTF8SubString(ani_string string, ani_size substr_offset, ani_size substr_size, + char *utf8_buffer, ani_size utf8_buffer_size, ani_size *result) + { + return c_api->String_GetUTF8SubString(this, string, substr_offset, substr_size, utf8_buffer, utf8_buffer_size, + result); + } + ani_status String_GetCritical(ani_string string, uint32_t *result_string_type, const void **result_data, + ani_size *result_size) // result_string_type - string type utf16/utf8, etc + { + return c_api->String_GetCritical(this, string, result_string_type, result_data, result_size); + } + ani_status String_ReleaseCritical(ani_string string, const void *data) + { + return c_api->String_ReleaseCritical(this, string, data); + } + ani_status StringLiteral_NewUTF16(const uint16_t *utf16_string, ani_size utf16_size, ani_stringliteral *result) + { + return c_api->StringLiteral_NewUTF16(this, utf16_string, utf16_size, result); + } + ani_status StringLiteral_GetUTF16Size(ani_stringliteral string, ani_size *result) + { + return c_api->StringLiteral_GetUTF16Size(this, string, result); + } + ani_status StringLiteral_GetUTF16(ani_stringliteral string, uint16_t *utf16_buffer, ani_size utf16_buffer_size, + ani_size *result) + { + return c_api->StringLiteral_GetUTF16(this, string, utf16_buffer, utf16_buffer_size, result); + } + ani_status StringLiteral_GetUTF16SubString(ani_stringliteral string, ani_size substr_offset, ani_size substr_size, + uint16_t *utf16_buffer, ani_size utf16_buffer_size, ani_size *result) + { + return c_api->StringLiteral_GetUTF16SubString(this, string, substr_offset, substr_size, utf16_buffer, + utf16_buffer_size, result); + } + ani_status StringLiteral_NewUTF8(const char *utf8_string, ani_size utf8_size, ani_stringliteral *result) + { + return c_api->StringLiteral_NewUTF8(this, utf8_string, utf8_size, result); + } + ani_status StringLiteral_GetUTF8Size(ani_stringliteral string, ani_size *result) + { + return c_api->StringLiteral_GetUTF8Size(this, string, result); + } + ani_status StringLiteral_GetUTF8(ani_stringliteral string, char *utf8_buffer, ani_size utf8_buffer_size, + ani_size *result) + { + return c_api->StringLiteral_GetUTF8(this, string, utf8_buffer, utf8_buffer_size, result); + } + ani_status StringLiteral_GetUTF8SubString(ani_stringliteral string, ani_size substr_offset, ani_size substr_size, + char *utf8_buffer, ani_size utf8_buffer_size, ani_size *result) + { + return c_api->StringLiteral_GetUTF8SubString(this, string, substr_offset, substr_size, utf8_buffer, + utf8_buffer_size, result); + } + ani_status StringLiteral_GetCritical(ani_stringliteral string, uint32_t *result_string_type, + const void **result_data, + ani_size *result_size) // result_string_type - string type utf16/utf8, etc + { + return c_api->StringLiteral_GetCritical(this, string, result_string_type, result_data, result_size); + } + ani_status StringLiteral_ReleaseCritical(ani_stringliteral string, const void *data) + { + return c_api->StringLiteral_ReleaseCritical(this, string, data); + } + ani_status FixedArray_GetLength(ani_fixedarray array, ani_size *result) + { + return c_api->FixedArray_GetLength(this, array, result); + } + ani_status FixedArray_New_Boolean(ani_size length, ani_fixedarray_boolean *result) + { + return c_api->FixedArray_New_Boolean(this, length, result); + } + ani_status FixedArray_New_Char(ani_size length, ani_fixedarray_char *result) + { + return c_api->FixedArray_New_Char(this, length, result); + } + ani_status FixedArray_New_Byte(ani_size length, ani_fixedarray_byte *result) + { + return c_api->FixedArray_New_Byte(this, length, result); + } + ani_status FixedArray_New_Short(ani_size length, ani_fixedarray_short *result) + { + return c_api->FixedArray_New_Short(this, length, result); + } + ani_status FixedArray_New_Int(ani_size length, ani_fixedarray_int *result) + { + return c_api->FixedArray_New_Int(this, length, result); + } + ani_status FixedArray_New_Long(ani_size length, ani_fixedarray_long *result) + { + return c_api->FixedArray_New_Long(this, length, result); + } + ani_status FixedArray_New_Float(ani_size length, ani_fixedarray_float *result) + { + return c_api->FixedArray_New_Float(this, length, result); + } + ani_status FixedArray_New_Double(ani_size length, ani_fixedarray_double *result) + { + return c_api->FixedArray_New_Double(this, length, result); + } + ani_status FixedArray_GetRegion_Boolean(ani_fixedarray_boolean array, ani_size offset, ani_size length, + ani_boolean *native_buffer) + { + return c_api->FixedArray_GetRegion_Boolean(this, array, offset, length, native_buffer); + } + ani_status FixedArray_GetRegion_Char(ani_fixedarray_char array, ani_size offset, ani_size length, + ani_char *native_buffer) + { + return c_api->FixedArray_GetRegion_Char(this, array, offset, length, native_buffer); + } + ani_status FixedArray_GetRegion_Byte(ani_fixedarray_byte array, ani_size offset, ani_size length, + ani_byte *native_buffer) + { + return c_api->FixedArray_GetRegion_Byte(this, array, offset, length, native_buffer); + } + ani_status FixedArray_GetRegion_Short(ani_fixedarray_short array, ani_size offset, ani_size length, + ani_short *native_buffer) + { + return c_api->FixedArray_GetRegion_Short(this, array, offset, length, native_buffer); + } + ani_status FixedArray_GetRegion_Int(ani_fixedarray_int array, ani_size offset, ani_size length, + ani_int *native_buffer) + { + return c_api->FixedArray_GetRegion_Int(this, array, offset, length, native_buffer); + } + ani_status FixedArray_GetRegion_Long(ani_fixedarray_long array, ani_size offset, ani_size length, + ani_long *native_buffer) + { + return c_api->FixedArray_GetRegion_Long(this, array, offset, length, native_buffer); + } + ani_status FixedArray_GetRegion_Float(ani_fixedarray_float array, ani_size offset, ani_size length, + ani_float *native_buffer) + { + return c_api->FixedArray_GetRegion_Float(this, array, offset, length, native_buffer); + } + ani_status FixedArray_GetRegion_Double(ani_fixedarray_double array, ani_size offset, ani_size length, + ani_double *native_buffer) + { + return c_api->FixedArray_GetRegion_Double(this, array, offset, length, native_buffer); + } + ani_status FixedArray_SetRegion_Boolean(ani_fixedarray_boolean array, ani_size offset, ani_size length, + const ani_boolean *native_buffer) + { + return c_api->FixedArray_SetRegion_Boolean(this, array, offset, length, native_buffer); + } + ani_status FixedArray_SetRegion_Char(ani_fixedarray_char array, ani_size offset, ani_size length, + const ani_char *native_buffer) + { + return c_api->FixedArray_SetRegion_Char(this, array, offset, length, native_buffer); + } + ani_status FixedArray_SetRegion_Byte(ani_fixedarray_byte array, ani_size offset, ani_size length, + const ani_byte *native_buffer) + { + return c_api->FixedArray_SetRegion_Byte(this, array, offset, length, native_buffer); + } + ani_status FixedArray_SetRegion_Short(ani_fixedarray_short array, ani_size offset, ani_size length, + const ani_short *native_buffer) + { + return c_api->FixedArray_SetRegion_Short(this, array, offset, length, native_buffer); + } + ani_status FixedArray_SetRegion_Int(ani_fixedarray_int array, ani_size offset, ani_size length, + const ani_int *native_buffer) + { + return c_api->FixedArray_SetRegion_Int(this, array, offset, length, native_buffer); + } + ani_status FixedArray_SetRegion_Long(ani_fixedarray_long array, ani_size offset, ani_size length, + const ani_long *native_buffer) + { + return c_api->FixedArray_SetRegion_Long(this, array, offset, length, native_buffer); + } + ani_status FixedArray_SetRegion_Float(ani_fixedarray_float array, ani_size offset, ani_size length, + const ani_float *native_buffer) + { + return c_api->FixedArray_SetRegion_Float(this, array, offset, length, native_buffer); + } + ani_status FixedArray_SetRegion_Double(ani_fixedarray_double array, ani_size offset, ani_size length, + const ani_double *native_buffer) + { + return c_api->FixedArray_SetRegion_Double(this, array, offset, length, native_buffer); + } + ani_status FixedArray_Pin(ani_fixedarray primitive_array, void **result) + { + return c_api->FixedArray_Pin(this, primitive_array, result); + } + ani_status FixedArray_Unpin(ani_fixedarray primitive_array, void *data) + { + return c_api->FixedArray_Unpin(this, primitive_array, data); + } + ani_status FixedArray_New_Ref(ani_size length, ani_ref *initial_array, ani_fixedarray_ref *result) + { + return c_api->FixedArray_New_Ref(this, length, initial_array, result); + } + ani_status FixedArray_Set_Ref(ani_fixedarray_ref array, ani_size index, ani_ref ref) + { + return c_api->FixedArray_Set_Ref(this, array, index, ref); + } + ani_status FixedArray_Get_Ref(ani_fixedarray_ref array, ani_size index, ani_ref *result) + { + return c_api->FixedArray_Get_Ref(this, array, index, result); + } + ani_status Enum_GetEnumValueByName(ani_enum enm, const char *name, ani_enum_value *result) + { + return c_api->Enum_GetEnumValueByName(this, enm, name, result); + } + ani_status Enum_GetEnumValueByIndex(ani_enum enm, ani_size index, ani_enum_value *result) + { + return c_api->Enum_GetEnumValueByIndex(this, enm, index, result); + } + ani_status EnumValue_GetEnum(ani_enum_value enum_value, ani_enum *result) + { + return c_api->EnumValue_GetEnum(this, enum_value, result); + } + ani_status EnumValue_GetValue(ani_enum_value enum_value, ani_object *result) + { + return c_api->EnumValue_GetValue(this, enum_value, result); + } + ani_status EnumValue_GetName(ani_enum_value enum_value, ani_string *result) + { + return c_api->EnumValue_GetName(this, enum_value, result); + } + ani_status EnumValue_GetIndex(ani_enum_value enum_value, ani_size *result) + { + return c_api->EnumValue_GetIndex(this, enum_value, result); + } + ani_status FunctionalObject_Call(ani_fn_object fn, ani_size argc, ani_ref *argv, ani_ref *result) + { + return c_api->FunctionalObject_Call(this, fn, argc, argv, result); + } + ani_status Variable_SetValue_Boolean(ani_variable variable, ani_boolean value) + { + return c_api->Variable_SetValue_Boolean(this, variable, value); + } + ani_status Variable_SetValue_Char(ani_variable variable, ani_char value) + { + return c_api->Variable_SetValue_Char(this, variable, value); + } + ani_status Variable_SetValue_Byte(ani_variable variable, ani_byte value) + { + return c_api->Variable_SetValue_Byte(this, variable, value); + } + ani_status Variable_SetValue_Short(ani_variable variable, ani_short value) + { + return c_api->Variable_SetValue_Short(this, variable, value); + } + ani_status Variable_SetValue_Int(ani_variable variable, ani_int value) + { + return c_api->Variable_SetValue_Int(this, variable, value); + } + ani_status Variable_SetValue_Long(ani_variable variable, ani_long value) + { + return c_api->Variable_SetValue_Long(this, variable, value); + } + ani_status Variable_SetValue_Float(ani_variable variable, ani_float value) + { + return c_api->Variable_SetValue_Float(this, variable, value); + } + ani_status Variable_SetValue_Double(ani_variable variable, ani_double value) + { + return c_api->Variable_SetValue_Double(this, variable, value); + } + ani_status Variable_SetValue_Ref(ani_variable variable, ani_ref value) + { + return c_api->Variable_SetValue_Ref(this, variable, value); + } + ani_status Variable_GetValue_Boolean(ani_variable variable, ani_boolean *result) + { + return c_api->Variable_GetValue_Boolean(this, variable, result); + } + ani_status Variable_GetValue_Char(ani_variable variable, ani_char *result) + { + return c_api->Variable_GetValue_Char(this, variable, result); + } + ani_status Variable_GetValue_Byte(ani_variable variable, ani_byte *result) + { + return c_api->Variable_GetValue_Byte(this, variable, result); + } + ani_status Variable_GetValue_Short(ani_variable variable, ani_short *result) + { + return c_api->Variable_GetValue_Short(this, variable, result); + } + ani_status Variable_GetValue_Int(ani_variable variable, ani_int *result) + { + return c_api->Variable_GetValue_Int(this, variable, result); + } + ani_status Variable_GetValue_Long(ani_variable variable, ani_long *result) + { + return c_api->Variable_GetValue_Long(this, variable, result); + } + ani_status Variable_GetValue_Float(ani_variable variable, ani_float *result) + { + return c_api->Variable_GetValue_Float(this, variable, result); + } + ani_status Variable_GetValue_Double(ani_variable variable, ani_double *result) + { + return c_api->Variable_GetValue_Double(this, variable, result); + } + ani_status Variable_GetValue_Ref(ani_variable variable, ani_ref *result) + { + return c_api->Variable_GetValue_Ref(this, variable, result); + } + ani_status Function_Call_Boolean(ani_function fn, ani_boolean *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Boolean_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Boolean_A(ani_function fn, ani_boolean *result, const ani_value *args) + { + return c_api->Function_Call_Boolean_A(this, fn, result, args); + } + ani_status Function_Call_Boolean_V(ani_function fn, ani_boolean *result, va_list args) + { + return c_api->Function_Call_Boolean_V(this, fn, result, args); + } + ani_status Function_Call_Char(ani_function fn, ani_char *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Char_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Char_A(ani_function fn, ani_char *result, const ani_value *args) + { + return c_api->Function_Call_Char_A(this, fn, result, args); + } + ani_status Function_Call_Char_V(ani_function fn, ani_char *result, va_list args) + { + return c_api->Function_Call_Char_V(this, fn, result, args); + } + ani_status Function_Call_Byte(ani_function fn, ani_byte *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Byte_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Byte_A(ani_function fn, ani_byte *result, const ani_value *args) + { + return c_api->Function_Call_Byte_A(this, fn, result, args); + } + ani_status Function_Call_Byte_V(ani_function fn, ani_byte *result, va_list args) + { + return c_api->Function_Call_Byte_V(this, fn, result, args); + } + ani_status Function_Call_Short(ani_function fn, ani_short *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Short_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Short_A(ani_function fn, ani_short *result, const ani_value *args) + { + return c_api->Function_Call_Short_A(this, fn, result, args); + } + ani_status Function_Call_Short_V(ani_function fn, ani_short *result, va_list args) + { + return c_api->Function_Call_Short_V(this, fn, result, args); + } + ani_status Function_Call_Int(ani_function fn, ani_int *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Int_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Int_A(ani_function fn, ani_int *result, const ani_value *args) + { + return c_api->Function_Call_Int_A(this, fn, result, args); + } + ani_status Function_Call_Int_V(ani_function fn, ani_int *result, va_list args) + { + return c_api->Function_Call_Int_V(this, fn, result, args); + } + ani_status Function_Call_Long(ani_function fn, ani_long *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Long_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Long_A(ani_function fn, ani_long *result, const ani_value *args) + { + return c_api->Function_Call_Long_A(this, fn, result, args); + } + ani_status Function_Call_Long_V(ani_function fn, ani_long *result, va_list args) + { + return c_api->Function_Call_Long_V(this, fn, result, args); + } + ani_status Function_Call_Float(ani_function fn, ani_float *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Float_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Float_A(ani_function fn, ani_float *result, const ani_value *args) + { + return c_api->Function_Call_Float_A(this, fn, result, args); + } + ani_status Function_Call_Float_V(ani_function fn, ani_float *result, va_list args) + { + return c_api->Function_Call_Float_V(this, fn, result, args); + } + ani_status Function_Call_Double(ani_function fn, ani_double *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Double_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Double_A(ani_function fn, ani_double *result, const ani_value *args) + { + return c_api->Function_Call_Double_A(this, fn, result, args); + } + ani_status Function_Call_Double_V(ani_function fn, ani_double *result, va_list args) + { + return c_api->Function_Call_Double_V(this, fn, result, args); + } + ani_status Function_Call_Ref(ani_function fn, ani_ref *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Function_Call_Ref_V(this, fn, result, args); + va_end(args); + return status; + } + ani_status Function_Call_Ref_A(ani_function fn, ani_ref *result, const ani_value *args) + { + return c_api->Function_Call_Ref_A(this, fn, result, args); + } + ani_status Function_Call_Ref_V(ani_function fn, ani_ref *result, va_list args) + { + return c_api->Function_Call_Ref_V(this, fn, result, args); + } + ani_status Function_Call_Void(ani_function fn, ...) + { + va_list args; + va_start(args, fn); + ani_status status = c_api->Function_Call_Void_V(this, fn, args); + va_end(args); + return status; + } + ani_status Function_Call_Void_A(ani_function fn, const ani_value *args) + { + return c_api->Function_Call_Void_A(this, fn, args); + } + ani_status Function_Call_Void_V(ani_function fn, va_list args) + { + return c_api->Function_Call_Void_V(this, fn, args); + } + ani_status Class_GetPartial(ani_class cls, ani_class *result) + { + return c_api->Class_GetPartial(this, cls, result); + } + ani_status Class_GetRequired(ani_class cls, ani_class *result) + { + return c_api->Class_GetRequired(this, cls, result); + } + ani_status Class_GetField(ani_class cls, const char *name, ani_field *result) + { + return c_api->Class_GetField(this, cls, name, result); + } + ani_status Class_GetStaticField(ani_class cls, const char *name, ani_static_field *result) + { + return c_api->Class_GetStaticField(this, cls, name, result); + } + ani_status Class_GetMethod(ani_class cls, const char *name, const char *signature, ani_method *result) + { + return c_api->Class_GetMethod(this, cls, name, signature, result); + } + ani_status Class_GetStaticMethod(ani_class cls, const char *name, const char *signature, ani_static_method *result) + { + return c_api->Class_GetStaticMethod(this, cls, name, signature, result); + } + ani_status Class_GetProperty(ani_class cls, const char *name, ani_property *result) + { + return c_api->Class_GetProperty(this, cls, name, result); + } + ani_status Class_GetSetter(ani_class cls, const char *name, ani_method *result) + { + return c_api->Class_GetSetter(this, cls, name, result); + } + ani_status Class_GetGetter(ani_class cls, const char *name, ani_method *result) + { + return c_api->Class_GetGetter(this, cls, name, result); + } + ani_status Class_GetIndexableGetter(ani_class cls, const char *signature, ani_method *result) + { + return c_api->Class_GetIndexableGetter(this, cls, signature, result); + } + ani_status Class_GetIndexableSetter(ani_class cls, const char *signature, ani_method *result) + { + return c_api->Class_GetIndexableSetter(this, cls, signature, result); + } + ani_status Class_GetIterator(ani_class cls, ani_method *result) + { + return c_api->Class_GetIterator(this, cls, result); + } + ani_status Class_GetStaticField_Boolean(ani_class cls, ani_static_field field, ani_boolean *result) + { + return c_api->Class_GetStaticField_Boolean(this, cls, field, result); + } + ani_status Class_GetStaticField_Char(ani_class cls, ani_static_field field, ani_char *result) + { + return c_api->Class_GetStaticField_Char(this, cls, field, result); + } + ani_status Class_GetStaticField_Byte(ani_class cls, ani_static_field field, ani_byte *result) + { + return c_api->Class_GetStaticField_Byte(this, cls, field, result); + } + ani_status Class_GetStaticField_Short(ani_class cls, ani_static_field field, ani_short *result) + { + return c_api->Class_GetStaticField_Short(this, cls, field, result); + } + ani_status Class_GetStaticField_Int(ani_class cls, ani_static_field field, ani_int *result) + { + return c_api->Class_GetStaticField_Int(this, cls, field, result); + } + ani_status Class_GetStaticField_Long(ani_class cls, ani_static_field field, ani_long *result) + { + return c_api->Class_GetStaticField_Long(this, cls, field, result); + } + ani_status Class_GetStaticField_Float(ani_class cls, ani_static_field field, ani_float *result) + { + return c_api->Class_GetStaticField_Float(this, cls, field, result); + } + ani_status Class_GetStaticField_Double(ani_class cls, ani_static_field field, ani_double *result) + { + return c_api->Class_GetStaticField_Double(this, cls, field, result); + } + ani_status Class_GetStaticField_Ref(ani_class cls, ani_static_field field, ani_ref *result) + { + return c_api->Class_GetStaticField_Ref(this, cls, field, result); + } + ani_status Class_SetStaticField_Boolean(ani_class cls, ani_static_field field, ani_boolean value) + { + return c_api->Class_SetStaticField_Boolean(this, cls, field, value); + } + ani_status Class_SetStaticField_Char(ani_class cls, ani_static_field field, ani_char value) + { + return c_api->Class_SetStaticField_Char(this, cls, field, value); + } + ani_status Class_SetStaticField_Byte(ani_class cls, ani_static_field field, ani_byte value) + { + return c_api->Class_SetStaticField_Byte(this, cls, field, value); + } + ani_status Class_SetStaticField_Short(ani_class cls, ani_static_field field, ani_short value) + { + return c_api->Class_SetStaticField_Short(this, cls, field, value); + } + ani_status Class_SetStaticField_Int(ani_class cls, ani_static_field field, ani_int value) + { + return c_api->Class_SetStaticField_Int(this, cls, field, value); + } + ani_status Class_SetStaticField_Long(ani_class cls, ani_static_field field, ani_long value) + { + return c_api->Class_SetStaticField_Long(this, cls, field, value); + } + ani_status Class_SetStaticField_Float(ani_class cls, ani_static_field field, ani_float value) + { + return c_api->Class_SetStaticField_Float(this, cls, field, value); + } + ani_status Class_SetStaticField_Double(ani_class cls, ani_static_field field, ani_double value) + { + return c_api->Class_SetStaticField_Double(this, cls, field, value); + } + ani_status Class_SetStaticField_Ref(ani_class cls, ani_static_field field, ani_ref value) + { + return c_api->Class_SetStaticField_Ref(this, cls, field, value); + } + ani_status Class_GetStaticFieldByName_Boolean(ani_class cls, const char *name, ani_boolean *result) + { + return c_api->Class_GetStaticFieldByName_Boolean(this, cls, name, result); + } + ani_status Class_GetStaticFieldByName_Char(ani_class cls, const char *name, ani_char *result) + { + return c_api->Class_GetStaticFieldByName_Char(this, cls, name, result); + } + ani_status Class_GetStaticFieldByName_Byte(ani_class cls, const char *name, ani_byte *result) + { + return c_api->Class_GetStaticFieldByName_Byte(this, cls, name, result); + } + ani_status Class_GetStaticFieldByName_Short(ani_class cls, const char *name, ani_short *result) + { + return c_api->Class_GetStaticFieldByName_Short(this, cls, name, result); + } + ani_status Class_GetStaticFieldByName_Int(ani_class cls, const char *name, ani_int *result) + { + return c_api->Class_GetStaticFieldByName_Int(this, cls, name, result); + } + ani_status Class_GetStaticFieldByName_Long(ani_class cls, const char *name, ani_long *result) + { + return c_api->Class_GetStaticFieldByName_Long(this, cls, name, result); + } + ani_status Class_GetStaticFieldByName_Float(ani_class cls, const char *name, ani_float *result) + { + return c_api->Class_GetStaticFieldByName_Float(this, cls, name, result); + } + ani_status Class_GetStaticFieldByName_Double(ani_class cls, const char *name, ani_double *result) + { + return c_api->Class_GetStaticFieldByName_Double(this, cls, name, result); + } + ani_status Class_GetStaticFieldByName_Ref(ani_class cls, const char *name, ani_ref *result) + { + return c_api->Class_GetStaticFieldByName_Ref(this, cls, name, result); + } + ani_status Class_SetStaticFieldByName_Boolean(ani_class cls, const char *name, ani_boolean value) + { + return c_api->Class_SetStaticFieldByName_Boolean(this, cls, name, value); + } + ani_status Class_SetStaticFieldByName_Char(ani_class cls, const char *name, ani_char value) + { + return c_api->Class_SetStaticFieldByName_Char(this, cls, name, value); + } + ani_status Class_SetStaticFieldByName_Byte(ani_class cls, const char *name, ani_byte value) + { + return c_api->Class_SetStaticFieldByName_Byte(this, cls, name, value); + } + ani_status Class_SetStaticFieldByName_Short(ani_class cls, const char *name, ani_short value) + { + return c_api->Class_SetStaticFieldByName_Short(this, cls, name, value); + } + ani_status Class_SetStaticFieldByName_Int(ani_class cls, const char *name, ani_int value) + { + return c_api->Class_SetStaticFieldByName_Int(this, cls, name, value); + } + ani_status Class_SetStaticFieldByName_Long(ani_class cls, const char *name, ani_long value) + { + return c_api->Class_SetStaticFieldByName_Long(this, cls, name, value); + } + ani_status Class_SetStaticFieldByName_Float(ani_class cls, const char *name, ani_float value) + { + return c_api->Class_SetStaticFieldByName_Float(this, cls, name, value); + } + ani_status Class_SetStaticFieldByName_Double(ani_class cls, const char *name, ani_double value) + { + return c_api->Class_SetStaticFieldByName_Double(this, cls, name, value); + } + ani_status Class_SetStaticFieldByName_Ref(ani_class cls, const char *name, ani_ref value) + { + return c_api->Class_SetStaticFieldByName_Ref(this, cls, name, value); + } + ani_status Class_CallStaticMethod_Boolean(ani_class cls, ani_static_method method, ani_boolean *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Boolean_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Boolean_A(ani_class cls, ani_static_method method, ani_boolean *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Boolean_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Boolean_V(ani_class cls, ani_static_method method, ani_boolean *result, + va_list args) + { + return c_api->Class_CallStaticMethod_Boolean_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Char(ani_class cls, ani_static_method method, ani_char *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Char_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Char_A(ani_class cls, ani_static_method method, ani_char *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Char_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Char_V(ani_class cls, ani_static_method method, ani_char *result, va_list args) + { + return c_api->Class_CallStaticMethod_Char_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Byte(ani_class cls, ani_static_method method, ani_byte *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Byte_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Byte_A(ani_class cls, ani_static_method method, ani_byte *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Byte_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Byte_V(ani_class cls, ani_static_method method, ani_byte *result, va_list args) + { + return c_api->Class_CallStaticMethod_Byte_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Short(ani_class cls, ani_static_method method, ani_short *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Short_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Short_A(ani_class cls, ani_static_method method, ani_short *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Short_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Short_V(ani_class cls, ani_static_method method, ani_short *result, va_list args) + { + return c_api->Class_CallStaticMethod_Short_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Int(ani_class cls, ani_static_method method, ani_int *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Int_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Int_A(ani_class cls, ani_static_method method, ani_int *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Int_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Int_V(ani_class cls, ani_static_method method, ani_int *result, va_list args) + { + return c_api->Class_CallStaticMethod_Int_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Long(ani_class cls, ani_static_method method, ani_long *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Long_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Long_A(ani_class cls, ani_static_method method, ani_long *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Long_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Long_V(ani_class cls, ani_static_method method, ani_long *result, va_list args) + { + return c_api->Class_CallStaticMethod_Long_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Float(ani_class cls, ani_static_method method, ani_float *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Float_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Float_A(ani_class cls, ani_static_method method, ani_float *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Float_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Float_V(ani_class cls, ani_static_method method, ani_float *result, va_list args) + { + return c_api->Class_CallStaticMethod_Float_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Double(ani_class cls, ani_static_method method, ani_double *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Double_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Double_A(ani_class cls, ani_static_method method, ani_double *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Double_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Double_V(ani_class cls, ani_static_method method, ani_double *result, + va_list args) + { + return c_api->Class_CallStaticMethod_Double_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Ref(ani_class cls, ani_static_method method, ani_ref *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethod_Ref_V(this, cls, method, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Ref_A(ani_class cls, ani_static_method method, ani_ref *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethod_Ref_A(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Ref_V(ani_class cls, ani_static_method method, ani_ref *result, va_list args) + { + return c_api->Class_CallStaticMethod_Ref_V(this, cls, method, result, args); + } + ani_status Class_CallStaticMethod_Void(ani_class cls, ani_static_method method, ...) + { + va_list args; + va_start(args, method); + ani_status status = c_api->Class_CallStaticMethod_Void_V(this, cls, method, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethod_Void_A(ani_class cls, ani_static_method method, const ani_value *args) + { + return c_api->Class_CallStaticMethod_Void_A(this, cls, method, args); + } + ani_status Class_CallStaticMethod_Void_V(ani_class cls, ani_static_method method, va_list args) + { + return c_api->Class_CallStaticMethod_Void_V(this, cls, method, args); + } + ani_status Class_CallStaticMethodByName_Boolean(ani_class cls, const char *name, ani_boolean *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Boolean_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Boolean_A(ani_class cls, const char *name, ani_boolean *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Boolean_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Boolean_V(ani_class cls, const char *name, ani_boolean *result, + va_list args) + { + return c_api->Class_CallStaticMethodByName_Boolean_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Char(ani_class cls, const char *name, ani_char *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Char_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Char_A(ani_class cls, const char *name, ani_char *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Char_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Char_V(ani_class cls, const char *name, ani_char *result, va_list args) + { + return c_api->Class_CallStaticMethodByName_Char_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Byte(ani_class cls, const char *name, ani_byte *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Byte_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Byte_A(ani_class cls, const char *name, ani_byte *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Byte_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Byte_V(ani_class cls, const char *name, ani_byte *result, va_list args) + { + return c_api->Class_CallStaticMethodByName_Byte_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Short(ani_class cls, const char *name, ani_short *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Short_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Short_A(ani_class cls, const char *name, ani_short *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Short_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Short_V(ani_class cls, const char *name, ani_short *result, va_list args) + { + return c_api->Class_CallStaticMethodByName_Short_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Int(ani_class cls, const char *name, ani_int *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Int_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Int_A(ani_class cls, const char *name, ani_int *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Int_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Int_V(ani_class cls, const char *name, ani_int *result, va_list args) + { + return c_api->Class_CallStaticMethodByName_Int_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Long(ani_class cls, const char *name, ani_long *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Long_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Long_A(ani_class cls, const char *name, ani_long *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Long_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Long_V(ani_class cls, const char *name, ani_long *result, va_list args) + { + return c_api->Class_CallStaticMethodByName_Long_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Float(ani_class cls, const char *name, ani_float *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Float_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Float_A(ani_class cls, const char *name, ani_float *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Float_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Float_V(ani_class cls, const char *name, ani_float *result, va_list args) + { + return c_api->Class_CallStaticMethodByName_Float_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Double(ani_class cls, const char *name, ani_double *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Double_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Double_A(ani_class cls, const char *name, ani_double *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Double_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Double_V(ani_class cls, const char *name, ani_double *result, va_list args) + { + return c_api->Class_CallStaticMethodByName_Double_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Ref(ani_class cls, const char *name, ani_ref *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Class_CallStaticMethodByName_Ref_V(this, cls, name, result, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Ref_A(ani_class cls, const char *name, ani_ref *result, + const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Ref_A(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Ref_V(ani_class cls, const char *name, ani_ref *result, va_list args) + { + return c_api->Class_CallStaticMethodByName_Ref_V(this, cls, name, result, args); + } + ani_status Class_CallStaticMethodByName_Void(ani_class cls, const char *name, ...) + { + va_list args; + va_start(args, name); + ani_status status = c_api->Class_CallStaticMethodByName_Void_V(this, cls, name, args); + va_end(args); + return status; + } + ani_status Class_CallStaticMethodByName_Void_A(ani_class cls, const char *name, const ani_value *args) + { + return c_api->Class_CallStaticMethodByName_Void_A(this, cls, name, args); + } + ani_status Class_CallStaticMethodByName_Void_V(ani_class cls, const char *name, va_list args) + { + return c_api->Class_CallStaticMethodByName_Void_V(this, cls, name, args); + } + ani_status Object_GetField_Boolean(ani_object object, ani_field field, ani_boolean *result) + { + return c_api->Object_GetField_Boolean(this, object, field, result); + } + ani_status Object_GetField_Char(ani_object object, ani_field field, ani_char *result) + { + return c_api->Object_GetField_Char(this, object, field, result); + } + ani_status Object_GetField_Byte(ani_object object, ani_field field, ani_byte *result) + { + return c_api->Object_GetField_Byte(this, object, field, result); + } + ani_status Object_GetField_Short(ani_object object, ani_field field, ani_short *result) + { + return c_api->Object_GetField_Short(this, object, field, result); + } + ani_status Object_GetField_Int(ani_object object, ani_field field, ani_int *result) + { + return c_api->Object_GetField_Int(this, object, field, result); + } + ani_status Object_GetField_Long(ani_object object, ani_field field, ani_long *result) + { + return c_api->Object_GetField_Long(this, object, field, result); + } + ani_status Object_GetField_Float(ani_object object, ani_field field, ani_float *result) + { + return c_api->Object_GetField_Float(this, object, field, result); + } + ani_status Object_GetField_Double(ani_object object, ani_field field, ani_double *result) + { + return c_api->Object_GetField_Double(this, object, field, result); + } + ani_status Object_GetField_Ref(ani_object object, ani_field field, ani_ref *result) + { + return c_api->Object_GetField_Ref(this, object, field, result); + } + ani_status Object_SetField_Boolean(ani_object object, ani_field field, ani_boolean value) + { + return c_api->Object_SetField_Boolean(this, object, field, value); + } + ani_status Object_SetField_Char(ani_object object, ani_field field, ani_char value) + { + return c_api->Object_SetField_Char(this, object, field, value); + } + ani_status Object_SetField_Byte(ani_object object, ani_field field, ani_byte value) + { + return c_api->Object_SetField_Byte(this, object, field, value); + } + ani_status Object_SetField_Short(ani_object object, ani_field field, ani_short value) + { + return c_api->Object_SetField_Short(this, object, field, value); + } + ani_status Object_SetField_Int(ani_object object, ani_field field, ani_int value) + { + return c_api->Object_SetField_Int(this, object, field, value); + } + ani_status Object_SetField_Long(ani_object object, ani_field field, ani_long value) + { + return c_api->Object_SetField_Long(this, object, field, value); + } + ani_status Object_SetField_Float(ani_object object, ani_field field, ani_float value) + { + return c_api->Object_SetField_Float(this, object, field, value); + } + ani_status Object_SetField_Double(ani_object object, ani_field field, ani_double value) + { + return c_api->Object_SetField_Double(this, object, field, value); + } + ani_status Object_SetField_Ref(ani_object object, ani_field field, ani_ref value) + { + return c_api->Object_SetField_Ref(this, object, field, value); + } + ani_status Object_GetFieldByName_Boolean(ani_object object, const char *name, ani_boolean *result) + { + return c_api->Object_GetFieldByName_Boolean(this, object, name, result); + } + ani_status Object_GetFieldByName_Char(ani_object object, const char *name, ani_char *result) + { + return c_api->Object_GetFieldByName_Char(this, object, name, result); + } + ani_status Object_GetFieldByName_Byte(ani_object object, const char *name, ani_byte *result) + { + return c_api->Object_GetFieldByName_Byte(this, object, name, result); + } + ani_status Object_GetFieldByName_Short(ani_object object, const char *name, ani_short *result) + { + return c_api->Object_GetFieldByName_Short(this, object, name, result); + } + ani_status Object_GetFieldByName_Int(ani_object object, const char *name, ani_int *result) + { + return c_api->Object_GetFieldByName_Int(this, object, name, result); + } + ani_status Object_GetFieldByName_Long(ani_object object, const char *name, ani_long *result) + { + return c_api->Object_GetFieldByName_Long(this, object, name, result); + } + ani_status Object_GetFieldByName_Float(ani_object object, const char *name, ani_float *result) + { + return c_api->Object_GetFieldByName_Float(this, object, name, result); + } + ani_status Object_GetFieldByName_Double(ani_object object, const char *name, ani_double *result) + { + return c_api->Object_GetFieldByName_Double(this, object, name, result); + } + ani_status Object_GetFieldByName_Ref(ani_object object, const char *name, ani_ref *result) + { + return c_api->Object_GetFieldByName_Ref(this, object, name, result); + } + ani_status Object_SetFieldByName_Boolean(ani_object object, const char *name, ani_boolean value) + { + return c_api->Object_SetFieldByName_Boolean(this, object, name, value); + } + ani_status Object_SetFieldByName_Char(ani_object object, const char *name, ani_char value) + { + return c_api->Object_SetFieldByName_Char(this, object, name, value); + } + ani_status Object_SetFieldByName_Byte(ani_object object, const char *name, ani_byte value) + { + return c_api->Object_SetFieldByName_Byte(this, object, name, value); + } + ani_status Object_SetFieldByName_Short(ani_object object, const char *name, ani_short value) + { + return c_api->Object_SetFieldByName_Short(this, object, name, value); + } + ani_status Object_SetFieldByName_Int(ani_object object, const char *name, ani_int value) + { + return c_api->Object_SetFieldByName_Int(this, object, name, value); + } + ani_status Object_SetFieldByName_Long(ani_object object, const char *name, ani_long value) + { + return c_api->Object_SetFieldByName_Long(this, object, name, value); + } + ani_status Object_SetFieldByName_Float(ani_object object, const char *name, ani_float value) + { + return c_api->Object_SetFieldByName_Float(this, object, name, value); + } + ani_status Object_SetFieldByName_Double(ani_object object, const char *name, ani_double value) + { + return c_api->Object_SetFieldByName_Double(this, object, name, value); + } + ani_status Object_SetFieldByName_Ref(ani_object object, const char *name, ani_ref value) + { + return c_api->Object_SetFieldByName_Ref(this, object, name, value); + } + ani_status Object_GetProperty_Boolean(ani_object object, ani_property property, ani_boolean *result) + { + return c_api->Object_GetProperty_Boolean(this, object, property, result); + } + ani_status Object_GetProperty_Char(ani_object object, ani_property property, ani_char *result) + { + return c_api->Object_GetProperty_Char(this, object, property, result); + } + ani_status Object_GetProperty_Byte(ani_object object, ani_property property, ani_byte *result) + { + return c_api->Object_GetProperty_Byte(this, object, property, result); + } + ani_status Object_GetProperty_Short(ani_object object, ani_property property, ani_short *result) + { + return c_api->Object_GetProperty_Short(this, object, property, result); + } + ani_status Object_GetProperty_Int(ani_object object, ani_property property, ani_int *result) + { + return c_api->Object_GetProperty_Int(this, object, property, result); + } + ani_status Object_GetProperty_Long(ani_object object, ani_property property, ani_long *result) + { + return c_api->Object_GetProperty_Long(this, object, property, result); + } + ani_status Object_GetProperty_Float(ani_object object, ani_property property, ani_float *result) + { + return c_api->Object_GetProperty_Float(this, object, property, result); + } + ani_status Object_GetProperty_Double(ani_object object, ani_property property, ani_double *result) + { + return c_api->Object_GetProperty_Double(this, object, property, result); + } + ani_status Object_GetProperty_Ref(ani_object object, ani_property property, ani_ref *result) + { + return c_api->Object_GetProperty_Ref(this, object, property, result); + } + ani_status Object_SetProperty_Boolean(ani_object object, ani_property property, ani_boolean value) + { + return c_api->Object_SetProperty_Boolean(this, object, property, value); + } + ani_status Object_SetProperty_Char(ani_object object, ani_property property, ani_char value) + { + return c_api->Object_SetProperty_Char(this, object, property, value); + } + ani_status Object_SetProperty_Byte(ani_object object, ani_property property, ani_byte value) + { + return c_api->Object_SetProperty_Byte(this, object, property, value); + } + ani_status Object_SetProperty_Short(ani_object object, ani_property property, ani_short value) + { + return c_api->Object_SetProperty_Byte(this, object, property, value); + } + ani_status Object_SetProperty_Int(ani_object object, ani_property property, ani_int value) + { + return c_api->Object_SetProperty_Int(this, object, property, value); + } + ani_status Object_SetProperty_Long(ani_object object, ani_property property, ani_long value) + { + return c_api->Object_SetProperty_Long(this, object, property, value); + } + ani_status Object_SetProperty_Float(ani_object object, ani_property property, ani_float value) + { + return c_api->Object_SetProperty_Float(this, object, property, value); + } + ani_status Object_SetProperty_Double(ani_object object, ani_property property, ani_double value) + { + return c_api->Object_SetProperty_Double(this, object, property, value); + } + ani_status Object_SetProperty_Ref(ani_object object, ani_property property, ani_ref value) + { + return c_api->Object_SetProperty_Ref(this, object, property, value); + } + ani_status Object_GetPropertyByName_Boolean(ani_object object, const char *name, ani_boolean *result) + { + return c_api->Object_GetPropertyByName_Boolean(this, object, name, result); + } + ani_status Object_GetPropertyByName_Char(ani_object object, const char *name, ani_char *result) + { + return c_api->Object_GetPropertyByName_Char(this, object, name, result); + } + ani_status Object_GetPropertyByName_Byte(ani_object object, const char *name, ani_byte *result) + { + return c_api->Object_GetPropertyByName_Byte(this, object, name, result); + } + ani_status Object_GetPropertyByName_Short(ani_object object, const char *name, ani_short *result) + { + return c_api->Object_GetPropertyByName_Short(this, object, name, result); + } + ani_status Object_GetPropertyByName_Int(ani_object object, const char *name, ani_int *result) + { + return c_api->Object_GetPropertyByName_Int(this, object, name, result); + } + ani_status Object_GetPropertyByName_Long(ani_object object, const char *name, ani_long *result) + { + return c_api->Object_GetPropertyByName_Long(this, object, name, result); + } + ani_status Object_GetPropertyByName_Float(ani_object object, const char *name, ani_float *result) + { + return c_api->Object_GetPropertyByName_Float(this, object, name, result); + } + ani_status Object_GetPropertyByName_Double(ani_object object, const char *name, ani_double *result) + { + return c_api->Object_GetPropertyByName_Double(this, object, name, result); + } + ani_status Object_GetPropertyByName_Ref(ani_object object, const char *name, ani_ref *result) + { + return c_api->Object_GetPropertyByName_Ref(this, object, name, result); + } + ani_status Object_SetPropertyByName_Boolean(ani_object object, const char *name, ani_boolean value) + { + return c_api->Object_SetPropertyByName_Boolean(this, object, name, value); + } + ani_status Object_SetPropertyByName_Char(ani_object object, const char *name, ani_char value) + { + return c_api->Object_SetPropertyByName_Char(this, object, name, value); + } + ani_status Object_SetPropertyByName_Byte(ani_object object, const char *name, ani_byte value) + { + return c_api->Object_SetPropertyByName_Byte(this, object, name, value); + } + ani_status Object_SetPropertyByName_Short(ani_object object, const char *name, ani_short value) + { + return c_api->Object_SetPropertyByName_Short(this, object, name, value); + } + ani_status Object_SetPropertyByName_Int(ani_object object, const char *name, ani_int value) + { + return c_api->Object_SetPropertyByName_Int(this, object, name, value); + } + ani_status Object_SetPropertyByName_Long(ani_object object, const char *name, ani_long value) + { + return c_api->Object_SetPropertyByName_Long(this, object, name, value); + } + ani_status Object_SetPropertyByName_Float(ani_object object, const char *name, ani_float value) + { + return c_api->Object_SetPropertyByName_Float(this, object, name, value); + } + ani_status Object_SetPropertyByName_Double(ani_object object, const char *name, ani_double value) + { + return c_api->Object_SetPropertyByName_Double(this, object, name, value); + } + ani_status Object_SetPropertyByName_Ref(ani_object object, const char *name, ani_ref value) + { + return c_api->Object_SetPropertyByName_Ref(this, object, name, value); + } + ani_status Object_CallMethod_Boolean(ani_object object, ani_method method, ani_boolean *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Boolean_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Boolean_A(ani_object object, ani_method method, ani_boolean *result, + const ani_value *args) + { + return c_api->Object_CallMethod_Boolean_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Boolean_V(ani_object object, ani_method method, ani_boolean *result, va_list args) + { + return c_api->Object_CallMethod_Boolean_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Char(ani_object object, ani_method method, ani_char *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Char_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Char_A(ani_object object, ani_method method, ani_char *result, const ani_value *args) + { + return c_api->Object_CallMethod_Char_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Char_V(ani_object object, ani_method method, ani_char *result, va_list args) + { + return c_api->Object_CallMethod_Char_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Byte(ani_object object, ani_method method, ani_byte *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Byte_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Byte_A(ani_object object, ani_method method, ani_byte *result, const ani_value *args) + { + return c_api->Object_CallMethod_Byte_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Byte_V(ani_object object, ani_method method, ani_byte *result, va_list args) + { + return c_api->Object_CallMethod_Byte_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Short(ani_object object, ani_method method, ani_short *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Short_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Short_A(ani_object object, ani_method method, ani_short *result, const ani_value *args) + { + return c_api->Object_CallMethod_Short_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Short_V(ani_object object, ani_method method, ani_short *result, va_list args) + { + return c_api->Object_CallMethod_Short_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Int(ani_object object, ani_method method, ani_int *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Int_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Int_A(ani_object object, ani_method method, ani_int *result, const ani_value *args) + { + return c_api->Object_CallMethod_Int_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Int_V(ani_object object, ani_method method, ani_int *result, va_list args) + { + return c_api->Object_CallMethod_Int_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Long(ani_object object, ani_method method, ani_long *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Long_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Long_A(ani_object object, ani_method method, ani_long *result, const ani_value *args) + { + return c_api->Object_CallMethod_Long_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Long_V(ani_object object, ani_method method, ani_long *result, va_list args) + { + return c_api->Object_CallMethod_Long_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Float(ani_object object, ani_method method, ani_float *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Float_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Float_A(ani_object object, ani_method method, ani_float *result, const ani_value *args) + { + return c_api->Object_CallMethod_Float_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Float_V(ani_object object, ani_method method, ani_float *result, va_list args) + { + return c_api->Object_CallMethod_Float_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Double(ani_object object, ani_method method, ani_double *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Double_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Double_A(ani_object object, ani_method method, ani_double *result, + const ani_value *args) + { + return c_api->Object_CallMethod_Double_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Double_V(ani_object object, ani_method method, ani_double *result, va_list args) + { + return c_api->Object_CallMethod_Double_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Ref(ani_object object, ani_method method, ani_ref *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethod_Ref_V(this, object, method, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Ref_A(ani_object object, ani_method method, ani_ref *result, const ani_value *args) + { + return c_api->Object_CallMethod_Ref_A(this, object, method, result, args); + } + ani_status Object_CallMethod_Ref_V(ani_object object, ani_method method, ani_ref *result, va_list args) + { + return c_api->Object_CallMethod_Ref_V(this, object, method, result, args); + } + ani_status Object_CallMethod_Void(ani_object object, ani_method method, ...) + { + va_list args; + va_start(args, method); + ani_status status = c_api->Object_CallMethod_Void_V(this, object, method, args); + va_end(args); + return status; + } + ani_status Object_CallMethod_Void_A(ani_object object, ani_method method, const ani_value *args) + { + return c_api->Object_CallMethod_Void_A(this, object, method, args); + } + ani_status Object_CallMethod_Void_V(ani_object object, ani_method method, va_list args) + { + return c_api->Object_CallMethod_Void_V(this, object, method, args); + } + ani_status Object_CallMethodByName_Boolean(ani_object object, const char *name, const char *signature, + ani_boolean *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Boolean_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Boolean_A(ani_object object, const char *name, const char *signature, + ani_boolean *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Boolean_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Boolean_V(ani_object object, const char *name, const char *signature, + ani_boolean *result, va_list args) + { + return c_api->Object_CallMethodByName_Boolean_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Char(ani_object object, const char *name, const char *signature, + ani_char *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Char_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Char_A(ani_object object, const char *name, const char *signature, + ani_char *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Char_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Char_V(ani_object object, const char *name, const char *signature, + ani_char *result, va_list args) + { + return c_api->Object_CallMethodByName_Char_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Byte(ani_object object, const char *name, const char *signature, + ani_byte *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Byte_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Byte_A(ani_object object, const char *name, const char *signature, + ani_byte *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Byte_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Byte_V(ani_object object, const char *name, const char *signature, + ani_byte *result, va_list args) + { + return c_api->Object_CallMethodByName_Byte_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Short(ani_object object, const char *name, const char *signature, + ani_short *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Short_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Short_A(ani_object object, const char *name, const char *signature, + ani_short *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Short_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Short_V(ani_object object, const char *name, const char *signature, + ani_short *result, va_list args) + { + return c_api->Object_CallMethodByName_Short_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Int(ani_object object, const char *name, const char *signature, ani_int *result, + ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Int_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Int_A(ani_object object, const char *name, const char *signature, + ani_int *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Int_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Int_V(ani_object object, const char *name, const char *signature, + ani_int *result, va_list args) + { + return c_api->Object_CallMethodByName_Int_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Long(ani_object object, const char *name, const char *signature, + ani_long *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Long_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Long_A(ani_object object, const char *name, const char *signature, + ani_long *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Long_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Long_V(ani_object object, const char *name, const char *signature, + ani_long *result, va_list args) + { + return c_api->Object_CallMethodByName_Long_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Float(ani_object object, const char *name, const char *signature, + ani_float *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Float_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Float_A(ani_object object, const char *name, const char *signature, + ani_float *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Float_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Float_V(ani_object object, const char *name, const char *signature, + ani_float *result, va_list args) + { + return c_api->Object_CallMethodByName_Float_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Double(ani_object object, const char *name, const char *signature, + ani_double *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Double_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Double_A(ani_object object, const char *name, const char *signature, + ani_double *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Double_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Double_V(ani_object object, const char *name, const char *signature, + ani_double *result, va_list args) + { + return c_api->Object_CallMethodByName_Double_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Ref(ani_object object, const char *name, const char *signature, ani_ref *result, + ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Object_CallMethodByName_Ref_V(this, object, name, signature, result, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Ref_A(ani_object object, const char *name, const char *signature, + ani_ref *result, const ani_value *args) + { + return c_api->Object_CallMethodByName_Ref_A(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Ref_V(ani_object object, const char *name, const char *signature, + ani_ref *result, va_list args) + { + return c_api->Object_CallMethodByName_Ref_V(this, object, name, signature, result, args); + } + ani_status Object_CallMethodByName_Void(ani_object object, const char *name, const char *signature, ...) + { + va_list args; + va_start(args, signature); + ani_status status = c_api->Object_CallMethodByName_Void_V(this, object, name, signature, args); + va_end(args); + return status; + } + ani_status Object_CallMethodByName_Void_A(ani_object object, const char *name, const char *signature, + const ani_value *args) + { + return c_api->Object_CallMethodByName_Void_A(this, object, name, signature, args); + } + ani_status Object_CallMethodByName_Void_V(ani_object object, const char *name, const char *signature, va_list args) + { + return c_api->Object_CallMethodByName_Void_V(this, object, name, signature, args); + } + ani_status Tuple_NewTupleValue(ani_tuple tuple, ani_tuple_value *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Tuple_NewTupleValue_V(this, tuple, result, args); + va_end(args); + return status; + } + ani_status Tuple_NewTupleValue_A(ani_tuple tuple, ani_tuple_value *result, const ani_value *args) + { + return c_api->Tuple_NewTupleValue_A(this, tuple, result, args); + } + ani_status Tuple_NewTupleValue_V(ani_tuple tuple, ani_tuple_value *result, va_list args) + { + return c_api->Tuple_NewTupleValue_V(this, tuple, result, args); + } + ani_status Tuple_GetNumberOfItems(ani_tuple tuple, ani_size *result) + { + return c_api->Tuple_GetNumberOfItems(this, tuple, result); + } + ani_status Tuple_GetItemKind(ani_tuple tuple, ani_size index, ani_kind *result) + { + return c_api->Tuple_GetItemKind(this, tuple, index, result); + } + ani_status Tuple_GetItemType(ani_tuple tuple, ani_size index, ani_type *result) + { + return c_api->Tuple_GetItemType(this, tuple, index, result); + } + ani_status TupleValue_GetTuple(ani_tuple_value value, ani_tuple *result) + { + return c_api->TupleValue_GetTuple(this, value, result); + } + ani_status TupleValue_GetItem_Boolean(ani_tuple_value tuple_value, ani_size index, ani_boolean *result) + { + return c_api->TupleValue_GetItem_Boolean(this, tuple_value, index, result); + } + ani_status TupleValue_GetItem_Char(ani_tuple_value tuple_value, ani_size index, ani_char *result) + { + return c_api->TupleValue_GetItem_Char(this, tuple_value, index, result); + } + ani_status TupleValue_GetItem_Byte(ani_tuple_value tuple_value, ani_size index, ani_byte *result) + { + return c_api->TupleValue_GetItem_Byte(this, tuple_value, index, result); + } + ani_status TupleValue_GetItem_Short(ani_tuple_value tuple_value, ani_size index, ani_short *result) + { + return c_api->TupleValue_GetItem_Short(this, tuple_value, index, result); + } + ani_status TupleValue_GetItem_Int(ani_tuple_value tuple_value, ani_size index, ani_int *result) + { + return c_api->TupleValue_GetItem_Int(this, tuple_value, index, result); + } + ani_status TupleValue_GetItem_Long(ani_tuple_value tuple_value, ani_size index, ani_long *result) + { + return c_api->TupleValue_GetItem_Long(this, tuple_value, index, result); + } + ani_status TupleValue_GetItem_Float(ani_tuple_value tuple_value, ani_size index, ani_float *result) + { + return c_api->TupleValue_GetItem_Float(this, tuple_value, index, result); + } + ani_status TupleValue_GetItem_Double(ani_tuple_value tuple_value, ani_size index, ani_double *result) + { + return c_api->TupleValue_GetItem_Double(this, tuple_value, index, result); + } + ani_status TupleValue_GetItem_Ref(ani_tuple_value tuple_value, ani_size index, ani_ref *result) + { + return c_api->TupleValue_GetItem_Ref(this, tuple_value, index, result); + } + ani_status TupleValue_SetItem_Boolean(ani_tuple_value tuple_value, ani_size index, ani_boolean value) + { + return c_api->TupleValue_SetItem_Boolean(this, tuple_value, index, value); + } + ani_status TupleValue_SetItem_Char(ani_tuple_value tuple_value, ani_size index, ani_char value) + { + return c_api->TupleValue_SetItem_Char(this, tuple_value, index, value); + } + ani_status TupleValue_SetItem_Byte(ani_tuple_value tuple_value, ani_size index, ani_byte value) + { + return c_api->TupleValue_SetItem_Byte(this, tuple_value, index, value); + } + ani_status TupleValue_SetItem_Short(ani_tuple_value tuple_value, ani_size index, ani_short value) + { + return c_api->TupleValue_SetItem_Short(this, tuple_value, index, value); + } + ani_status TupleValue_SetItem_Int(ani_tuple_value tuple_value, ani_size index, ani_int value) + { + return c_api->TupleValue_SetItem_Int(this, tuple_value, index, value); + } + ani_status TupleValue_SetItem_Long(ani_tuple_value tuple_value, ani_size index, ani_long value) + { + return c_api->TupleValue_SetItem_Long(this, tuple_value, index, value); + } + ani_status TupleValue_SetItem_Float(ani_tuple_value tuple_value, ani_size index, ani_float value) + { + return c_api->TupleValue_SetItem_Float(this, tuple_value, index, value); + } + ani_status TupleValue_SetItem_Double(ani_tuple_value tuple_value, ani_size index, ani_double value) + { + return c_api->TupleValue_SetItem_Double(this, tuple_value, index, value); + } + ani_status TupleValue_SetItem_Ref(ani_tuple_value tuple_value, ani_size index, ani_ref value) + { + return c_api->TupleValue_SetItem_Ref(this, tuple_value, index, value); + } + ani_status GlobalReference_Create(ani_ref ref, ani_gref *result) + { + return c_api->GlobalReference_Create(this, ref, result); + } + ani_status GlobalReference_Delete(ani_gref ref) + { + return c_api->GlobalReference_Delete(this, ref); + } + ani_status WeakReference_Create(ani_ref ref, ani_wref *result) + { + return c_api->WeakReference_Create(this, ref, result); + } + ani_status WeakReference_Delete(ani_wref wref) + { + return c_api->WeakReference_Delete(this, wref); + } + ani_status WeakReference_GetReference(ani_wref wref, ani_ref *result) + { + return c_api->WeakReference_GetReference(this, wref, result); + } + ani_status CreateArrayBuffer(size_t length, void **data_result, ani_arraybuffer *arraybuffer_result) + { + return c_api->CreateArrayBuffer(this, length, data_result, arraybuffer_result); + } + ani_status CreateArrayBufferExternal(void *external_data, size_t length, ani_finalizer finalizer, void *hint, + ani_arraybuffer *result) + { + return c_api->CreateArrayBufferExternal(this, external_data, length, finalizer, hint, result); + } + ani_status ArrayBuffer_GetInfo(ani_arraybuffer arraybuffer, void **data_result, size_t *length_result) + { + return c_api->ArrayBuffer_GetInfo(this, arraybuffer, data_result, length_result); + } + ani_status Reflection_FromMethod(ani_object method, ani_method *result) + { + return c_api->Reflection_FromMethod(this, method, result); + } + ani_status Reflection_ToMethod(ani_class cls, ani_method method, ani_object *result) + { + return c_api->Reflection_ToMethod(this, cls, method, result); + } + ani_status Reflection_FromField(ani_object field, ani_field *result) + { + return c_api->Reflection_FromField(this, field, result); + } + ani_status Reflection_ToField(ani_class cls, ani_field field, ani_object *result) + { + return c_api->Reflection_ToField(this, cls, field, result); + } + ani_status Reflection_FromStaticMethod(ani_object method, ani_static_method *result) + { + return c_api->Reflection_FromStaticMethod(this, method, result); + } + ani_status Reflection_ToStaticMethod(ani_class cls, ani_static_method method, ani_object *result) + { + return c_api->Reflection_ToStaticMethod(this, cls, method, result); + } + ani_status Reflection_FromStaticField(ani_object field, ani_static_field *result) + { + return c_api->Reflection_FromStaticField(this, field, result); + } + ani_status Reflection_ToStaticField(ani_class cls, ani_static_field field, ani_object *result) + { + return c_api->Reflection_ToStaticField(this, cls, field, result); + } + ani_status Reflection_FromFunction(ani_object function, ani_function *result) + { + return c_api->Reflection_FromFunction(this, function, result); + } + ani_status Reflection_ToFunction(ani_function function, ani_object *result) + { + return c_api->Reflection_ToFunction(this, function, result); + } + ani_status Reflection_FromVariable(ani_object variable, ani_variable *result) + { + return c_api->Reflection_FromVariable(this, variable, result); + } + ani_status Reflection_ToVariable(ani_variable variable, ani_object *result) + { + return c_api->Reflection_ToVariable(this, variable, result); + } + ani_status CLS_Register(void *initial_data, ani_finalizer finalizer, void *hint, ani_cls_slot *result) + { + return c_api->CLS_Register(this, initial_data, finalizer, hint, result); + } + ani_status CLS_Unregister(ani_cls_slot slot) + { + return c_api->CLS_Unregister(this, slot); + } + ani_status CLS_SetData(ani_cls_slot slot, void *data) + { + return c_api->CLS_SetData(this, slot, data); + } + ani_status CLS_GetData(ani_cls_slot slot, void **result) + { + return c_api->CLS_GetData(this, slot, result); + } + ani_status Coroutine_LaunchFunctionalObject(ani_fn_object fn, ani_size argc, ani_ref *argv, ani_promise *result) + { + return c_api->Coroutine_LaunchFunctionalObject(this, fn, argc, argv, result); + } + ani_status Coroutine_LaunchFunction(ani_function function, ani_promise *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Coroutine_LaunchFunction_V(this, function, result, args); + va_end(args); + return status; + } + ani_status Coroutine_LaunchFunction_A(ani_function function, ani_promise *result, const ani_value *args) + { + return c_api->Coroutine_LaunchFunction_A(this, function, result, args); + } + ani_status Coroutine_LaunchFunction_V(ani_function function, ani_promise *result, va_list args) + { + return c_api->Coroutine_LaunchFunction_V(this, function, result, args); + } + ani_status Coroutine_LaunchMethod(ani_object self, ani_function function, ani_promise *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Coroutine_LaunchMethod_V(this, self, function, result, args); + va_end(args); + return status; + } + ani_status Coroutine_LaunchMethod_A(ani_object self, ani_function function, ani_promise *result, + const ani_value *args) + { + return c_api->Coroutine_LaunchMethod_A(this, self, function, result, args); + } + ani_status Coroutine_LaunchMethod_V(ani_object self, ani_function function, ani_promise *result, va_list args) + { + return c_api->Coroutine_LaunchMethod_V(this, self, function, result, args); + } + ani_status Coroutine_LaunchStaticMethod(ani_class cls, ani_function function, ani_promise *result, ...) + { + va_list args; + va_start(args, result); + ani_status status = c_api->Coroutine_LaunchStaticMethod_V(this, cls, function, result, args); + va_end(args); + return status; + } + ani_status Coroutine_LaunchStaticMethod_A(ani_class cls, ani_function function, ani_promise *result, + const ani_value *args) + { + return c_api->Coroutine_LaunchStaticMethod_A(this, cls, function, result, args); + } + ani_status Coroutine_LaunchStaticMethod_V(ani_class cls, ani_function function, ani_promise *result, va_list args) + { + return c_api->Coroutine_LaunchStaticMethod_V(this, cls, function, result, args); + } + ani_status Coroutine_Await_Boolean(ani_promise promise, ani_boolean value) + { + return c_api->Coroutine_Await_Boolean(this, promise, value); + } + ani_status Coroutine_Await_Char(ani_promise promise, ani_char value) + { + return c_api->Coroutine_Await_Char(this, promise, value); + } + ani_status Coroutine_Await_Byte(ani_promise promise, ani_byte value) + { + return c_api->Coroutine_Await_Byte(this, promise, value); + } + ani_status Coroutine_Await_Short(ani_promise promise, ani_short value) + { + return c_api->Coroutine_Await_Short(this, promise, value); + } + ani_status Coroutine_Await_Int(ani_promise promise, ani_int value) + { + return c_api->Coroutine_Await_Int(this, promise, value); + } + ani_status Coroutine_Await_Long(ani_promise promise, ani_long value) + { + return c_api->Coroutine_Await_Long(this, promise, value); + } + ani_status Coroutine_Await_Float(ani_promise promise, ani_float value) + { + return c_api->Coroutine_Await_Float(this, promise, value); + } + ani_status Coroutine_Await_Double(ani_promise promise, ani_double value) + { + return c_api->Coroutine_Await_Double(this, promise, value); + } + ani_status Coroutine_Await_Ref(ani_promise promise, ani_ref value) + { + return c_api->Coroutine_Await_Ref(this, promise, value); + } +#endif // __cplusplus +}; + +// NOLINTEND +#endif // __ANI_H__ diff --git a/koala-wrapper/koalaui/interop/src/cpp/ani/convertors-ani.cc b/koala-wrapper/koalaui/interop/src/cpp/ani/convertors-ani.cc new file mode 100644 index 000000000..f41a2f5bf --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ani/convertors-ani.cc @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2022-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 "convertors-ani.h" +#include "signatures.h" +#include "interop-logging.h" +#include "interop-types.h" + +static const char* callCallbackFromNative = "callCallbackFromNative"; +static const char* callCallbackFromNativeSig = "I[BI:I"; + +static const char* FAST_NATIVE_PREFIX = "#F$"; + +const bool registerByOne = true; + +static bool registerNatives(ani_env *env, const ani_class clazz, const std::vector> impls) { + std::vector methods; + methods.reserve(impls.size()); + bool result = true; + for (const auto &[name, type, func, flag] : impls) { + ani_native_function method; + method.name = name.c_str(); + method.pointer = func; + method.signature = (flag & ANI_SLOW_NATIVE_FLAG) == 0 ? FAST_NATIVE_PREFIX : nullptr; + if (registerByOne) { + result &= env->Class_BindNativeMethods(clazz, &method, 1) == ANI_OK; + ani_boolean isError = false; + env->ExistUnhandledError(&isError); + if (isError) { + //env->ErrorDescribe(); + env->ResetError(); + } + } + else { + methods.push_back(method); + } + } + if (!registerByOne) { + result = env->Class_BindNativeMethods(clazz, methods.data(), static_cast(methods.size())) == ANI_OK; + } + return registerByOne ? true : result; +} + +bool registerAllModules(ani_env *env) { + auto moduleNames = AniExports::getInstance()->getModules(); + + for (auto it = moduleNames.begin(); it != moduleNames.end(); ++it) { + std::string classpath = AniExports::getInstance()->getClasspath(*it); + ani_class nativeModule = nullptr; + env->FindClass(classpath.c_str(), &nativeModule); + if (nativeModule == nullptr) { + LOGE("Cannot find managed class %s", classpath.c_str()); + continue; + } + if (!registerNatives(env, nativeModule, AniExports::getInstance()->getMethods(*it))) { + return false; + } + } + + return true; +} + +#if 0 +extern "C" ETS_EXPORT ets_int ETS_CALL EtsNapiOnLoad(ets_env *env) { + if (!registerAllModules(env)) { + LOGE("Failed to register ets modules"); + return ETS_ERR; + } + auto interopClasspath = AniExports::getInstance()->getClasspath("InteropNativeModule"); + auto interopClass = env->FindClass(interopClasspath.c_str()); + if (interopClass == nullptr) { + LOGE("Can not find InteropNativeModule classpath to set callback dispatcher"); + return ETS_ERR; + } + if (!setKoalaEtsNapiCallbackDispatcher(env, interopClass, callCallbackFromNative, callCallbackFromNativeSig)) { + LOGE("Failed to set koala ets callback dispatcher"); + return ETS_ERR; + } + return ETS_NAPI_VERSION_1_0; +} +#endif + +AniExports* AniExports::getInstance() { + static AniExports *instance = nullptr; + if (instance == nullptr) { + instance = new AniExports(); + } + return instance; +} + +std::vector AniExports::getModules() { + std::vector result; + for (auto it = implementations.begin(); it != implementations.end(); ++it) { + result.push_back(it->first); + } + return result; +} + +const std::vector>& AniExports::getMethods(const std::string& module) { + auto it = implementations.find(module); + if (it == implementations.end()) { + LOGE("Module %s is not registered", module.c_str()); + } + return it->second; +} + +void AniExports::addMethod(const char* module, const char *name, const char *type, void *impl, int flags) { + auto it = implementations.find(module); + if (it == implementations.end()) { + it = implementations.insert(std::make_pair(module, std::vector>())).first; + } + it->second.push_back(std::make_tuple(name, convertType(name, type), impl, flags)); +} + +void AniExports::setClasspath(const char* module, const char *classpath) { + auto it = classpaths.find(module); + if (it == classpaths.end()) { + classpaths.insert(std::make_pair(module, classpath)); + } else { + LOGE("Classpath for module %s was redefined", module); + } +} + +static std::map g_defaultClasspaths = { + {"InteropNativeModule", "@koalaui/interop/InteropNativeModule/InteropNativeModule"}, + // todo leave just InteropNativeModule, define others via KOALA_ETS_INTEROP_MODULE_CLASSPATH + {"TestNativeModule", "@koalaui/arkts-arkui/generated/arkts/TestNativeModule/TestNativeModule"}, + {"ArkUINativeModule", "@koalaui/arkts-arkui/generated/arkts/ArkUINativeModule/ArkUINativeModule"}, + {"ArkUIGeneratedNativeModule", "@koalaui/arkts-arkui/generated/arkts/ArkUIGeneratedNativeModule/ArkUIGeneratedNativeModule"}, +}; +const std::string& AniExports::getClasspath(const std::string& module) { + auto it = classpaths.find(module); + if (it != classpaths.end()) { + return it->second; + } + auto defaultClasspath = g_defaultClasspaths.find(module); + if (defaultClasspath != g_defaultClasspaths.end()) { + return defaultClasspath->second; + } + INTEROP_FATAL("Classpath for module %s was not registered", module.c_str()); +} diff --git a/koala-wrapper/koalaui/interop/src/cpp/ani/convertors-ani.h b/koala-wrapper/koalaui/interop/src/cpp/ani/convertors-ani.h new file mode 100644 index 000000000..3be74d311 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ani/convertors-ani.h @@ -0,0 +1,1378 @@ +/* + * Copyright (c) 2022-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 KOALA_ANI +#define KOALA_ANI + +#include +#include +#include +#include +#include +#include +#include + +#include "ani.h" +#include "koala-types.h" + +template +struct InteropTypeConverter { + using InteropType = T; + static T convertFrom(ani_env* env, InteropType value) { return value; } + static InteropType convertTo(ani_env* env, T value) { return value; } + static void release(ani_env* env, InteropType value, T converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = ani_string; + static KStringPtr convertFrom(ani_env* env, InteropType value) { + if (value == nullptr) return KStringPtr(); + KStringPtr result; + // Notice that we use UTF length for buffer size, but counter is expressed in number of Unicode chars. + ani_size lengthUtf8 = 0; + env->String_GetUTF8Size(value, &lengthUtf8); + result.resize(lengthUtf8); + ani_size lengthUtf16 = 0; + env->String_GetUTF16Size(value, &lengthUtf16); + ani_size count; + env->String_GetUTF8SubString(value, 0, lengthUtf16, result.data(), result.length(), &count); + return result; + } + static InteropType convertTo(ani_env* env, const KStringPtr& value) { + ani_string result; + env->String_NewUTF8(value.c_str(), value.length(), &result); + return result; + } + static void release(ani_env* env, InteropType value, const KStringPtr& converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = ani_long; + static KNativePointer convertFrom(ani_env* env, InteropType value) { + return reinterpret_cast(value); + } + static InteropType convertTo(ani_env* env, KNativePointer value) { + return reinterpret_cast(value); + } + static void release(ani_env* env, InteropType value, KNativePointer converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = ani_fixedarray_int; + static KInt* convertFrom(ani_env* env, InteropType value) { + if (!value) return nullptr; + ani_size length = 0; + env->FixedArray_GetLength(value, &length); + KInt* result = new KInt[length]; + env->FixedArray_GetRegion_Int(value, 0, length, result); + return result; + } + static InteropType convertTo(ani_env* env, KInt* value) = delete; + static void release(ani_env* env, InteropType value, KInt* converted) { + if (converted) delete [] converted; + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = ani_fixedarray_float; + static KFloat* convertFrom(ani_env* env, InteropType value) { + if (!value) return nullptr; + ani_size length = 0; + env->FixedArray_GetLength(value, &length); + KFloat* result = new KFloat[length]; + env->FixedArray_GetRegion_Float(value, 0, length, result); + return result; + } + static InteropType convertTo(ani_env* env, KFloat* value) = delete; + static void release(ani_env* env, InteropType value, KFloat* converted) { + if (converted) delete [] converted; + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = ani_fixedarray_byte; + static KByte* convertFrom(ani_env* env, InteropType value) { + if (!value) return nullptr; + ani_size length = 0; + env->FixedArray_GetLength(value, &length); + KByte* result = new KByte[length]; + env->FixedArray_GetRegion_Byte(value, 0, length, (ani_byte*)result); + return result; + } + static InteropType convertTo(ani_env* env, KByte* value) = delete; + static void release(ani_env* env, InteropType value, KByte* converted) { + if (converted) delete [] converted; + } +}; + +template <> struct InteropTypeConverter { + using InteropType = ani_double; + static KInteropNumber convertFrom(ani_env *env, InteropType value) { + return KInteropNumber::fromDouble(value); + } + static InteropType convertTo(ani_env *env, KInteropNumber value) { + return value.asDouble(); + } + static void release(ani_env *env, InteropType value, + KInteropNumber converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = ani_ref; + static KLength convertFrom(ani_env* env, InteropType value) { + // TODO: implement me + return KLength( { 0, 0, 0, 0}); + } + static InteropType convertTo(ani_env* env, KLength value) = delete; + static void release(ani_env* env, InteropType value, const KLength& converted) {} +}; + +template +inline typename InteropTypeConverter::InteropType makeResult(ani_env* env, Type value) { + return InteropTypeConverter::convertTo(env, value); +} + +template +inline Type getArgument(ani_env* env, typename InteropTypeConverter::InteropType arg) { + return InteropTypeConverter::convertFrom(env, arg); +} + +template +inline void releaseArgument(ani_env* env, typename InteropTypeConverter::InteropType arg, Type& data) { + InteropTypeConverter::release(env, arg, data); +} + +#define ANI_SLOW_NATIVE_FLAG 1 + +class AniExports { + std::unordered_map>> implementations; + std::unordered_map classpaths; + +public: + static AniExports* getInstance(); + + std::vector getModules(); + void addMethod(const char* module, const char* name, const char* type, void* impl, int flags); + const std::vector>& getMethods(const std::string& module); + + void setClasspath(const char* module, const char* classpath); + const std::string& getClasspath(const std::string& module); +}; + +#define KOALA_QUOTE0(x) #x +#define KOALA_QUOTE(x) KOALA_QUOTE0(x) + +#ifdef _MSC_VER +#define MAKE_ANI_EXPORT(module, name, type, flag) \ + static void __init_##name() { \ + AniExports::getInstance()->addMethod(KOALA_QUOTE(module), "_"#name, type, reinterpret_cast(Ani_##name), flag); \ + } \ + namespace { \ + struct __Init_##name { \ + __Init_##name() { __init_##name(); } \ + } __Init_##name##_v; \ + } +#define KOALA_ANI_INTEROP_MODULE_CLASSPATH(module, classpath) \ + static void __init_classpath_##module() { \ + AniExports::getInstance()->setClasspath(KOALA_QUOTE(module), classpath); \ + } \ + namespace { \ + struct __Init_classpath_##module { \ + __Init_classpath_##module() { __init_classpath_##module(); } \ + } __Init_classpath_##module##_v; \ + } +#else +#define MAKE_ANI_EXPORT(module, name, type, flag) \ + __attribute__((constructor)) \ + static void __init_ets_##name() { \ + AniExports::getInstance()->addMethod(KOALA_QUOTE(module), "_"#name, type, reinterpret_cast(Ani_##name), flag); \ + } +#define KOALA_ANI_INTEROP_MODULE_CLASSPATH(module, classpath) \ + __attribute__((constructor)) \ + static void __init_ani_classpath_##module() { \ + AniExports::getInstance()->setClasspath(KOALA_QUOTE(module), classpath); \ + } +#endif + +#define KOALA_INTEROP_0(name, Ret) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz) { \ + KOALA_MAYBE_LOG(name) \ + return makeResult(env, impl_##name()); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret, 0) + +#define KOALA_INTEROP_1(name, Ret, P0) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + auto rv = makeResult(env, impl_##name(p0)); \ + releaseArgument(env, _p0, p0); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0, 0) + +#define KOALA_INTEROP_2(name, Ret, P0, P1) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + auto rv = makeResult(env, impl_##name(p0, p1)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1, 0) + +#define KOALA_INTEROP_3(name, Ret, P0, P1, P2) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2, 0) + +#define KOALA_INTEROP_4(name, Ret, P0, P1, P2, P3) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3, 0) + +#define KOALA_INTEROP_5(name, Ret, P0, P1, P2, P3, P4) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4, 0) + +#define KOALA_INTEROP_6(name, Ret, P0, P1, P2, P3, P4, P5) \ +InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5, 0) + +#define KOALA_INTEROP_7(name, Ret, P0, P1, P2, P3, P4, P5, P6) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6, 0) + +#define KOALA_INTEROP_8(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7, 0) + +#define KOALA_INTEROP_9(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + return rv; \ + } \ + MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8, 0) + +#define KOALA_INTEROP_10(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9, 0) + +#define KOALA_INTEROP_11(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10, 0) + +#define KOALA_INTEROP_12(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11, 0) + +#define KOALA_INTEROP_13(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + return rv; \ + } \ + MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12, 0) + +#define KOALA_INTEROP_14(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13, 0) + +#define KOALA_INTEROP_V0(name) \ + void Ani_##name(ani_env *env) { \ + KOALA_MAYBE_LOG(name) \ + impl_##name(); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void", 0) + +#define KOALA_INTEROP_V1(name, P0) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + impl_##name(p0); \ + releaseArgument(env, _p0, p0); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0, 0) + +#define KOALA_INTEROP_V2(name, P0, P1) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + impl_##name(p0, p1); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1, 0) + +#define KOALA_INTEROP_V3(name, P0, P1, P2) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + impl_##name(p0, p1, p2); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2, 0) + +#define KOALA_INTEROP_V4(name, P0, P1, P2, P3) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + impl_##name(p0, p1, p2, p3); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ +} \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3, 0) + +#define KOALA_INTEROP_V5(name, P0, P1, P2, P3, P4) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + impl_##name(p0, p1, p2, p3, p4); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ +} \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4, 0) + +#define KOALA_INTEROP_V6(name, P0, P1, P2, P3, P4, P5) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + impl_##name(p0, p1, p2, p3, p4, p5); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5, 0) + +#define KOALA_INTEROP_V7(name, P0, P1, P2, P3, P4, P5, P6) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6, 0) + +#define KOALA_INTEROP_V8(name, P0, P1, P2, P3, P4, P5, P6, P7) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7, 0) + +#define KOALA_INTEROP_V9(name, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8, 0) + +#define KOALA_INTEROP_V10(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ +} \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9, 0) + +#define KOALA_INTEROP_V11(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10, 0) + +#define KOALA_INTEROP_V12(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ +} \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11, 0) + +#define KOALA_INTEROP_V13(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ +} \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12, 0) + +#define KOALA_INTEROP_V14(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ +} \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13, 0) + +#define KOALA_INTEROP_V15(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13, \ + InteropTypeConverter::InteropType _p14) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + P14 p14 = getArgument(env, _p14); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ + releaseArgument(env, _p14, p14); \ +} \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13 "|" #P14, 0) + +#define KOALA_INTEROP_CTX_0(name, Ret) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz) { \ + KOALA_MAYBE_LOG(name) \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx)); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_1(name, Ret, P0) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0)); \ + releaseArgument(env, _p0, p0); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_2(name, Ret, P0, P1) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0, p1)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_3(name, Ret, P0, P1, P2) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0, p1, p2)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_4(name, Ret, P0, P1, P2, P3) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0, p1, p2, p3)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_5(name, Ret, P0, P1, P2, P3, P4) \ + InteropTypeConverter::InteropType Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3 \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0, p1, p2, p3, p4)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + return rv; \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V0(name) \ + void Ani_##name(ani_env *env, ani_class clazz) { \ + KOALA_MAYBE_LOG(name) \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void", ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V1(name, P0) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0); \ + releaseArgument(env, _p0, p0); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V2(name, P0, P1) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V3(name, P0, P1, P2) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V4(name, P0, P1, P2, P3) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2, p3); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3, ANI_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V5(name, P0, P1, P2, P3, P4) \ + void Ani_##name(ani_env *env, ani_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2, p3, p4); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + } \ +MAKE_ANI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4, ANI_SLOW_NATIVE_FLAG) + +bool setKoalaEtsNapiCallbackDispatcher( + ani_env* ani_env, + ani_class clazz, + const char* dispatcherMethodName, + const char* dispactherMethodSig +); +void getKoalaEtsNapiCallbackDispatcher(ani_class* clazz, ani_method* method); + +#if 0 +#define KOALA_INTEROP_CALL_VOID(venv, id, length, args) \ +{ \ + ani_class clazz = nullptr; \ + ani_method method = nullptr; \ + getKoalaEtsNapiCallbackDispatcher(&clazz, &method); \ + ani_env* ani_env = reinterpret_cast(vmContext); \ + ani_env->PushLocalFrame(1); \ + ani_fixedarray_byte args_ets = ani_env->NewByteArray(length); \ + ani_env->SetByteArrayRegion(args_ets, 0, length, reinterpret_cast(args)); \ + ani_env->CallStaticIntMethod(clazz, method, id, args_ets, length); \ + ani_env->GetByteArrayRegion(args_ets, 0, length, reinterpret_cast(args)); \ + ani_env->PopLocalFrame(nullptr); \ +} + +#define KOALA_INTEROP_CALL_INT(venv, id, length, args) \ +{ \ + ani_class clazz = nullptr; \ + ani_method method = nullptr; \ + getKoalaEtsNapiCallbackDispatcher(&clazz, &method); \ + ani_env* ani_env = reinterpret_cast(venv); \ + ani_env->PushLocalFrame(1); \ + ani_fixedarray_byte args_ets = ani_env->NewByteArray(length); \ + ani_env->SetByteArrayRegion(args_ets, 0, length, reinterpret_cast(args)); \ + int32_t rv = ani_env->CallStaticIntMethod(clazz, method, id, args_ets, length); \ + ani_env->GetByteArrayRegion(args_ets, 0, length, reinterpret_cast(args)); \ + ani_env->PopLocalFrame(nullptr); \ + return rv; \ +} + +#define KOALA_INTEROP_CALL_VOID_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_VOID(venv, id, (argc) * sizeof(int32_t), args) +#define KOALA_INTEROP_CALL_INT_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_INT(venv, id, (argc) * sizeof(int32_t), args) + +#define KOALA_INTEROP_THROW(vmContext, object, ...) \ + do { \ + ani_env* env = reinterpret_cast(vmContext); \ + env->ThrowError(object); \ + return __VA_ARGS__; \ + } while (0) + +#define KOALA_INTEROP_THROW_STRING(vmContext, message, ...) \ + do { \ + ani_env* env = reinterpret_cast(vmContext); \ + const static ani_class errorClass = env->FindClass("std/core/Error"); \ + env->ThrowErrorNew(errorClass, message); \ + } while (0) +#else + +#define KOALA_INTEROP_CALL_VOID(venv, id, length, args) +#define KOALA_INTEROP_CALL_INT(venv, id, length, args) { return 0; } +#define KOALA_INTEROP_CALL_VOID_INTS32(venv, id, argc, args) { return; } +#define KOALA_INTEROP_CALL_INT_INTS32(venv, id, argc, args) { return 0; } +#define KOALA_INTEROP_THROW(vmContext, object, ...) { return __VA_ARGS__; } +#define KOALA_INTEROP_THROW_STRING(vmContext, message, ...) { return __VA_ARGS__; } +#endif + +#endif // KOALA_ETS_NAPI diff --git a/koala-wrapper/koalaui/interop/src/cpp/callback-resource.cc b/koala-wrapper/koalaui/interop/src/cpp/callback-resource.cc new file mode 100644 index 000000000..d7851e405 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/callback-resource.cc @@ -0,0 +1,95 @@ +/* + * 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. + */ + +#define KOALA_INTEROP_MODULE InteropNativeModule +#include "common-interop.h" +#include "interop-types.h" +#include "callback-resource.h" +#include +#include + + +static bool needReleaseFront = false; +static std::deque callbackEventsQueue; +static std::deque callbackCallSubqueue; +static std::deque callbackResourceSubqueue; + +void enqueueCallback(const CallbackBuffer* event) { + callbackEventsQueue.push_back(Event_CallCallback); + callbackCallSubqueue.push_back(*event); +} + +void holdManagedCallbackResource(InteropInt32 resourceId) { + callbackEventsQueue.push_back(Event_HoldManagedResource); + callbackResourceSubqueue.push_back(resourceId); +} + +void releaseManagedCallbackResource(InteropInt32 resourceId) { + callbackEventsQueue.push_back(Event_ReleaseManagedResource); + callbackResourceSubqueue.push_back(resourceId); +} + +KInt impl_CheckCallbackEvent(KByte* result, KInt size) { + if (needReleaseFront) + { + switch (callbackEventsQueue.front()) + { + case Event_CallCallback: + callbackCallSubqueue.front().resourceHolder.release(); + callbackCallSubqueue.pop_front(); + break; + case Event_HoldManagedResource: + case Event_ReleaseManagedResource: + callbackResourceSubqueue.pop_front(); + break; + default: + INTEROP_FATAL("Unknown event kind"); + } + callbackEventsQueue.pop_front(); + needReleaseFront = false; + } + if (callbackEventsQueue.empty()) { + return 0; + } + const CallbackEventKind frontEventKind = callbackEventsQueue.front(); + memcpy(result, &frontEventKind, 4); + switch (frontEventKind) + { + case Event_CallCallback: + memcpy(result + 4, callbackCallSubqueue.front().buffer, sizeof(CallbackBuffer::buffer)); + break; + case Event_HoldManagedResource: + case Event_ReleaseManagedResource: { + const InteropInt32 resourceId = callbackResourceSubqueue.front(); + memcpy(result + 4, &resourceId, 4); + break; + } + default: + INTEROP_FATAL("Unknown event kind"); + } + needReleaseFront = true; + return 1; +} +KOALA_INTEROP_2(CheckCallbackEvent, KInt, KByte*, KInt) + +void impl_ReleaseCallbackResource(InteropInt32 resourceId) { + releaseManagedCallbackResource(resourceId); +} +KOALA_INTEROP_V1(ReleaseCallbackResource, KInt) + +void impl_HoldCallbackResource(InteropInt32 resourceId) { + holdManagedCallbackResource(resourceId); +} +KOALA_INTEROP_V1(HoldCallbackResource, KInt) diff --git a/koala-wrapper/koalaui/interop/src/cpp/callback-resource.h b/koala-wrapper/koalaui/interop/src/cpp/callback-resource.h new file mode 100644 index 000000000..451e4a3db --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/callback-resource.h @@ -0,0 +1,55 @@ +/* + * 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 _INTEROP_CALLBACK_RESOURCE_H +#define _INTEROP_CALLBACK_RESOURCE_H + +#include +#include "interop-types.h" + + +class CallbackResourceHolder { +private: + std::vector heldResources; +public: + void holdCallbackResource(const InteropCallbackResource* resource) { + resource->hold(resource->resourceId); + this->heldResources.push_back(*resource); + } + void release() { + for (auto resource : this->heldResources) { + resource.release(resource.resourceId); + } + this->heldResources.clear(); + } +}; + +struct CallbackBuffer { + InteropInt32 kind; + uint8_t buffer[60 * 4]; + CallbackResourceHolder resourceHolder; +}; + +enum CallbackEventKind { + Event_CallCallback = 0, + Event_HoldManagedResource = 1, + Event_ReleaseManagedResource = 2, +}; + +void enqueueCallback(const CallbackBuffer* event); +void holdManagedCallbackResource(InteropInt32 resourceId); +void releaseManagedCallbackResource(InteropInt32 resourceId); + +#endif diff --git a/koala-wrapper/koalaui/interop/src/cpp/cangjie/convertors-cj.cc b/koala-wrapper/koalaui/interop/src/cpp/cangjie/convertors-cj.cc new file mode 100644 index 000000000..0a26aa8d9 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/cangjie/convertors-cj.cc @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2022-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. + */ \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/cangjie/convertors-cj.h b/koala-wrapper/koalaui/interop/src/cpp/cangjie/convertors-cj.h new file mode 100644 index 000000000..17949006b --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/cangjie/convertors-cj.h @@ -0,0 +1,875 @@ +/* + * Copyright (c) 2022-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. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include "koala-types.h" + +#define KOALA_INTEROP_EXPORT extern "C" + +#define MAKE_CJ_EXPORT(name, type, flag) \ + __attribute__((constructor)) \ + static void __init_ets_##name() { \ + CJExports::getInstance()->addImpl("_"#name, type, reinterpret_cast(Ark_##name), flag); \ + } + +class CJExports { + std::vector> implementations; + +public: + static CJExports* getInstance(); + + void addImpl(const char* name, const char* type, void* impl); + const std::vector>& getImpls() { + return implementations; + } +}; + +template +struct InteropTypeConverter { + using InteropType = T; + static inline T convertFrom(InteropType value) { return value; } + static inline InteropType convertTo(T value) { return value; } +}; + +template +inline T getArgument(typename InteropTypeConverter::InteropType arg) { + return InteropTypeConverter::convertFrom(arg); +} + +template +inline typename InteropTypeConverter::InteropType makeResult(T value) { + return InteropTypeConverter::convertTo(value); +} + +template<> +struct InteropTypeConverter { + using InteropType = KDouble; + static inline KInteropNumber convertFrom(InteropType value) { + return KInteropNumber::fromDouble(value); + } + static inline InteropType convertTo(KInteropNumber value) { + return value.asDouble(); + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = char*; + static KStringPtr convertFrom(InteropType value) { + return KStringPtr(value); + } + static InteropType convertTo(const KStringPtr& value) { + return value.data(); + } +}; + +// TODO: Rewrite all others to typed convertors. + +#define KOALA_INTEROP_0(name, Ret) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name() { \ + KOALA_MAYBE_LOG(name) \ + return makeResult(impl_##name()); \ +} +// MAKE_CJ_EXPORT(name, #Ret, 0) + +#define KOALA_INTEROP_1(name, Ret, P0) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name(InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + return makeResult(impl_##name(p0)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0, 0) + +#define KOALA_INTEROP_2(name, Ret, P0, P1) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + return makeResult(impl_##name(p0, p1)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1, 0) + +#define KOALA_INTEROP_3(name, Ret, P0, P1, P2) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + return makeResult(impl_##name(p0, p1, p2)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2, 0) + +#define KOALA_INTEROP_4(name, Ret, P0, P1, P2, P3) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + return makeResult(impl_##name(p0, p1, p2, p3)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3, 0) + +#define KOALA_INTEROP_5(name, Ret, P0, P1, P2, P3, P4) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4, 0) + +#define KOALA_INTEROP_6(name, Ret, P0, P1, P2, P3, P4, P5) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5, 0) + +#define KOALA_INTEROP_7(name, Ret, P0, P1, P2, P3, P4, P5, P6) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6, 0) + +#define KOALA_INTEROP_8(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7, 0) + +#define KOALA_INTEROP_9(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8, 0) + +#define KOALA_INTEROP_10(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9, 0) + +#define KOALA_INTEROP_11(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10, 0) + +#define KOALA_INTEROP_12(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11, 0) + +#define KOALA_INTEROP_13(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + P12 p12 = getArgument(_p12); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12, 0) + +#define KOALA_INTEROP_14(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + P12 p12 = getArgument(_p12); \ + P13 p13 = getArgument(_p13); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13)); \ +} +// MAKE_CJ_EXPORT(name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13, 0) + +#define KOALA_INTEROP_V0(name) \ +KOALA_INTEROP_EXPORT void name() { \ + KOALA_MAYBE_LOG(name) \ + impl_##name(); \ + return; \ +} + +#define KOALA_INTEROP_V1(name, P0) \ +KOALA_INTEROP_EXPORT void name(typename InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + impl_##name(p0); \ + return; \ +} + +#define KOALA_INTEROP_V2(name, P0, P1) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + impl_##name(p0, p1); \ + return; \ +} + +#define KOALA_INTEROP_V3(name, P0, P1, P2) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + impl_##name(p0, p1, p2); \ + return; \ +} + +#define KOALA_INTEROP_V4(name, P0, P1, P2, P3) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + impl_##name(p0, p1, p2, p3); \ + return; \ +} + +#define KOALA_INTEROP_V5(name, P0, P1, P2, P3, P4) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + impl_##name(p0, p1, p2, p3, p4); \ + return; \ +} + +#define KOALA_INTEROP_V6(name, P0, P1, P2, P3, P4, P5) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + impl_##name(p0, p1, p2, p3, p4, p5); \ + return; \ +} + +#define KOALA_INTEROP_V7(name, P0, P1, P2, P3, P4, P5, P6) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6); \ + return; \ +} + +#define KOALA_INTEROP_V8(name, P0, P1, P2, P3, P4, P5, P6, P7) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7); \ + return; \ +} + +#define KOALA_INTEROP_V9(name, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8); \ + return; \ +} + +#define KOALA_INTEROP_V10(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \ + return; \ +} + +#define KOALA_INTEROP_V11(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9, \ + typename InteropTypeConverter::InteropType _p10 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); \ + return; \ +} + +#define KOALA_INTEROP_V12(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9, \ + typename InteropTypeConverter::InteropType _p10, \ + typename InteropTypeConverter::InteropType _p11 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); \ + return; \ +} + +#define KOALA_INTEROP_V13(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9, \ + typename InteropTypeConverter::InteropType _p10, \ + typename InteropTypeConverter::InteropType _p11, \ + typename InteropTypeConverter::InteropType _p12 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + P12 p12 = getArgument(_p12); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); \ + return; \ +} + +#define KOALA_INTEROP_V14(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9, \ + typename InteropTypeConverter::InteropType _p10, \ + typename InteropTypeConverter::InteropType _p11, \ + typename InteropTypeConverter::InteropType _p12, \ + typename InteropTypeConverter::InteropType _p13 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + P12 p12 = getArgument(_p12); \ + P13 p13 = getArgument(_p13); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); \ + return; \ +} + +#define KOALA_INTEROP_CTX_0(name, Ret) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name() { \ + KOALA_MAYBE_LOG(name) \ + KVMContext ctx = (KVMContext)0; \ + return makeResult(impl_##name(ctx)); \ +} + +#define KOALA_INTEROP_CTX_1(name, Ret, P0) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name(InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + KVMContext ctx = (KVMContext)0; \ + return makeResult(impl_##name(ctx, p0)); \ +} + +#define KOALA_INTEROP_CTX_2(name, Ret, P0, P1) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name(InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + KVMContext ctx = (KVMContext)0; \ + return makeResult(impl_##name(ctx, p0, p1)); \ +} + + +#define KOALA_INTEROP_CTX_3(name, Ret, P0, P1, P2) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + KVMContext ctx = (KVMContext)0; \ + return makeResult(impl_##name(ctx, p0, p1, p2)); \ +} + +#define KOALA_INTEROP_CTX_4(name, Ret, P0, P1, P2, P3) \ +KOALA_INTEROP_EXPORT InteropTypeConverter::InteropType name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + KVMContext ctx = (KVMContext)0; \ + return makeResult(impl_##name(ctx, p0, p1, p2, p3)); \ +} + + +#define KOALA_INTEROP_CALL_INT(venv, id, length, args) \ +{ \ + int32_t rv = 0; \ + return rv; \ +} +#define KOALA_INTEROP_CALL_VOID(venv, id, length, args) \ +{ \ +} + + +#define KOALA_INTEROP_CALL_VOID_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_VOID(venv, id, (argc) * sizeof(int32_t), args) +#define KOALA_INTEROP_CALL_INT_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_INT(venv, id, (argc) * sizeof(int32_t), args) + + +#define KOALA_INTEROP_CTX_V1(name, P0) \ +KOALA_INTEROP_EXPORT void name(InteropTypeConverter::InteropType _p0) {\ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + impl_##name(nullptr, p0); \ +} + +#define KOALA_INTEROP_CTX_V2(name, P0, P1) \ +KOALA_INTEROP_EXPORT void name(InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + impl_##name(nullptr, p0, p1); \ +} + +#define KOALA_INTEROP_CTX_V3(name, P0, P1, P2) \ +KOALA_INTEROP_EXPORT void name(InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + impl_##name(nullptr, p0, p1, p2); \ +} + +#define KOALA_INTEROP_CTX_V4(name, P0, P1, P2, P3) \ +KOALA_INTEROP_EXPORT void name(InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + impl_##name(nullptr, p0, p1, p2, p3); \ +} + +#define KOALA_INTEROP_CTX_V5(name, P0, P1, P2, P3, P4) \ +KOALA_INTEROP_EXPORT void name(InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + impl_##name(nullptr, p0, p1, p2, p3, p4); \ +} + +#define KOALA_INTEROP_THROW(vmContext, object, ...) \ + do { \ + /* TODO: implement*/ assert(false); \ + return __VA_ARGS__; \ + } while (0) + +#define KOALA_INTEROP_THROW_STRING(vmContext, message, ...) \ + do { \ + /* TODO: implement*/ assert(false); \ + return __VA_ARGS__; \ + } while (0) diff --git a/koala-wrapper/koalaui/interop/src/cpp/common-interop.cc b/koala-wrapper/koalaui/interop/src/cpp/common-interop.cc new file mode 100644 index 000000000..ec6572c6d --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/common-interop.cc @@ -0,0 +1,469 @@ +/* + * Copyright (c) 2022-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 + +#ifdef KOALA_INTEROP_MODULE +#undef KOALA_INTEROP_MODULE +#endif + +#define KOALA_INTEROP_MODULE InteropNativeModule +#include "common-interop.h" +#include "interop-logging.h" +#include "dynamic-loader.h" + + +#if KOALA_INTEROP_PROFILER +#include "profiler.h" + +InteropProfiler* InteropProfiler::_instance = nullptr; + +#endif + +using std::string; + +#ifdef KOALA_NAPI +// Callback dispatcher MOVED to convertors-napi.cc. +// Let's keep platform-specific parts of the code together + +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 }; +} +KOALA_INTEROP_5(MaterializeBuffer, KInteropBuffer, KNativePointer, KLong, KInt, KNativePointer, KNativePointer) + +KNativePointer impl_GetNativeBufferPointer(KInteropBuffer buffer) { + return buffer.data; +} +KOALA_INTEROP_1(GetNativeBufferPointer, KNativePointer, KInteropBuffer) + +#endif + +#ifdef KOALA_ETS_NAPI +#include "etsapi.h" + +static struct { + 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; +} + +void getKoalaEtsNapiCallbackDispatcher(ets_class* clazz, ets_method* method) { + *clazz = g_koalaEtsNapiCallbackDispatcher.clazz; + *method = g_koalaEtsNapiCallbackDispatcher.method; +} +#endif + +#ifdef KOALA_JNI +#include "jni.h" +static struct { + 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; +} + +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(); +} +KOALA_INTEROP_1(StringLength, KInt, KNativePointer) + +void impl_StringData(KNativePointer ptr, KByte* bytes, KUInt size) { + string* s = reinterpret_cast(ptr); + if (s) memcpy(bytes, s->c_str(), size); +} +KOALA_INTEROP_V3(StringData, KNativePointer, KByte*, KUInt) + + +#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; +} +KOALA_INTEROP_CTX_1(StringDataBytes, KInteropBuffer, KNativePointer) +#endif + +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, KByte* buffer, KInt offset) { + memcpy(buffer + offset, string.c_str(), string.length() + 1); + return string.length() + 1; +} +KOALA_INTEROP_3(ManagedStringWrite, KInt, KStringPtr, KByte*, KInt) + +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); +} +KOALA_INTEROP_V2(InvokeFinalizer, KNativePointer, KNativePointer) + +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); +} +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)); +} + +std::vector makeStringVector(KStringArray strArray) { + if (strArray == nullptr) { + return std::vector(0); + } + KUInt arraySize = unpackUInt(strArray); + std::vector res(arraySize); + size_t offset = sizeof(KUInt); + for (KUInt i = 0; i < arraySize; ++i) { + int len = unpackUInt(strArray + offset); + res[i].assign((const char*)(strArray + offset + sizeof(KUInt)), len); + offset += len + sizeof(KUInt); + } + return res; +} + +std::vector makeStringVector(KNativePointerArray arr, KInt length) { + if (arr == nullptr) { + return std::vector(0); + } else { + std::vector res(length); + char** strings = reinterpret_cast(arr); + for (KInt i = 0; i < length; ++i) { + const char* str = reinterpret_cast(strings[i]); + res[i].assign(str); + } + return res; + } +} + +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); +} +KOALA_INTEROP_V1(StartGroupedLog, KInt) + +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()); +} +KOALA_INTEROP_V2(AppendGroupedLog, KInt, KStringPtr) + +void impl_PrintGroupedLog(KInt index) { +#ifdef KOALA_OHOS + LOGI("%" LOG_PUBLIC "s", GetDefaultLogger()->getGroupedLog(index)); +#else + 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); +#else + return 0; +#endif +} + +struct ForeignVMContext { + KVMContext vmContext; + int32_t (*callSync)(KVMContext vmContext, int32_t callback, uint8_t* data, int32_t length); +}; +typedef KInt (*LoadVirtualMachine_t)(KInt vmKind, const char* classPath, const char* libraryPath, const struct ForeignVMContext* foreignVM); +typedef KNativePointer (*StartApplication_t)(const char* appUrl, const char* appParams); +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); + +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) + "/" + +#endif + 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& classPath, 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* appClassPath = envClassPath ? envClassPath : classPath.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, appClassPath, nativeLibPath, &foreignVM); +} +KOALA_INTEROP_CTX_3(LoadVirtualMachine, KInt, KInt, KStringPtr, KStringPtr) + +KNativePointer impl_StartApplication(const KStringPtr& appUrl, const KStringPtr& appParams) { + static StartApplication_t impl = nullptr; + if (!impl) impl = reinterpret_cast(getImpl(nullptr, "StartApplication")); + return impl(appUrl.c_str(), appParams.c_str()); +} +KOALA_INTEROP_2(StartApplication, KNativePointer, KStringPtr, KStringPtr) + +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; +} +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()); +} +KOALA_INTEROP_V1(RestartWith, KStringPtr) + +static Callback_Caller_t g_callbackCaller = nullptr; +void setCallbackCaller(Callback_Caller_t callbackCaller) { + g_callbackCaller = callbackCaller; +} + +void impl_CallCallback(KInt callbackKind, KByte* args, KInt argsSize) { + if (g_callbackCaller) { + g_callbackCaller(callbackKind, args, argsSize); + } +} +KOALA_INTEROP_V3(CallCallback, KInt, KByte*, KInt) + +static Callback_Caller_Sync_t g_callbackCallerSync = nullptr; +void setCallbackCallerSync(Callback_Caller_Sync_t callbackCallerSync) { + g_callbackCallerSync = callbackCallerSync; +} + +void impl_CallCallbackSync(KVMContext vmContext, KInt callbackKind, KByte* args, KInt argsSize) { + if (g_callbackCallerSync) { + g_callbackCallerSync(vmContext, callbackKind, args, argsSize); + } +} +KOALA_INTEROP_CTX_V3(CallCallbackSync, KInt, KByte*, KInt) + +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); +} +KOALA_INTEROP_V2(CallCallbackResourceReleaser, KNativePointer, KInt) + +KInt impl_CallForeignVM(KNativePointer foreignContextRaw, KInt function, KByte* data, KInt length) { + const ForeignVMContext* foreignContext = (const ForeignVMContext*)foreignContextRaw; + // TODO: 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, data, length); +} +KOALA_INTEROP_4(CallForeignVM, KInt, KNativePointer, KInt, KByte*, KInt) + + +#define __QUOTE(x) #x +#define QUOTE(x) __QUOTE(x) + +void impl_NativeLog(const KStringPtr& str) { +#ifdef KOALA_OHOS + 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); +#endif +} +KOALA_INTEROP_V1(NativeLog, KStringPtr) + + + +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); + napi_release_threadsafe_function((napi_threadsafe_function)deferred->handler, napi_tsfn_release); +#endif +} + +void rejectDeferred(KVMDeferred* deferred, const char* message) { +#ifdef KOALA_NAPI + napi_release_threadsafe_function((napi_threadsafe_function)deferred->handler, napi_tsfn_release); + delete deferred; +#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; +#ifdef KOALA_NAPI + // TODO: move to interop! + napi_env env = (napi_env)vmContext; + napi_value promise; + napi_value resourceName; + napi_create_string_utf8(env, "Async", 5, &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 + return deferred; +} + +#if defined(KOALA_ETS_NAPI) || 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; +} +KOALA_INTEROP_CTX_3(Utf8ToString, KStringPtr, KByte*, KInt, KInt) + +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) +#endif + +#if defined(KOALA_JNI) || defined(KOALA_NAPI) || defined(KOALA_CJ) +KInteropReturnBuffer impl_RawReturnData(KVMContext vmContext, KInt v1, KInt v2) { + void* data = new int8_t[v1]; + memset(data, v2, v1); + KInteropReturnBuffer buffer = { v1, data, [](KNativePointer ptr, KInt) { delete[] (int8_t*)ptr; }}; + return buffer; +} +KOALA_INTEROP_CTX_2(RawReturnData, KInteropReturnBuffer, KInt, KInt) +#endif diff --git a/koala-wrapper/koalaui/interop/src/cpp/common-interop.h b/koala-wrapper/koalaui/interop/src/cpp/common-interop.h new file mode 100644 index 000000000..abc8ebfd0 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/common-interop.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022-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 COMMON_INTEROP_BASE_H +#define COMMON_INTEROP_BASE_H + +#include + +#include "koala-types.h" + +#define KOALA_INTEROP_PROFILER 0 +#define KOALA_INTEROP_TRACER 0 + +#if KOALA_INTEROP_PROFILER +#include "profiler.h" +#define KOALA_INTEROP_LOGGER(name) InteropMethodCall logger(#name); +#endif + +#if KOALA_INTEROP_TRACER +#include "tracer.h" +#define KOALA_INTEROP_LOGGER(name) InteropMethodCall logger(#name); +#endif + + +#ifdef KOALA_INTEROP_LOGGER +#define KOALA_MAYBE_LOG(name) KOALA_INTEROP_LOGGER(name); +#else +#define KOALA_MAYBE_LOG(name) +#endif + +typedef void (*Callback_Caller_t)(KInt callbackKind, KByte* argsData, KInt argsLength); +typedef void (*Callback_Caller_Sync_t)(KVMContext vmContext, KInt callbackKind, KByte* argsData, KInt argsLength); +void setCallbackCaller(Callback_Caller_t caller); +void setCallbackCallerSync(Callback_Caller_Sync_t callerSync); + +KVMDeferred* CreateDeferred(KVMContext context, KVMObjectHandle* promise); + +std::vector makeStringVector(KStringArray strArray); +std::vector makeStringVector(KNativePointerArray arr, KInt size); + +#if KOALA_USE_NODE_VM || KOALA_USE_HZ_VM +#include "convertors-napi.h" +#elif KOALA_USE_JSC_VM +#include "convertors-jsc.h" +#elif KOALA_ETS_NAPI +#include "convertors-ets.h" +#elif KOALA_USE_JAVA_VM +#include "convertors-jni.h" +#elif KOALA_WASM +#include "convertors-wasm.h" +#elif KOALA_CJ +#include "convertors-cj.h" +#elif KOALA_ANI +#include "convertors-ani.h" +#else +#error "One of above branches must be taken" +#endif + +#endif // COMMON_INTEROP_BASE_H diff --git a/koala-wrapper/koalaui/interop/src/cpp/crashdump.h b/koala-wrapper/koalaui/interop/src/cpp/crashdump.h new file mode 100644 index 000000000..7d1bac040 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/crashdump.h @@ -0,0 +1,43 @@ +/* + * 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 _INTEROP_CRASHDUMP_H +#define _INTEROP_CRASHDUMP_H + +#ifdef KOALA_LINUX +#include +#include + +sighandler_t oldCrashHandler = nullptr; + +static void onCrashHandler(int signo) { + void* stack[20]; + size_t size = backtrace(stack, 20); + backtrace_symbols_fd(stack, size, STDERR_FILENO); + if (oldCrashHandler) oldCrashHandler(signo); +} + +static void installCrashHandlers() { + static bool installed = false; + if (!installed) { + oldCrashHandler = signal(SIGSEGV, onCrashHandler); + installed = true; + } +} +#else +static void installCrashHandlers() {} +#endif + +#endif // _INTEROP_CRASHDUMP_H \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/dynamic-loader.h b/koala-wrapper/koalaui/interop/src/cpp/dynamic-loader.h new file mode 100644 index 000000000..f354a4f25 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/dynamic-loader.h @@ -0,0 +1,110 @@ +/* + * 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 _DYNAMIC_LOADER_H +#define _DYNAMIC_LOADER_H + +#include + +#ifdef KOALA_WINDOWS +#include +// Here we need to find module where GetArkUINodeAPI() +// function is implemented. +inline void* loadLibrary(const std::string& libPath) { + return LoadLibraryA(libPath.c_str()); +} + +inline const char* libraryError() { + static char error[256]; + snprintf(error, sizeof error, "error %lu", GetLastError()); + return error; +} + +inline void* findSymbol(void* library, const char* name) { + return (void*)GetProcAddress(reinterpret_cast(library), name); +} + +inline std::string libName(const char* lib) { + return std::string(lib) + ".dll"; +} + +#elif defined(KOALA_LINUX) || defined(KOALA_MACOS) || defined(KOALA_OHOS) +#include + +inline void* loadLibrary(const std::string& libPath) { + void* handle = dlopen(libPath.c_str(), RTLD_LOCAL | RTLD_NOW); + if (!handle) { + return nullptr; + } + return handle; +} + +inline const char* libraryError() { + return dlerror(); +} + +inline std::string symbolName(const char* name) { + return name; +} + +inline void* findSymbol(void* library, const char* name) { + return dlsym(library, symbolName(name).c_str()); +} + +inline std::string libName(const char* lib) { + std::string result; + std::string suffix = +#ifdef KOALA_MACOS + ".dylib" +#else + ".so" +#endif + ; + result = "lib" + std::string(lib) + suffix; + return result; +} + +#else + +#include + +inline void* loadLibrary(const std::string& libPath) { + fprintf(stderr, "No loadLibrary() on this platform\n"); + return nullptr; +} + +inline const char* libraryError() { + fprintf(stderr, "No libraryError() on this platform\n"); + return nullptr; +} + +inline std::string symbolName(const char* name) { + fprintf(stderr, "No symbolName() on this platform\n"); + return ""; +} + +inline void* findSymbol(void* library, const char* name) { + fprintf(stderr, "No findSymbol() on this platform\n"); + return nullptr; +} + +inline std::string libName(const char* lib) { + fprintf(stderr, "No libName() on this platform\n"); + return ""; +} + +#endif + +#endif // _DYNAMIC_LOADER_H \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/ets/convertors-ets.cc b/koala-wrapper/koalaui/interop/src/cpp/ets/convertors-ets.cc new file mode 100644 index 000000000..450804338 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ets/convertors-ets.cc @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2022-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 "convertors-ets.h" +#include "signatures.h" +#include "interop-logging.h" +#include "interop-types.h" + +static const char* callCallbackFromNative = "callCallbackFromNative"; +static const char* callCallbackFromNativeSig = "I[BI:I"; + +static const char* FAST_NATIVE_PREFIX = "#F$"; + +const bool registerByOne = true; + +static bool registerNatives(ets_env *env, const ets_class clazz, const std::vector> impls) { + std::vector methods; + methods.reserve(impls.size()); + bool result = true; + for (const auto &[name, type, func, flag] : impls) { + EtsNativeMethod method; + method.name = name.c_str(); + method.func = func; + method.signature = (flag & ETS_SLOW_NATIVE_FLAG) == 0 ? FAST_NATIVE_PREFIX : nullptr; + if (registerByOne) { + result &= env->RegisterNatives(clazz, &method, 1) >= 0; + if (env->ErrorCheck()) { + //env->ErrorDescribe(); + env->ErrorClear(); + } + } + else { + methods.push_back(method); + } + } + if (!registerByOne) { + result = env->RegisterNatives(clazz, methods.data(), static_cast(methods.size())) >= 0; + } + return registerByOne ? true : result; +} + +bool registerAllModules(ets_env *env) { + auto moduleNames = EtsExports::getInstance()->getModules(); + + for (auto it = moduleNames.begin(); it != moduleNames.end(); ++it) { + std::string classpath = EtsExports::getInstance()->getClasspath(*it); + ets_class nativeModule = env->FindClass(classpath.c_str()); + if (nativeModule == nullptr) { + LOGE("Cannot find managed class %s", classpath.c_str()); + continue; + } + if (!registerNatives(env, nativeModule, EtsExports::getInstance()->getMethods(*it))) { + return false; + } + } + + return true; +} + +extern "C" ETS_EXPORT ets_int ETS_CALL EtsNapiOnLoad(ets_env *env) { + if (!registerAllModules(env)) { + LOGE("Failed to register ets modules"); + return ETS_ERR; + } + auto interopClasspath = EtsExports::getInstance()->getClasspath("InteropNativeModule"); + auto interopClass = env->FindClass(interopClasspath.c_str()); + if (interopClass == nullptr) { + LOGE("Can not find InteropNativeModule classpath to set callback dispatcher"); + return ETS_ERR; + } + if (!setKoalaEtsNapiCallbackDispatcher(env, interopClass, callCallbackFromNative, callCallbackFromNativeSig)) { + LOGE("Failed to set koala ets callback dispatcher"); + return ETS_ERR; + } + return ETS_NAPI_VERSION_1_0; +} + +EtsExports* EtsExports::getInstance() { + static EtsExports *instance = nullptr; + if (instance == nullptr) { + instance = new EtsExports(); + } + return instance; +} + +std::vector EtsExports::getModules() { + std::vector result; + for (auto it = implementations.begin(); it != implementations.end(); ++it) { + result.push_back(it->first); + } + return result; +} + +const std::vector>& EtsExports::getMethods(const std::string& module) { + auto it = implementations.find(module); + if (it == implementations.end()) { + LOGE("Module %s is not registered", module.c_str()); + } + return it->second; +} + +void EtsExports::addMethod(const char* module, const char *name, const char *type, void *impl, int flags) { + auto it = implementations.find(module); + if (it == implementations.end()) { + it = implementations.insert(std::make_pair(module, std::vector>())).first; + } + it->second.push_back(std::make_tuple(name, convertType(name, type), impl, flags)); +} + +void EtsExports::setClasspath(const char* module, const char *classpath) { + auto it = classpaths.find(module); + if (it == classpaths.end()) { + classpaths.insert(std::make_pair(module, classpath)); + } else { + LOGE("Classpath for module %s was redefined", module); + } +} + +static std::map g_defaultClasspaths = { + {"InteropNativeModule", "@koalaui/interop/InteropNativeModule/InteropNativeModule"}, + // todo leave just InteropNativeModule, define others via KOALA_ETS_INTEROP_MODULE_CLASSPATH + {"TestNativeModule", "@koalaui/arkts-arkui/generated/arkts/TestNativeModule/TestNativeModule"}, + {"ArkUINativeModule", "@koalaui/arkts-arkui/generated/arkts/ArkUINativeModule/ArkUINativeModule"}, + {"ArkUIGeneratedNativeModule", "@koalaui/arkts-arkui/generated/arkts/ArkUIGeneratedNativeModule/ArkUIGeneratedNativeModule"}, +}; +const std::string& EtsExports::getClasspath(const std::string& module) { + auto it = classpaths.find(module); + if (it != classpaths.end()) { + return it->second; + } + auto defaultClasspath = g_defaultClasspaths.find(module); + if (defaultClasspath != g_defaultClasspaths.end()) { + return defaultClasspath->second; + } + INTEROP_FATAL("Classpath for module %s was not registered", module.c_str()); +} diff --git a/koala-wrapper/koalaui/interop/src/cpp/ets/convertors-ets.h b/koala-wrapper/koalaui/interop/src/cpp/ets/convertors-ets.h new file mode 100644 index 000000000..c03b5af27 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ets/convertors-ets.h @@ -0,0 +1,1349 @@ +/* + * Copyright (c) 2022-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. + */ + +#pragma once + +#ifdef KOALA_ETS_NAPI + +#include +#include +#include +#include +#include +#include +#include + +#include "etsapi.h" +#include "koala-types.h" + +template +struct InteropTypeConverter { + using InteropType = T; + static T convertFrom(EtsEnv* env, InteropType value) { return value; } + static InteropType convertTo(EtsEnv* env, T value) { return value; } + static void release(EtsEnv* env, InteropType value, T converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = ets_string; + static KStringPtr convertFrom(EtsEnv* env, InteropType value) { + if (value == nullptr) return KStringPtr(); + KStringPtr result; + // Notice that we use UTF length for buffer size, but counter is expressed in number of Unicode chars. + result.resize(env->GetStringUTFLength(value)); + env->GetStringUTFRegion(value, 0, env->GetStringLength(value), result.data()); + return result; + } + static InteropType convertTo(EtsEnv* env, const KStringPtr& value) { + return env->NewStringUTF(value.c_str()); + } + static void release(EtsEnv* env, InteropType value, const KStringPtr& converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = ets_long; + static KNativePointer convertFrom(EtsEnv* env, InteropType value) { + return reinterpret_cast(value); + } + static InteropType convertTo(EtsEnv* env, KNativePointer value) { + return reinterpret_cast(value); + } + static void release(EtsEnv* env, InteropType value, KNativePointer converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = ets_intArray; + static KInt* convertFrom(EtsEnv* env, InteropType value) { + if (!value) return nullptr; + return env->PinIntArray(value); + } + static InteropType convertTo(EtsEnv* env, KInt* value) = delete; + static void release(EtsEnv* env, InteropType value, KInt* converted) { + if (value) env->UnpinIntArray(value); + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = ets_floatArray; + static KFloat* convertFrom(EtsEnv* env, InteropType value) { + if (!value) return nullptr; + return env->PinFloatArray(value); + } + static InteropType convertTo(EtsEnv* env, KFloat* value) = delete; + static void release(EtsEnv* env, InteropType value, KFloat* converted) { + if (value) env->UnpinFloatArray(value); + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = ets_byteArray; + static KByte* convertFrom(EtsEnv* env, InteropType value) { + if (!value) return nullptr; + return (KByte*)env->PinByteArray(value); + } + static InteropType convertTo(EtsEnv* env, KByte* value) = delete; + static void release(EtsEnv* env, InteropType value, KByte* converted) { + if (value) env->UnpinByteArray((ets_byteArray)value); + } +}; + +template <> struct InteropTypeConverter { + using InteropType = ets_double; + static KInteropNumber convertFrom(EtsEnv *env, InteropType value) { + return KInteropNumber::fromDouble(value); + } + static InteropType convertTo(EtsEnv *env, KInteropNumber value) { + return value.asDouble(); + } + static void release(EtsEnv *env, InteropType value, + KInteropNumber converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = ets_object; + static KLength convertFrom(EtsEnv* env, InteropType value) { + const static ets_class double_class = reinterpret_cast(env->NewGlobalRef(env->FindClass("std/core/Double"))); + const static ets_class int_class = reinterpret_cast(env->NewGlobalRef(env->FindClass("std/core/Int"))); + const static ets_class string_class = reinterpret_cast(env->NewGlobalRef(env->FindClass("std/core/String"))); + const static ets_class resource_class = reinterpret_cast( + env->NewGlobalRef(env->FindClass("@koalaui/arkts-arkui/generated/ArkResourceInterfaces/Resource"))); + + if (env->IsInstanceOf(value, double_class)) { + const static ets_method double_p = env->Getp_method(double_class, "unboxed", ":D"); + return KLength{ 1, (KFloat)env->CallDoubleMethod(value, double_p), 1, 0 }; + } else if (env->IsInstanceOf(value, int_class)) { + const static ets_method int_p = env->Getp_method(int_class, "unboxed", ":I"); + return KLength{ 1, (KFloat)env->CallIntMethod(value, int_p), 1, 0 }; + } else if (env->IsInstanceOf(value, string_class)) { + KStringPtr ptr = InteropTypeConverter::convertFrom(env, reinterpret_cast(value)); + KLength length = { 0 }; + parseKLength(ptr, &length); + length.type = 2; + length.resource = 0; + return length; + } else if (env->IsInstanceOf(value, resource_class)) { + const static ets_method resource_p = env->Getp_method(resource_class, "id", ":D"); + return KLength{ 3, 0, 1, (KInt)env->CallDoubleMethod(value, resource_p) }; + } else { + return KLength( { 0, 0, 0, 0}); + } + } + static InteropType convertTo(EtsEnv* env, KLength value) = delete; + static void release(EtsEnv* env, InteropType value, const KLength& converted) {} +}; + +template +inline typename InteropTypeConverter::InteropType makeResult(EtsEnv* env, Type value) { + return InteropTypeConverter::convertTo(env, value); +} + +template +inline Type getArgument(EtsEnv* env, typename InteropTypeConverter::InteropType arg) { + return InteropTypeConverter::convertFrom(env, arg); +} + +template +inline void releaseArgument(EtsEnv* env, typename InteropTypeConverter::InteropType arg, Type& data) { + InteropTypeConverter::release(env, arg, data); +} + +#define ETS_SLOW_NATIVE_FLAG 1 + +class EtsExports { + std::unordered_map>> implementations; + std::unordered_map classpaths; + +public: + static EtsExports* getInstance(); + + std::vector getModules(); + void addMethod(const char* module, const char* name, const char* type, void* impl, int flags); + const std::vector>& getMethods(const std::string& module); + + void setClasspath(const char* module, const char* classpath); + const std::string& getClasspath(const std::string& module); +}; + +#define KOALA_QUOTE0(x) #x +#define KOALA_QUOTE(x) KOALA_QUOTE0(x) + +#ifdef _MSC_VER +#define MAKE_ETS_EXPORT(module, name, type, flag) \ + static void __init_##name() { \ + EtsExports::getInstance()->addMethod(KOALA_QUOTE(module), "_"#name, type, reinterpret_cast(Ark_##name), flag); \ + } \ + namespace { \ + struct __Init_##name { \ + __Init_##name() { __init_##name(); } \ + } __Init_##name##_v; \ + } +#define KOALA_ETS_INTEROP_MODULE_CLASSPATH(module, classpath) \ + static void __init_classpath_##module() { \ + EtsExports::getInstance()->setClasspath(KOALA_QUOTE(module), classpath); \ + } \ + namespace { \ + struct __Init_classpath_##module { \ + __Init_classpath_##module() { __init_classpath_##module(); } \ + } __Init_classpath_##module##_v; \ + } +#else +#define MAKE_ETS_EXPORT(module, name, type, flag) \ + __attribute__((constructor)) \ + static void __init_ets_##name() { \ + EtsExports::getInstance()->addMethod(KOALA_QUOTE(module), "_"#name, type, reinterpret_cast(Ark_##name), flag); \ + } +#define KOALA_ETS_INTEROP_MODULE_CLASSPATH(module, classpath) \ + __attribute__((constructor)) \ + static void __init_ets_classpath_##module() { \ + EtsExports::getInstance()->setClasspath(KOALA_QUOTE(module), classpath); \ + } +#endif + +#define KOALA_INTEROP_0(name, Ret) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz) { \ + KOALA_MAYBE_LOG(name) \ + return makeResult(env, impl_##name()); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret, 0) + +#define KOALA_INTEROP_1(name, Ret, P0) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + auto rv = makeResult(env, impl_##name(p0)); \ + releaseArgument(env, _p0, p0); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0, 0) + +#define KOALA_INTEROP_2(name, Ret, P0, P1) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + auto rv = makeResult(env, impl_##name(p0, p1)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1, 0) + +#define KOALA_INTEROP_3(name, Ret, P0, P1, P2) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2, 0) + +#define KOALA_INTEROP_4(name, Ret, P0, P1, P2, P3) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3, 0) + +#define KOALA_INTEROP_5(name, Ret, P0, P1, P2, P3, P4) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4, 0) + +#define KOALA_INTEROP_6(name, Ret, P0, P1, P2, P3, P4, P5) \ +InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5, 0) + +#define KOALA_INTEROP_7(name, Ret, P0, P1, P2, P3, P4, P5, P6) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6, 0) + +#define KOALA_INTEROP_8(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7, 0) + +#define KOALA_INTEROP_9(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + return rv; \ + } \ + MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8, 0) + +#define KOALA_INTEROP_10(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9, 0) + +#define KOALA_INTEROP_11(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10, 0) + +#define KOALA_INTEROP_12(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11, 0) + +#define KOALA_INTEROP_13(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + return rv; \ + } \ + MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12, 0) + +#define KOALA_INTEROP_14(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + auto rv = makeResult(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13, 0) + +#define KOALA_INTEROP_V0(name) \ + void Ark_##name(EtsEnv *env) { \ + KOALA_MAYBE_LOG(name) \ + impl_##name(); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void", 0) + +#define KOALA_INTEROP_V1(name, P0) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + impl_##name(p0); \ + releaseArgument(env, _p0, p0); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0, 0) + +#define KOALA_INTEROP_V2(name, P0, P1) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + impl_##name(p0, p1); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1, 0) + +#define KOALA_INTEROP_V3(name, P0, P1, P2) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + impl_##name(p0, p1, p2); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2, 0) + +#define KOALA_INTEROP_V4(name, P0, P1, P2, P3) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + impl_##name(p0, p1, p2, p3); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ +} \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3, 0) + +#define KOALA_INTEROP_V5(name, P0, P1, P2, P3, P4) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + impl_##name(p0, p1, p2, p3, p4); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ +} \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4, 0) + +#define KOALA_INTEROP_V6(name, P0, P1, P2, P3, P4, P5) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + impl_##name(p0, p1, p2, p3, p4, p5); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5, 0) + +#define KOALA_INTEROP_V7(name, P0, P1, P2, P3, P4, P5, P6) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6, 0) + +#define KOALA_INTEROP_V8(name, P0, P1, P2, P3, P4, P5, P6, P7) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7, 0) + +#define KOALA_INTEROP_V9(name, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8, 0) + +#define KOALA_INTEROP_V10(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ +} \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9, 0) + +#define KOALA_INTEROP_V11(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10, 0) + +#define KOALA_INTEROP_V12(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ +} \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11, 0) + +#define KOALA_INTEROP_V13(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ +} \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12, 0) + +#define KOALA_INTEROP_V14(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ +} \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13, 0) + +#define KOALA_INTEROP_V15(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13, \ + InteropTypeConverter::InteropType _p14) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + P14 p14 = getArgument(env, _p14); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ + releaseArgument(env, _p14, p14); \ +} \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13 "|" #P14, 0) + +#define KOALA_INTEROP_CTX_0(name, Ret) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz) { \ + KOALA_MAYBE_LOG(name) \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx)); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_1(name, Ret, P0) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0)); \ + releaseArgument(env, _p0, p0); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_2(name, Ret, P0, P1) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0, p1)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_3(name, Ret, P0, P1, P2) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0, p1, p2)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_4(name, Ret, P0, P1, P2, P3) \ + InteropTypeConverter::InteropType Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = makeResult(env, impl_##name(ctx, p0, p1, p2, p3)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + return rv; \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V0(name) \ + void Ark_##name(EtsEnv *env, ets_class clazz) { \ + KOALA_MAYBE_LOG(name) \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void", ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V1(name, P0) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0); \ + releaseArgument(env, _p0, p0); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V2(name, P0, P1) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V3(name, P0, P1, P2) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V4(name, P0, P1, P2, P3) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2, p3); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3, ETS_SLOW_NATIVE_FLAG) + +#define KOALA_INTEROP_CTX_V5(name, P0, P1, P2, P3, P4) \ + void Ark_##name(EtsEnv *env, ets_class clazz, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2, p3, p4); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + } \ +MAKE_ETS_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4, ETS_SLOW_NATIVE_FLAG) + +bool setKoalaEtsNapiCallbackDispatcher( + EtsEnv* etsEnv, + ets_class clazz, + const char* dispatcherMethodName, + const char* dispactherMethodSig +); +void getKoalaEtsNapiCallbackDispatcher(ets_class* clazz, ets_method* method); + +#define KOALA_INTEROP_CALL_VOID(venv, id, length, args) \ +{ \ + ets_class clazz = nullptr; \ + ets_method method = nullptr; \ + getKoalaEtsNapiCallbackDispatcher(&clazz, &method); \ + EtsEnv* etsEnv = reinterpret_cast(vmContext); \ + etsEnv->PushLocalFrame(1); \ + ets_byteArray args_ets = etsEnv->NewByteArray(length); \ + etsEnv->SetByteArrayRegion(args_ets, 0, length, reinterpret_cast(args)); \ + etsEnv->CallStaticIntMethod(clazz, method, id, args_ets, length); \ + etsEnv->GetByteArrayRegion(args_ets, 0, length, reinterpret_cast(args)); \ + etsEnv->PopLocalFrame(nullptr); \ +} + +#define KOALA_INTEROP_CALL_INT(venv, id, length, args) \ +{ \ + ets_class clazz = nullptr; \ + ets_method method = nullptr; \ + getKoalaEtsNapiCallbackDispatcher(&clazz, &method); \ + EtsEnv* etsEnv = reinterpret_cast(venv); \ + etsEnv->PushLocalFrame(1); \ + ets_byteArray args_ets = etsEnv->NewByteArray(length); \ + etsEnv->SetByteArrayRegion(args_ets, 0, length, reinterpret_cast(args)); \ + int32_t rv = etsEnv->CallStaticIntMethod(clazz, method, id, args_ets, length); \ + etsEnv->GetByteArrayRegion(args_ets, 0, length, reinterpret_cast(args)); \ + etsEnv->PopLocalFrame(nullptr); \ + return rv; \ +} + +#define KOALA_INTEROP_CALL_VOID_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_VOID(venv, id, (argc) * sizeof(int32_t), args) +#define KOALA_INTEROP_CALL_INT_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_INT(venv, id, (argc) * sizeof(int32_t), args) + +#define KOALA_INTEROP_THROW(vmContext, object, ...) \ + do { \ + EtsEnv* env = reinterpret_cast(vmContext); \ + env->ThrowError(object); \ + return __VA_ARGS__; \ + } while (0) + +#define KOALA_INTEROP_THROW_STRING(vmContext, message, ...) \ + do { \ + EtsEnv* env = reinterpret_cast(vmContext); \ + const static ets_class errorClass = env->FindClass("std/core/Error"); \ + env->ThrowErrorNew(errorClass, message); \ + } while (0) + +#endif // KOALA_ETS_NAPI diff --git a/koala-wrapper/koalaui/interop/src/cpp/ets/etsapi.h b/koala-wrapper/koalaui/interop/src/cpp/ets/etsapi.h new file mode 100644 index 000000000..15868ee90 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ets/etsapi.h @@ -0,0 +1,1545 @@ +/** + * Copyright (c) 2021-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 PANDA_RUNTIME_INTEROP_ETS_NAPI_H +#define PANDA_RUNTIME_INTEROP_ETS_NAPI_H + +// NOLINTBEGIN(modernize-use-using, readability-identifier-naming, cppcoreguidelines-pro-type-vararg) + +#ifdef __cplusplus +#include +#include +#else +#include +#include +#endif + +// NOLINTBEGIN(cppcoreguidelines-macro-usage) + +// Version Constants +#define ETS_NAPI_VERSION_1_0 0x00010000 + +// General return value constants +#define ETS_OK 0 // success +#define ETS_ERR (-1) // unknown error +#define ETS_ERR_VER (-2) // ETS version error +#define ETS_ERR_NOMEM (-3) // not enough memory +#define ETS_ERR_EXIST (-4) // VM already created +#define ETS_ERR_INVAL (-5) // invalid arguments + +// Boolean Constants +#define ETS_FALSE 0 +#define ETS_TRUE 1 + +// Mode Constants +#define ETS_COMMIT 1 +#define ETS_ABORT 2 + +// NOLINTEND(cppcoreguidelines-macro-usage) + +// Primitive Types +typedef uint8_t ets_boolean; +typedef int8_t ets_byte; +typedef uint16_t ets_char; +typedef int16_t ets_short; +typedef int32_t ets_int; +typedef int64_t ets_long; +typedef float ets_float; +typedef double ets_double; +typedef ets_int ets_size; + +// Reference Types +#ifdef __cplusplus +class __ets_object {}; +class __ets_class : public __ets_object {}; +class __ets_string : public __ets_object {}; +class __ets_array : public __ets_object {}; +class __ets_objectArray : public __ets_array {}; +class __ets_booleanArray : public __ets_array {}; +class __ets_byteArray : public __ets_array {}; +class __ets_charArray : public __ets_array {}; +class __ets_shortArray : public __ets_array {}; +class __ets_intArray : public __ets_array {}; +class __ets_longArray : public __ets_array {}; +class __ets_floatArray : public __ets_array {}; +class __ets_doubleArray : public __ets_array {}; +class __ets_error : public __ets_object {}; + +typedef __ets_object *ets_object; +typedef __ets_class *ets_class; +typedef __ets_string *ets_string; +typedef __ets_array *ets_array; +typedef __ets_objectArray *ets_objectArray; +typedef __ets_booleanArray *ets_booleanArray; +typedef __ets_byteArray *ets_byteArray; +typedef __ets_charArray *ets_charArray; +typedef __ets_shortArray *ets_shortArray; +typedef __ets_intArray *ets_intArray; +typedef __ets_longArray *ets_longArray; +typedef __ets_floatArray *ets_floatArray; +typedef __ets_doubleArray *ets_doubleArray; +typedef __ets_error *ets_error; +typedef __ets_object *ets_weak; + +#else // __cplusplus + +struct __ets_object; +typedef struct __ets_object *ets_object; +typedef ets_object ets_class; +typedef ets_object ets_string; +typedef ets_object ets_error; +typedef ets_object ets_weak; +typedef ets_object ets_array; +typedef ets_array ets_objectArray; +typedef ets_array ets_booleanArray; +typedef ets_array ets_byteArray; +typedef ets_array ets_charArray; +typedef ets_array ets_shortArray; +typedef ets_array ets_intArray; +typedef ets_array ets_longArray; +typedef ets_array ets_floatArray; +typedef ets_array ets_doubleArray; +#endif // __cplusplus + +struct __ets_deferred; +typedef struct __ets_deferred *ets_deferred; + +// Field and Method IDs +struct __ets_method; +struct __ets_field; +typedef struct __ets_method *ets_method; +typedef struct __ets_field *ets_field; + +// The Value Type +typedef union ets_value { + ets_boolean z; + ets_byte b; + ets_char c; + ets_short s; + ets_int i; + ets_long j; + ets_float f; + ets_double d; + ets_object l; +} ets_value; + +// Describe native method by name, signature and function pointer +typedef struct { + const char *name; + const char *signature; + void *func; +} EtsNativeMethod; + +// The object reference types +typedef enum { + ETS_INVALID_REF_TYPE = 0, + ETS_LOCAL_REF_TYPE = 1, + ETS_GLOBAL_REF_TYPE = 2, + ETS_WEAK_GLOBAL_REF_TYPE = 3 +} ets_objectRefType; + +#ifdef __cplusplus +typedef struct __EtsVM EtsVM; +typedef struct __EtsEnv ets_env; +#else +typedef const struct ETS_InvokeInterface *EtsVM; +typedef const struct ETS_NativeInterface *ets_env; +#endif + +// Deprecated types: +typedef ets_env EtsEnv; + +typedef enum { + ETS_OKAY, + ETS_INVALID_ARG, + ETS_GENERIC_FAILURE, + ETS_PENDING_EXCEPTION, + ETS_INVALID_VERSION, // NOTE(v.cherkashin): This status code doesn't match to napi interface. + // Should we probably delete this status code? +} ets_status; + +// clang-format off +// Interface Function Table +struct ETS_NativeInterface { + // NOTE(a.urakov): solve the "Array" naming problem + ets_int (*GetVersion)(EtsEnv *env); +#ifdef ETS_NAPI_DESIGN_FINISHED + ets_class (*DefineClass)(EtsEnv *env, const char *name, ets_object loader, const ets_byte *buf, ets_size bufLen); +#endif + ets_class (*FindClass)(EtsEnv *env, const char *name); +#ifdef ETS_NAPI_DESIGN_FINISHED + ets_method (*FromReflectedMethod)(EtsEnv *env, ets_object method); + ets_field (*FromReflectedField)(EtsEnv *env, ets_object field); + ets_object (*ToReflectedMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ets_boolean isStatic); +#endif + ets_class (*GetSuperclass)(EtsEnv *env, ets_class cls); + ets_boolean (*IsAssignableFrom)(EtsEnv *env, ets_class cls1, ets_class cls2); +#ifdef ETS_NAPI_DESIGN_FINISHED + ets_object (*ToReflectedField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_boolean isStatic); +#endif + ets_int (*ThrowError)(EtsEnv *env, ets_error obj); + ets_int (*ThrowErrorNew)(EtsEnv *env, ets_class cls, const char *message); + ets_error (*ErrorOccurred)(EtsEnv *env); + void (*ErrorDescribe)(EtsEnv *env); + void (*ErrorClear)(EtsEnv *env); + void (*FatalError)(EtsEnv *env, const char *message); + ets_int (*PushLocalFrame)(EtsEnv *env, ets_int capacity); + ets_object (*PopLocalFrame)(EtsEnv *env, ets_object result); + ets_object (*NewGlobalRef)(EtsEnv *env, ets_object obj); + void (*DeleteGlobalRef)(EtsEnv *env, ets_object globalRef); + void (*DeleteLocalRef)(EtsEnv *env, ets_object localRef); + ets_boolean (*IsSameObject)(EtsEnv *env, ets_object ref1, ets_object ref2); + ets_object (*NewLocalRef)(EtsEnv *env, ets_object ref); + ets_int (*EnsureLocalCapacity)(EtsEnv *env, ets_int capacity); + ets_object (*AllocObject)(EtsEnv *env, ets_class cls); + ets_object (*NewObject)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_object (*NewObjectList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_object (*NewObjectArray)(EtsEnv *env, ets_class cls, ets_method p_method, const ets_value *args); + ets_class (*GetObjectClass)(EtsEnv *env, ets_object obj); + ets_boolean (*IsInstanceOf)(EtsEnv *env, ets_object obj, ets_class cls); + ets_method (*Getp_method)(EtsEnv *env, ets_class cls, const char *name, const char *sig); + ets_object (*CallObjectMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_object (*CallObjectMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_object (*CallObjectMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + ets_boolean (*CallBooleanMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_boolean (*CallBooleanMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_boolean (*CallBooleanMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + ets_byte (*CallByteMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_byte (*CallByteMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_byte (*CallByteMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + ets_char (*CallCharMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_char (*CallCharMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_char (*CallCharMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + ets_short (*CallShortMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_short (*CallShortMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_short (*CallShortMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + ets_int (*CallIntMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_int (*CallIntMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_int (*CallIntMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + ets_long (*CallLongMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_long (*CallLongMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_long (*CallLongMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + ets_float (*CallFloatMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_float (*CallFloatMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_float (*CallFloatMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + ets_double (*CallDoubleMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + ets_double (*CallDoubleMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + ets_double (*CallDoubleMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + void (*CallVoidMethod)(EtsEnv *env, ets_object obj, ets_method p_method, ...); + void (*CallVoidMethodList)(EtsEnv *env, ets_object obj, ets_method p_method, va_list args); + void (*CallVoidMethodArray)(EtsEnv *env, ets_object obj, ets_method p_method, const ets_value *args); + + ets_object (*CallNonvirtualObjectMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_object (*CallNonvirtualObjectMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_object (*CallNonvirtualObjectMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_boolean (*CallNonvirtualBooleanMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_boolean (*CallNonvirtualBooleanMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_boolean (*CallNonvirtualBooleanMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_byte (*CallNonvirtualByteMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_byte (*CallNonvirtualByteMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_byte (*CallNonvirtualByteMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_char (*CallNonvirtualCharMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_char (*CallNonvirtualCharMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_char (*CallNonvirtualCharMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_short (*CallNonvirtualShortMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_short (*CallNonvirtualShortMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_short (*CallNonvirtualShortMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_int (*CallNonvirtualIntMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_int (*CallNonvirtualIntMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_int (*CallNonvirtualIntMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_long (*CallNonvirtualLongMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_long (*CallNonvirtualLongMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_long (*CallNonvirtualLongMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_float (*CallNonvirtualFloatMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_float (*CallNonvirtualFloatMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_float (*CallNonvirtualFloatMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_double (*CallNonvirtualDoubleMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + ets_double (*CallNonvirtualDoubleMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + va_list args); + ets_double (*CallNonvirtualDoubleMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + void (*CallNonvirtualVoidMethod)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, ...); + void (*CallNonvirtualVoidMethodList)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, va_list args); + void (*CallNonvirtualVoidMethodArray)(EtsEnv *env, ets_object obj, ets_class cls, ets_method p_method, + const ets_value *args); + ets_field (*Getp_field)(EtsEnv *env, ets_class cls, const char *name, const char *sig); + ets_object (*GetObjectField)(EtsEnv *env, ets_object obj, ets_field p_field); + ets_boolean (*GetBooleanField)(EtsEnv *env, ets_object obj, ets_field p_field); + ets_byte (*GetByteField)(EtsEnv *env, ets_object obj, ets_field p_field); + ets_char (*GetCharField)(EtsEnv *env, ets_object obj, ets_field p_field); + ets_short (*GetShortField)(EtsEnv *env, ets_object obj, ets_field p_field); + ets_int (*GetIntField)(EtsEnv *env, ets_object obj, ets_field p_field); + ets_long (*GetLongField)(EtsEnv *env, ets_object obj, ets_field p_field); + ets_float (*GetFloatField)(EtsEnv *env, ets_object obj, ets_field p_field); + ets_double (*GetDoubleField)(EtsEnv *env, ets_object obj, ets_field p_field); + void (*SetObjectField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_object value); + void (*SetBooleanField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_boolean value); + void (*SetByteField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_byte value); + void (*SetCharField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_char value); + void (*SetShortField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_short value); + void (*SetIntField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_int value); + void (*SetLongField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_long value); + void (*SetFloatField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_float value); + void (*SetDoubleField)(EtsEnv *env, ets_object obj, ets_field p_field, ets_double value); + ets_method (*GetStaticp_method)(EtsEnv *env, ets_class cls, const char *name, const char *sig); + ets_object (*CallStaticObjectMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_object (*CallStaticObjectMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_object (*CallStaticObjectMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_boolean (*CallStaticBooleanMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_boolean (*CallStaticBooleanMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_boolean (*CallStaticBooleanMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_byte (*CallStaticByteMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_byte (*CallStaticByteMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_byte (*CallStaticByteMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_char (*CallStaticCharMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_char (*CallStaticCharMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_char (*CallStaticCharMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_short (*CallStaticShortMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_short (*CallStaticShortMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_short (*CallStaticShortMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_int (*CallStaticIntMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_int (*CallStaticIntMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_int (*CallStaticIntMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_long (*CallStaticLongMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_long (*CallStaticLongMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_long (*CallStaticLongMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_float (*CallStaticFloatMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_float (*CallStaticFloatMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_float (*CallStaticFloatMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_double (*CallStaticDoubleMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + ets_double (*CallStaticDoubleMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + ets_double (*CallStaticDoubleMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + void (*CallStaticVoidMethod)(EtsEnv *env, ets_class cls, ets_method p_method, ...); + void (*CallStaticVoidMethodList)(EtsEnv *env, ets_class cls, ets_method p_method, va_list args); + void (*CallStaticVoidMethodArray)(EtsEnv *env, ets_class cls, ets_method p_method, ets_value *args); + ets_field (*GetStaticp_field)(EtsEnv *env, ets_class cls, const char *name, const char *sig); + ets_object (*GetStaticObjectField)(EtsEnv *env, ets_class cls, ets_field p_field); + ets_boolean (*GetStaticBooleanField)(EtsEnv *env, ets_class cls, ets_field p_field); + ets_byte (*GetStaticByteField)(EtsEnv *env, ets_class cls, ets_field p_field); + ets_char (*GetStaticCharField)(EtsEnv *env, ets_class cls, ets_field p_field); + ets_short (*GetStaticShortField)(EtsEnv *env, ets_class cls, ets_field p_field); + ets_int (*GetStaticIntField)(EtsEnv *env, ets_class cls, ets_field p_field); + ets_long (*GetStaticLongField)(EtsEnv *env, ets_class cls, ets_field p_field); + ets_float (*GetStaticFloatField)(EtsEnv *env, ets_class cls, ets_field p_field); + ets_double (*GetStaticDoubleField)(EtsEnv *env, ets_class cls, ets_field p_field); + void (*SetStaticObjectField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_object value); + void (*SetStaticBooleanField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_boolean value); + void (*SetStaticByteField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_byte value); + void (*SetStaticCharField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_char value); + void (*SetStaticShortField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_short value); + void (*SetStaticIntField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_int value); + void (*SetStaticLongField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_long value); + void (*SetStaticFloatField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_float value); + void (*SetStaticDoubleField)(EtsEnv *env, ets_class cls, ets_field p_field, ets_double value); + ets_string (*NewString)(EtsEnv *env, const ets_char *unicodeChars, ets_size len); + ets_size (*GetStringLength)(EtsEnv *env, ets_string string); + const ets_char *(*GetStringChars)(EtsEnv *env, ets_string string, ets_boolean *isCopy); + void (*ReleaseStringChars)(EtsEnv *env, ets_string string, const ets_char *chars); + ets_string (*NewStringUTF)(EtsEnv *env, const char *bytes); + ets_size (*GetStringUTFLength)(EtsEnv *env, ets_string string); + const char *(*GetStringUTFChars)(EtsEnv *env, ets_string string, ets_boolean *isCopy); + void (*ReleaseStringUTFChars)(EtsEnv *env, ets_string string, const char *utf); + ets_size (*GetArrayLength)(EtsEnv *env, ets_array array); + ets_objectArray (*NewObjectsArray)(EtsEnv *env, ets_size length, ets_class element_class, + ets_object initial_element); + ets_object (*GetObjectArrayElement)(EtsEnv *env, ets_objectArray array, ets_size index); + void (*SetObjectArrayElement)(EtsEnv *env, ets_objectArray array, ets_size index, ets_object value); + ets_booleanArray (*NewBooleanArray)(EtsEnv *env, ets_size length); + ets_byteArray (*NewByteArray)(EtsEnv *env, ets_size length); + ets_charArray (*NewCharArray)(EtsEnv *env, ets_size length); + ets_shortArray (*NewShortArray)(EtsEnv *env, ets_size length); + ets_intArray (*NewIntArray)(EtsEnv *env, ets_size length); + ets_longArray (*NewLongArray)(EtsEnv *env, ets_size length); + ets_floatArray (*NewFloatArray)(EtsEnv *env, ets_size length); + ets_doubleArray (*NewDoubleArray)(EtsEnv *env, ets_size length); + ets_boolean *(*PinBooleanArray)(EtsEnv *env, ets_booleanArray array); + ets_byte *(*PinByteArray)(EtsEnv *env, ets_byteArray array); + ets_char *(*PinCharArray)(EtsEnv *env, ets_charArray array); + ets_short *(*PinShortArray)(EtsEnv *env, ets_shortArray array); + ets_int *(*PinIntArray)(EtsEnv *env, ets_intArray array); + ets_long *(*PinLongArray)(EtsEnv *env, ets_longArray array); + ets_float *(*PinFloatArray)(EtsEnv *env, ets_floatArray array); + ets_double *(*PinDoubleArray)(EtsEnv *env, ets_doubleArray array); + void (*UnpinBooleanArray)(EtsEnv *env, ets_booleanArray array); + void (*UnpinByteArray)(EtsEnv *env, ets_byteArray array); + void (*UnpinCharArray)(EtsEnv *env, ets_charArray array); + void (*UnpinShortArray)(EtsEnv *env, ets_shortArray array); + void (*UnpinIntArray)(EtsEnv *env, ets_intArray array); + void (*UnpinLongArray)(EtsEnv *env, ets_longArray array); + void (*UnpinFloatArray)(EtsEnv *env, ets_floatArray array); + void (*UnpinDoubleArray)(EtsEnv *env, ets_doubleArray array); + void (*GetBooleanArrayRegion)(EtsEnv *env, ets_booleanArray array, ets_size start, ets_size len, ets_boolean *buf); + void (*GetByteArrayRegion)(EtsEnv *env, ets_byteArray array, ets_size start, ets_size len, ets_byte *buf); + void (*GetCharArrayRegion)(EtsEnv *env, ets_charArray array, ets_size start, ets_size len, ets_char *buf); + void (*GetShortArrayRegion)(EtsEnv *env, ets_shortArray array, ets_size start, ets_size len, ets_short *buf); + void (*GetIntArrayRegion)(EtsEnv *env, ets_intArray array, ets_size start, ets_size len, ets_int *buf); + void (*GetLongArrayRegion)(EtsEnv *env, ets_longArray array, ets_size start, ets_size len, ets_long *buf); + void (*GetFloatArrayRegion)(EtsEnv *env, ets_floatArray array, ets_size start, ets_size len, ets_float *buf); + void (*GetDoubleArrayRegion)(EtsEnv *env, ets_doubleArray array, ets_size start, ets_size len, ets_double *buf); + void (*SetBooleanArrayRegion)(EtsEnv *env, ets_booleanArray array, ets_size start, ets_size len, + const ets_boolean *buf); + void (*SetByteArrayRegion)(EtsEnv *env, ets_byteArray array, ets_size start, ets_size len, const ets_byte *buf); + void (*SetCharArrayRegion)(EtsEnv *env, ets_charArray array, ets_size start, ets_size len, const ets_char *buf); + void (*SetShortArrayRegion)(EtsEnv *env, ets_shortArray array, ets_size start, ets_size len, const ets_short *buf); + void (*SetIntArrayRegion)(EtsEnv *env, ets_intArray array, ets_size start, ets_size len, const ets_int *buf); + void (*SetLongArrayRegion)(EtsEnv *env, ets_longArray array, ets_size start, ets_size len, const ets_long *buf); + void (*SetFloatArrayRegion)(EtsEnv *env, ets_floatArray array, ets_size start, ets_size len, const ets_float *buf); + void (*SetDoubleArrayRegion)(EtsEnv *env, ets_doubleArray array, ets_size start, ets_size len, + const ets_double *buf); + ets_int (*RegisterNatives)(EtsEnv *env, ets_class cls, const EtsNativeMethod *methods, ets_int nMethods); + ets_int (*UnregisterNatives)(EtsEnv *env, ets_class cls); + ets_int (*GetEtsVM)(EtsEnv *env, EtsVM **vm); + void (*GetStringRegion)(EtsEnv *env, ets_string str, ets_size start, ets_size len, ets_char *buf); + void (*GetStringUTFRegion)(EtsEnv *env, ets_string str, ets_size start, ets_size len, char *buf); + ets_weak (*NewWeakGlobalRef)(EtsEnv *env, ets_object obj); + void (*DeleteWeakGlobalRef)(EtsEnv *env, ets_weak obj); + ets_boolean (*ErrorCheck)(EtsEnv *env); +#ifdef ETS_NAPI_DESIGN_FINISHED + ets_object (*NewDirectByteBuffer)(EtsEnv *env, void *address, ets_long capacity); + void *(*GetDirectBufferAddress)(EtsEnv *env, ets_object buf); + ets_long (*GetDirectBufferCapacity)(EtsEnv *env, ets_object buf); +#endif + ets_objectRefType (*GetObjectRefType)(EtsEnv *env, ets_object obj); + + /* 227 methods */ + + // Promise API + ets_status (*PromiseCreate)(EtsEnv *env, ets_deferred *deferred, ets_object *promise); + ets_status (*DeferredResolve)(EtsEnv *env, ets_deferred deferred, ets_object resolution); + ets_status (*DeferredReject)(EtsEnv *env, ets_deferred deferred, ets_object rejection); +}; +// clang-format on + +// Invocation API Functions +typedef enum { + ETS_LOG_LEVEL, + ETS_MOBILE_LOG, + ETS_BOOT_FILE, + ETS_AOT_FILE, + ETS_ARK_FILE, + ETS_JIT, + ETS_NO_JIT, + ETS_AOT, + ETS_NO_AOT, + ETS_GC_TRIGGER_TYPE, + ETS_GC_TYPE, + ETS_RUN_GC_IN_PLACE, + ETS_INTERPRETER_TYPE, + ETS_NATIVE_LIBRARY_PATH, + ETS_VERIFICATION_MODE +} EtsOptionType; + +typedef struct EtsVMOption { + EtsOptionType option; + const void *extraInfo; +} EtsVMOption; + +typedef struct EtsVMInitArgs { + ets_int version; + ets_int nOptions; + EtsVMOption *options; +} EtsVMInitArgs; + +typedef enum { + ETS_MOBILE_LOG_LEVEL_UNKNOWN = 0, + ETS_MOBILE_LOG_LEVEL_DEFAULT, + ETS_MOBILE_LOG_LEVEL_VERBOSE, + ETS_MOBILE_LOG_LEVEL_DEBUG, + ETS_MOBILE_LOG_LEVEL_INFO, + ETS_MOBILE_LOG_LEVEL_WARN, + ETS_MOBILE_LOG_LEVEL_ERROR, + ETS_MOBILE_LOG_LEVEL_FATAL, + ETS_MOBILE_LOG_LEVEL_SILENT +} EtsMobileLogggerLevel; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _MSC_VER +#define ETS_EXPORT __declspec(dllexport) +#else +#define ETS_EXPORT __attribute__((visibility("default"))) +#endif +#define ETS_IMPORT +#define ETS_CALL + +ETS_EXPORT ets_int ETS_GetDefaultVMInitArgs(EtsVMInitArgs *vmArgs); +ETS_EXPORT ets_int ETS_GetCreatedVMs(EtsVM **vmBuf, ets_size bufLen, ets_size *nVms); +ETS_EXPORT ets_int ETS_CreateVM(EtsVM **pVm, EtsEnv **pEnv, EtsVMInitArgs *vmArgs); + +#ifdef __cplusplus +} +#endif + +struct ETS_InvokeInterface { + ets_int (*DestroyEtsVM)(EtsVM *vm); + ets_int (*GetEnv)(EtsVM *vm, EtsEnv **pEnv, ets_int version); +}; + +struct __EtsVM { + // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) + const struct ETS_InvokeInterface *invoke_interface; + +#ifdef __cplusplus + ets_int DestroyEtsVM() + { + return invoke_interface->DestroyEtsVM(this); + } + + ets_int GetEnv(EtsEnv **pEnv, ets_int version) + { + return invoke_interface->GetEnv(this, pEnv, version); + } +#endif +}; + +struct __EtsEnv { + // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) + const struct ETS_NativeInterface *native_interface; + +#ifdef __cplusplus + + ets_int GetVersion() + { + return native_interface->GetVersion(this); + } + // DefineClass, + ets_class FindClass(const char *name) + { + return native_interface->FindClass(this, name); + } + // FromReflectedMethod, + // FromReflectedField, + // ToReflectedMethod, + ets_class GetSuperclass(ets_class cls) + { + return native_interface->GetSuperclass(this, cls); + } + ets_boolean IsAssignableFrom(ets_class cls1, ets_class cls2) + { + return native_interface->IsAssignableFrom(this, cls1, cls2); + } + // ToReflectedField, + ets_int ThrowError(ets_error obj) + { + return native_interface->ThrowError(this, obj); + } + ets_int ThrowErrorNew(ets_class cls, const char *message) + { + return native_interface->ThrowErrorNew(this, cls, message); + } + ets_error ErrorOccurred() + { + return native_interface->ErrorOccurred(this); + } + void ErrorDescribe() + { + native_interface->ErrorDescribe(this); + } + void ErrorClear() + { + native_interface->ErrorClear(this); + } + void FatalError(const char *message) + { + native_interface->FatalError(this, message); + } + ets_int PushLocalFrame(ets_int capacity) + { + return native_interface->PushLocalFrame(this, capacity); + } + ets_object PopLocalFrame(ets_object result) + { + return native_interface->PopLocalFrame(this, result); + } + ets_object NewGlobalRef(ets_object obj) + { + return native_interface->NewGlobalRef(this, obj); + } + void DeleteGlobalRef(ets_object globalRef) + { + native_interface->DeleteGlobalRef(this, globalRef); + } + void DeleteLocalRef(ets_object localRef) + { + native_interface->DeleteLocalRef(this, localRef); + } + ets_boolean IsSameObject(ets_object ref1, ets_object ref2) + { + return native_interface->IsSameObject(this, ref1, ref2); + } + ets_object NewLocalRef(ets_object ref) + { + return native_interface->NewLocalRef(this, ref); + } + ets_int EnsureLocalCapacity(ets_int capacity) + { + return native_interface->EnsureLocalCapacity(this, capacity); + } + ets_object AllocObject(ets_class cls) + { + return native_interface->AllocObject(this, cls); + } + ets_object NewObject(ets_class cls, ets_method p_method, ...) + { + va_list args; + va_start(args, p_method); + ets_object ret = native_interface->NewObjectList(this, cls, p_method, args); + va_end(args); + return ret; + } + ets_object NewObjectList(ets_class cls, ets_method p_method, va_list args) + { + return native_interface->NewObjectList(this, cls, p_method, args); + } + ets_object NewObjectArray(ets_class cls, ets_method p_method, const ets_value *args) + { + return native_interface->NewObjectArray(this, cls, p_method, args); + } + ets_class GetObjectClass(ets_object obj) + { + return native_interface->GetObjectClass(this, obj); + } + ets_boolean IsInstanceOf(ets_object obj, ets_class cls) + { + return native_interface->IsInstanceOf(this, obj, cls); + } + ets_method Getp_method(ets_class cls, const char *name, const char *sig) + { + return native_interface->Getp_method(this, cls, name, sig); + } + ets_object CallObjectMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_object res = native_interface->CallObjectMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_object CallObjectMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallObjectMethodList(this, obj, method_id, args); + } + ets_object CallObjectMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallObjectMethodArray(this, obj, method_id, args); + } + ets_boolean CallBooleanMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_boolean res = native_interface->CallBooleanMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_boolean CallBooleanMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallBooleanMethodList(this, obj, method_id, args); + } + ets_boolean CallBooleanMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallBooleanMethodArray(this, obj, method_id, args); + } + ets_byte CallByteMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_byte res = native_interface->CallByteMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_byte CallByteMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallByteMethodList(this, obj, method_id, args); + } + ets_byte CallByteMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallByteMethodArray(this, obj, method_id, args); + } + ets_char CallCharMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_char res = native_interface->CallCharMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_char CallCharMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallCharMethodList(this, obj, method_id, args); + } + ets_char CallCharMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallCharMethodArray(this, obj, method_id, args); + } + ets_short CallShortMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_short res = native_interface->CallShortMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_short CallShortMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallShortMethodList(this, obj, method_id, args); + } + ets_short CallShortMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallShortMethodArray(this, obj, method_id, args); + } + ets_int CallIntMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_int res = native_interface->CallIntMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_int CallIntMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallIntMethodList(this, obj, method_id, args); + } + ets_int CallIntMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallIntMethodArray(this, obj, method_id, args); + } + ets_long CallLongMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_long res = native_interface->CallLongMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_long CallLongMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallLongMethodList(this, obj, method_id, args); + } + ets_long CallLongMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallLongMethodArray(this, obj, method_id, args); + } + ets_float CallFloatMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_float res = native_interface->CallFloatMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_float CallFloatMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallFloatMethodList(this, obj, method_id, args); + } + ets_float CallFloatMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallFloatMethodArray(this, obj, method_id, args); + } + ets_double CallDoubleMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_double res = native_interface->CallDoubleMethodList(this, obj, method_id, args); + va_end(args); + return res; + } + ets_double CallDoubleMethodList(ets_object obj, ets_method method_id, va_list args) + { + return native_interface->CallDoubleMethodList(this, obj, method_id, args); + } + ets_double CallDoubleMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + return native_interface->CallDoubleMethodArray(this, obj, method_id, args); + } + void CallVoidMethod(ets_object obj, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + native_interface->CallVoidMethodList(this, obj, method_id, args); + va_end(args); + } + void CallVoidMethodList(ets_object obj, ets_method method_id, va_list args) + { + native_interface->CallVoidMethodList(this, obj, method_id, args); + } + void CallVoidMethodArray(ets_object obj, ets_method method_id, const ets_value *args) + { + native_interface->CallVoidMethodArray(this, obj, method_id, args); + } + ets_object CallNonvirtualObjectMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_object res = native_interface->CallNonvirtualObjectMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_object CallNonvirtualObjectMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualObjectMethodList(this, obj, cls, method_id, args); + } + ets_object CallNonvirtualObjectMethodArray(ets_object obj, ets_class cls, ets_method method_id, + const ets_value *args) + { + return native_interface->CallNonvirtualObjectMethodArray(this, obj, cls, method_id, args); + } + ets_boolean CallNonvirtualBooleanMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_boolean res = native_interface->CallNonvirtualBooleanMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_boolean CallNonvirtualBooleanMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualBooleanMethodList(this, obj, cls, method_id, args); + } + ets_boolean CallNonvirtualBooleanMethodArray(ets_object obj, ets_class cls, ets_method method_id, + const ets_value *args) + { + return native_interface->CallNonvirtualBooleanMethodArray(this, obj, cls, method_id, args); + } + ets_byte CallNonvirtualByteMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_byte res = native_interface->CallNonvirtualByteMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_byte CallNonvirtualByteMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualByteMethodList(this, obj, cls, method_id, args); + } + ets_byte CallNonvirtualByteMethodArray(ets_object obj, ets_class cls, ets_method method_id, const ets_value *args) + { + return native_interface->CallNonvirtualByteMethodArray(this, obj, cls, method_id, args); + } + ets_char CallNonvirtualCharMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_char res = native_interface->CallNonvirtualCharMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_char CallNonvirtualCharMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualCharMethodList(this, obj, cls, method_id, args); + } + ets_char CallNonvirtualCharMethodArray(ets_object obj, ets_class cls, ets_method method_id, const ets_value *args) + { + return native_interface->CallNonvirtualCharMethodArray(this, obj, cls, method_id, args); + } + ets_short CallNonvirtualShortMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_short res = native_interface->CallNonvirtualShortMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_short CallNonvirtualShortMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualShortMethodList(this, obj, cls, method_id, args); + } + ets_short CallNonvirtualShortMethodArray(ets_object obj, ets_class cls, ets_method method_id, const ets_value *args) + { + return native_interface->CallNonvirtualShortMethodArray(this, obj, cls, method_id, args); + } + ets_int CallNonvirtualIntMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_int res = native_interface->CallNonvirtualIntMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_int CallNonvirtualIntMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualIntMethodList(this, obj, cls, method_id, args); + } + ets_int CallNonvirtualIntMethodArray(ets_object obj, ets_class cls, ets_method method_id, const ets_value *args) + { + return native_interface->CallNonvirtualIntMethodArray(this, obj, cls, method_id, args); + } + ets_long CallNonvirtualLongMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_long res = native_interface->CallNonvirtualLongMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_long CallNonvirtualLongMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualLongMethodList(this, obj, cls, method_id, args); + } + ets_long CallNonvirtualLongMethodArray(ets_object obj, ets_class cls, ets_method method_id, const ets_value *args) + { + return native_interface->CallNonvirtualLongMethodArray(this, obj, cls, method_id, args); + } + ets_float CallNonvirtualFloatMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_float res = native_interface->CallNonvirtualFloatMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_float CallNonvirtualFloatMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualFloatMethodList(this, obj, cls, method_id, args); + } + ets_float CallNonvirtualFloatMethodArray(ets_object obj, ets_class cls, ets_method method_id, const ets_value *args) + { + return native_interface->CallNonvirtualFloatMethodArray(this, obj, cls, method_id, args); + } + ets_double CallNonvirtualDoubleMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_double res = native_interface->CallNonvirtualDoubleMethodList(this, obj, cls, method_id, args); + va_end(args); + return res; + } + ets_double CallNonvirtualDoubleMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallNonvirtualDoubleMethodList(this, obj, cls, method_id, args); + } + ets_double CallNonvirtualDoubleMethodArray(ets_object obj, ets_class cls, ets_method method_id, + const ets_value *args) + { + return native_interface->CallNonvirtualDoubleMethodArray(this, obj, cls, method_id, args); + } + void CallNonvirtualVoidMethod(ets_object obj, ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + native_interface->CallNonvirtualVoidMethodList(this, obj, cls, method_id, args); + va_end(args); + } + void CallNonvirtualVoidMethodList(ets_object obj, ets_class cls, ets_method method_id, va_list args) + { + native_interface->CallNonvirtualVoidMethodList(this, obj, cls, method_id, args); + } + void CallNonvirtualVoidMethodArray(ets_object obj, ets_class cls, ets_method method_id, const ets_value *args) + { + native_interface->CallNonvirtualVoidMethodArray(this, obj, cls, method_id, args); + } + ets_field Getp_field(ets_class cls, const char *name, const char *sig) + { + return native_interface->Getp_field(this, cls, name, sig); + } + ets_object GetObjectField(ets_object obj, ets_field p_field) + { + return native_interface->GetObjectField(this, obj, p_field); + } + ets_boolean GetBooleanField(ets_object obj, ets_field p_field) + { + return native_interface->GetBooleanField(this, obj, p_field); + } + ets_byte GetByteField(ets_object obj, ets_field p_field) + { + return native_interface->GetByteField(this, obj, p_field); + } + ets_char GetCharField(ets_object obj, ets_field p_field) + { + return native_interface->GetCharField(this, obj, p_field); + } + ets_short GetShortField(ets_object obj, ets_field p_field) + { + return native_interface->GetShortField(this, obj, p_field); + } + ets_int GetIntField(ets_object obj, ets_field p_field) + { + return native_interface->GetIntField(this, obj, p_field); + } + ets_long GetLongField(ets_object obj, ets_field p_field) + { + return native_interface->GetLongField(this, obj, p_field); + } + ets_float GetFloatField(ets_object obj, ets_field p_field) + { + return native_interface->GetFloatField(this, obj, p_field); + } + ets_double GetDoubleField(ets_object obj, ets_field p_field) + { + return native_interface->GetDoubleField(this, obj, p_field); + } + void SetObjectField(ets_object obj, ets_field p_field, ets_object value) + { + return native_interface->SetObjectField(this, obj, p_field, value); + } + void SetBooleanField(ets_object obj, ets_field p_field, ets_boolean value) + { + return native_interface->SetBooleanField(this, obj, p_field, value); + } + void SetByteField(ets_object obj, ets_field p_field, ets_byte value) + { + return native_interface->SetByteField(this, obj, p_field, value); + } + void SetCharField(ets_object obj, ets_field p_field, ets_char value) + { + return native_interface->SetCharField(this, obj, p_field, value); + } + void SetShortField(ets_object obj, ets_field p_field, ets_short value) + { + return native_interface->SetShortField(this, obj, p_field, value); + } + void SetIntField(ets_object obj, ets_field p_field, ets_int value) + { + return native_interface->SetIntField(this, obj, p_field, value); + } + void SetLongField(ets_object obj, ets_field p_field, ets_long value) + { + return native_interface->SetLongField(this, obj, p_field, value); + } + void SetFloatField(ets_object obj, ets_field p_field, ets_float value) + { + return native_interface->SetFloatField(this, obj, p_field, value); + } + void SetDoubleField(ets_object obj, ets_field p_field, ets_double value) + { + return native_interface->SetDoubleField(this, obj, p_field, value); + } + ets_method GetStaticp_method(ets_class cls, const char *name, const char *sig) + { + return native_interface->GetStaticp_method(this, cls, name, sig); + } + ets_object CallStaticObjectMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_object res = native_interface->CallStaticObjectMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_object CallStaticObjectMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticObjectMethodList(this, cls, method_id, args); + } + ets_object CallStaticObjectMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticObjectMethodArray(this, cls, method_id, args); + } + ets_boolean CallStaticBooleanMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_boolean res = native_interface->CallStaticBooleanMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_boolean CallStaticBooleanMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticBooleanMethodList(this, cls, method_id, args); + } + ets_boolean CallStaticBooleanMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticBooleanMethodArray(this, cls, method_id, args); + } + ets_byte CallStaticByteMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_byte res = native_interface->CallStaticByteMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_byte CallStaticByteMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticByteMethodList(this, cls, method_id, args); + } + ets_byte CallStaticByteMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticByteMethodArray(this, cls, method_id, args); + } + ets_char CallStaticCharMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_char res = native_interface->CallStaticCharMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_char CallStaticCharMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticCharMethodList(this, cls, method_id, args); + } + ets_char CallStaticCharMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticCharMethodArray(this, cls, method_id, args); + } + ets_short CallStaticShortMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_short res = native_interface->CallStaticShortMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_short CallStaticShortMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticShortMethodList(this, cls, method_id, args); + } + ets_short CallStaticShortMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticShortMethodArray(this, cls, method_id, args); + } + ets_int CallStaticIntMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_int res = native_interface->CallStaticIntMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_int CallStaticIntMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticIntMethodList(this, cls, method_id, args); + } + ets_int CallStaticIntMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticIntMethodArray(this, cls, method_id, args); + } + ets_long CallStaticLongMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_long res = native_interface->CallStaticLongMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_long CallStaticLongMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticLongMethodList(this, cls, method_id, args); + } + ets_long CallStaticLongMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticLongMethodArray(this, cls, method_id, args); + } + ets_float CallStaticFloatMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_float res = native_interface->CallStaticFloatMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_float CallStaticFloatMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticFloatMethodList(this, cls, method_id, args); + } + ets_float CallStaticFloatMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticFloatMethodArray(this, cls, method_id, args); + } + ets_double CallStaticDoubleMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + ets_double res = native_interface->CallStaticDoubleMethodList(this, cls, method_id, args); + va_end(args); + return res; + } + ets_double CallStaticDoubleMethodList(ets_class cls, ets_method method_id, va_list args) + { + return native_interface->CallStaticDoubleMethodList(this, cls, method_id, args); + } + ets_double CallStaticDoubleMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + return native_interface->CallStaticDoubleMethodArray(this, cls, method_id, args); + } + void CallStaticVoidMethod(ets_class cls, ets_method method_id, ...) + { + va_list args; + va_start(args, method_id); + native_interface->CallStaticVoidMethodList(this, cls, method_id, args); + va_end(args); + } + void CallStaticVoidMethodList(ets_class cls, ets_method method_id, va_list args) + { + native_interface->CallStaticVoidMethodList(this, cls, method_id, args); + } + void CallStaticVoidMethodArray(ets_class cls, ets_method method_id, ets_value *args) + { + native_interface->CallStaticVoidMethodArray(this, cls, method_id, args); + } + ets_field GetStaticp_field(ets_class cls, const char *name, const char *sig) + { + return native_interface->GetStaticp_field(this, cls, name, sig); + } + ets_object GetStaticObjectField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticObjectField(this, cls, p_field); + } + ets_boolean GetStaticBooleanField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticBooleanField(this, cls, p_field); + } + ets_byte GetStaticByteField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticByteField(this, cls, p_field); + } + ets_char GetStaticCharField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticCharField(this, cls, p_field); + } + ets_short GetStaticShortField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticShortField(this, cls, p_field); + } + ets_int GetStaticIntField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticIntField(this, cls, p_field); + } + ets_long GetStaticLongField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticLongField(this, cls, p_field); + } + ets_float GetStaticFloatField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticFloatField(this, cls, p_field); + } + ets_double GetStaticDoubleField(ets_class cls, ets_field p_field) + { + return native_interface->GetStaticDoubleField(this, cls, p_field); + } + void SetStaticObjectField(ets_class cls, ets_field p_field, ets_object value) + { + return native_interface->SetStaticObjectField(this, cls, p_field, value); + } + void SetStaticBooleanField(ets_class cls, ets_field p_field, ets_boolean value) + { + return native_interface->SetStaticBooleanField(this, cls, p_field, value); + } + void SetStaticByteField(ets_class cls, ets_field p_field, ets_byte value) + { + return native_interface->SetStaticByteField(this, cls, p_field, value); + } + void SetStaticCharField(ets_class cls, ets_field p_field, ets_char value) + { + return native_interface->SetStaticCharField(this, cls, p_field, value); + } + void SetStaticShortField(ets_class cls, ets_field p_field, ets_short value) + { + return native_interface->SetStaticShortField(this, cls, p_field, value); + } + void SetStaticIntField(ets_class cls, ets_field p_field, ets_int value) + { + return native_interface->SetStaticIntField(this, cls, p_field, value); + } + void SetStaticLongField(ets_class cls, ets_field p_field, ets_long value) + { + return native_interface->SetStaticLongField(this, cls, p_field, value); + } + void SetStaticFloatField(ets_class cls, ets_field p_field, ets_float value) + { + return native_interface->SetStaticFloatField(this, cls, p_field, value); + } + void SetStaticDoubleField(ets_class cls, ets_field p_field, ets_double value) + { + return native_interface->SetStaticDoubleField(this, cls, p_field, value); + } + ets_string NewString(const ets_char *unicode_chars, ets_size len) + { + return native_interface->NewString(this, unicode_chars, len); + } + ets_size GetStringLength(ets_string string) + { + return native_interface->GetStringLength(this, string); + } + const ets_char *GetStringChars(ets_string string, ets_boolean *is_copy) + { + return native_interface->GetStringChars(this, string, is_copy); + } + void ReleaseStringChars(ets_string string, const ets_char *chars) + { + native_interface->ReleaseStringChars(this, string, chars); + } + ets_string NewStringUTF(const char *bytes) + { + return native_interface->NewStringUTF(this, bytes); + } + ets_size GetStringUTFLength(ets_string string) + { + return native_interface->GetStringUTFLength(this, string); + } + const char *GetStringUTFChars(ets_string string, ets_boolean *is_copy) + { + return native_interface->GetStringUTFChars(this, string, is_copy); + } + void ReleaseStringUTFChars(ets_string string, const char *chars) + { + native_interface->ReleaseStringUTFChars(this, string, chars); + } + ets_size GetArrayLength(ets_array array) + { + return native_interface->GetArrayLength(this, array); + } + ets_objectArray NewObjectsArray(ets_size length, ets_class element_class, ets_object initial_element) + { + return native_interface->NewObjectsArray(this, length, element_class, initial_element); + } + ets_object GetObjectArrayElement(ets_objectArray array, ets_size index) + { + return native_interface->GetObjectArrayElement(this, array, index); + } + + void SetObjectArrayElement(ets_objectArray array, ets_size index, ets_object value) + { + native_interface->SetObjectArrayElement(this, array, index, value); + } + + // SetObjectArrayElement, + ets_booleanArray NewBooleanArray(ets_size length) + { + return native_interface->NewBooleanArray(this, length); + } + ets_byteArray NewByteArray(ets_size length) + { + return native_interface->NewByteArray(this, length); + } + ets_charArray NewCharArray(ets_size length) + { + return native_interface->NewCharArray(this, length); + } + ets_shortArray NewShortArray(ets_size length) + { + return native_interface->NewShortArray(this, length); + } + ets_intArray NewIntArray(ets_size length) + { + return native_interface->NewIntArray(this, length); + } + ets_longArray NewLongArray(ets_size length) + { + return native_interface->NewLongArray(this, length); + } + ets_floatArray NewFloatArray(ets_size length) + { + return native_interface->NewFloatArray(this, length); + } + ets_doubleArray NewDoubleArray(ets_size length) + { + return native_interface->NewDoubleArray(this, length); + } + ets_boolean *PinBooleanArray(ets_booleanArray array) + { + return native_interface->PinBooleanArray(this, array); + } + ets_byte *PinByteArray(ets_byteArray array) + { + return native_interface->PinByteArray(this, array); + } + ets_char *PinCharArray(ets_charArray array) + { + return native_interface->PinCharArray(this, array); + } + ets_short *PinShortArray(ets_shortArray array) + { + return native_interface->PinShortArray(this, array); + } + ets_int *PinIntArray(ets_intArray array) + { + return native_interface->PinIntArray(this, array); + } + ets_long *PinLongArray(ets_longArray array) + { + return native_interface->PinLongArray(this, array); + } + ets_float *PinFloatArray(ets_floatArray array) + { + return native_interface->PinFloatArray(this, array); + } + ets_double *PinDoubleArray(ets_doubleArray array) + { + return native_interface->PinDoubleArray(this, array); + } + void UnpinBooleanArray(ets_booleanArray array) + { + return native_interface->UnpinBooleanArray(this, array); + } + void UnpinByteArray(ets_byteArray array) + { + return native_interface->UnpinByteArray(this, array); + } + void UnpinCharArray(ets_charArray array) + { + return native_interface->UnpinCharArray(this, array); + } + void UnpinShortArray(ets_shortArray array) + { + return native_interface->UnpinShortArray(this, array); + } + void UnpinIntArray(ets_intArray array) + { + return native_interface->UnpinIntArray(this, array); + } + void UnpinLongArray(ets_longArray array) + { + return native_interface->UnpinLongArray(this, array); + } + void UnpinFloatArray(ets_floatArray array) + { + return native_interface->UnpinFloatArray(this, array); + } + void UnpinDoubleArray(ets_doubleArray array) + { + return native_interface->UnpinDoubleArray(this, array); + } + void GetBooleanArrayRegion(ets_booleanArray array, ets_size start, ets_size len, ets_boolean *buf) + { + return native_interface->GetBooleanArrayRegion(this, array, start, len, buf); + } + void GetByteArrayRegion(ets_byteArray array, ets_size start, ets_size len, ets_byte *buf) + { + return native_interface->GetByteArrayRegion(this, array, start, len, buf); + } + void GetCharArrayRegion(ets_charArray array, ets_size start, ets_size len, ets_char *buf) + { + return native_interface->GetCharArrayRegion(this, array, start, len, buf); + } + void GetShortArrayRegion(ets_shortArray array, ets_size start, ets_size len, ets_short *buf) + { + return native_interface->GetShortArrayRegion(this, array, start, len, buf); + } + void GetIntArrayRegion(ets_intArray array, ets_size start, ets_size len, ets_int *buf) + { + return native_interface->GetIntArrayRegion(this, array, start, len, buf); + } + void GetLongArrayRegion(ets_longArray array, ets_size start, ets_size len, ets_long *buf) + { + return native_interface->GetLongArrayRegion(this, array, start, len, buf); + } + void GetFloatArrayRegion(ets_floatArray array, ets_size start, ets_size len, ets_float *buf) + { + return native_interface->GetFloatArrayRegion(this, array, start, len, buf); + } + void GetDoubleArrayRegion(ets_doubleArray array, ets_size start, ets_size len, ets_double *buf) + { + return native_interface->GetDoubleArrayRegion(this, array, start, len, buf); + } + void SetBooleanArrayRegion(ets_booleanArray array, ets_size start, ets_size length, const ets_boolean *buf) + { + native_interface->SetBooleanArrayRegion(this, array, start, length, buf); + } + void SetByteArrayRegion(ets_byteArray array, ets_size start, ets_size length, const ets_byte *buf) + { + native_interface->SetByteArrayRegion(this, array, start, length, buf); + } + void SetCharArrayRegion(ets_charArray array, ets_size start, ets_size length, const ets_char *buf) + { + native_interface->SetCharArrayRegion(this, array, start, length, buf); + } + void SetShortArrayRegion(ets_shortArray array, ets_size start, ets_size length, const ets_short *buf) + { + native_interface->SetShortArrayRegion(this, array, start, length, buf); + } + void SetIntArrayRegion(ets_intArray array, ets_size start, ets_size length, const ets_int *buf) + { + native_interface->SetIntArrayRegion(this, array, start, length, buf); + } + void SetLongArrayRegion(ets_longArray array, ets_size start, ets_size length, const ets_long *buf) + { + native_interface->SetLongArrayRegion(this, array, start, length, buf); + } + void SetFloatArrayRegion(ets_floatArray array, ets_size start, ets_size length, const ets_float *buf) + { + native_interface->SetFloatArrayRegion(this, array, start, length, buf); + } + void SetDoubleArrayRegion(ets_doubleArray array, ets_size start, ets_size length, const ets_double *buf) + { + native_interface->SetDoubleArrayRegion(this, array, start, length, buf); + } + ets_int RegisterNatives(ets_class cls, const EtsNativeMethod *methods, ets_int nMethods) + { + return native_interface->RegisterNatives(this, cls, methods, nMethods); + } + ets_int UnregisterNatives(ets_class cls) + { + return native_interface->UnregisterNatives(this, cls); + } + ets_int GetEtsVM(EtsVM **vm) + { + return native_interface->GetEtsVM(this, vm); + } + void GetStringRegion(ets_string str, ets_size start, ets_size len, ets_char *buf) + { + native_interface->GetStringRegion(this, str, start, len, buf); + } + void GetStringUTFRegion(ets_string str, ets_size start, ets_size len, char *buf) + { + native_interface->GetStringUTFRegion(this, str, start, len, buf); + } + ets_weak NewWeakGlobalRef(ets_object obj) + { + return native_interface->NewWeakGlobalRef(this, obj); + } + void DeleteWeakGlobalRef(ets_weak obj) + { + native_interface->DeleteWeakGlobalRef(this, obj); + } + ets_boolean ErrorCheck() + { + return native_interface->ErrorCheck(this); + } + // NewDirectByteBuffer, + // GetDirectBufferAddress, + // GetDirectBufferCapacity, + ets_objectRefType GetObjectRefType(ets_object obj) + { + return native_interface->GetObjectRefType(this, obj); + } + + // Promise + ets_status PromiseCreate(ets_deferred *deferred, ets_object *promise) + { + return native_interface->PromiseCreate(this, deferred, promise); + } + ets_status DeferredResolve(ets_deferred deferred, ets_object resolution) + { + return native_interface->DeferredResolve(this, deferred, resolution); + } + ets_status DeferredReject(ets_deferred deferred, ets_object rejection) + { + return native_interface->DeferredReject(this, deferred, rejection); + } +#endif +}; + +// NOLINTEND(modernize-use-using, readability-identifier-naming, cppcoreguidelines-pro-type-vararg) + +#endif // PANDA_RUNTIME_INTEROP_ETS_NAPI_H diff --git a/koala-wrapper/koalaui/interop/src/cpp/interop-logging.cc b/koala-wrapper/koalaui/interop/src/cpp/interop-logging.cc new file mode 100644 index 000000000..073878547 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/interop-logging.cc @@ -0,0 +1,79 @@ +/* + * 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 "interop-logging.h" + +namespace { + +struct Log { + std::string log; + bool isActive = true; +}; + +std::vector groupedLogs; + +void startGroupedLog(int index) { + if (index >= (int)groupedLogs.size()) { + groupedLogs.resize(index + 1); + for (int i = 0; i <= index; i++) { + if (!groupedLogs[i]) groupedLogs[i] = new Log(); + } + } + groupedLogs[index]->isActive = true; + groupedLogs[index]->log.clear(); +} + +void stopGroupedLog(int index) { + if (index < (int)groupedLogs.size()) { + groupedLogs[index]->isActive = false; + } +} + +void appendGroupedLog(int index, const char* str) { + if (index < (int)groupedLogs.size()) { + groupedLogs[index]->log.append(str); + } +} + +const char* getGroupedLog(int index) { + if (index < (int)groupedLogs.size()) { + auto result = groupedLogs[index]->log.c_str(); + return result; + } + return ""; +} + +int needGroupedLog(int index) { + if (index < (int)groupedLogs.size()) { + return groupedLogs[index]->isActive; + } + return 0; +} + +const GroupLogger defaultInstance = { + startGroupedLog, + stopGroupedLog, + appendGroupedLog, + getGroupedLog, + needGroupedLog, +}; + +} // namespace + +const GroupLogger* GetDefaultLogger() { + return &defaultInstance; +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/interop-logging.h b/koala-wrapper/koalaui/interop/src/cpp/interop-logging.h new file mode 100644 index 000000000..4d1b7bc0f --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/interop-logging.h @@ -0,0 +1,51 @@ +/* + * 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 _INTEROP_LGGING_H +#define _INTEROP_LGGING_H + +#include +#include + +#if defined(KOALA_OHOS) +#include "oh_sk_log.h" +#define LOG(msg) OH_SK_LOG_INFO(msg); +#define LOGI(msg, ...) OH_SK_LOG_INFO_A(msg, ##__VA_ARGS__); +#define LOGE(msg, ...) OH_SK_LOG_ERROR_A(msg, ##__VA_ARGS__); +#define LOG_PUBLIC "{public}" +#else +#define LOG(msg) fprintf(stdout, msg "\n"); +#define LOGI(msg, ...) fprintf(stdout, msg "\n", ##__VA_ARGS__); +#define LOGE(msg, ...) fprintf(stderr, msg "\n", ##__VA_ARGS__); +#define LOG_PUBLIC "" +#endif + +#if defined(KOALA_WINDOWS) +#define INTEROP_API_EXPORT __declspec(dllexport) +#else +#define INTEROP_API_EXPORT __attribute__((visibility("default"))) +#endif + +// Grouped logs. Keep consistent with type in ServiceGroupLogger +typedef struct GroupLogger { + void (*startGroupedLog)(int kind); + void (*stopGroupedLog)(int kind); + void (*appendGroupedLog)(int kind, const char* str); + const char* (*getGroupedLog)(int kind); + int (*needGroupedLog)(int kind); +} GroupLogger; + +const GroupLogger* GetDefaultLogger(); + +#endif // _INTEROP_LOGGING_H \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/interop-types.h b/koala-wrapper/koalaui/interop/src/cpp/interop-types.h new file mode 100644 index 000000000..4c5c26187 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/interop-types.h @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2022-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 _INTEROP_TYPES_H_ +#define _INTEROP_TYPES_H_ + +#include + +#define INTEROP_FATAL(msg, ...) do { fprintf(stderr, msg "\n", ##__VA_ARGS__); abort(); } while (0) + +typedef enum InteropTag +{ + INTEROP_TAG_UNDEFINED = 101, + INTEROP_TAG_INT32 = 102, + INTEROP_TAG_FLOAT32 = 103, + INTEROP_TAG_STRING = 104, + INTEROP_TAG_LENGTH = 105, + INTEROP_TAG_RESOURCE = 106, + INTEROP_TAG_OBJECT = 107, +} InteropTag; + +typedef enum InteropRuntimeType +{ + INTEROP_RUNTIME_UNEXPECTED = -1, + INTEROP_RUNTIME_NUMBER = 1, + INTEROP_RUNTIME_STRING = 2, + INTEROP_RUNTIME_OBJECT = 3, + INTEROP_RUNTIME_BOOLEAN = 4, + INTEROP_RUNTIME_UNDEFINED = 5, + INTEROP_RUNTIME_BIGINT = 6, + INTEROP_RUNTIME_FUNCTION = 7, + INTEROP_RUNTIME_SYMBOL = 8, + INTEROP_RUNTIME_MATERIALIZED = 9, +} InteropRuntimeType; + +typedef float InteropFloat32; +typedef double InteropFloat64; +typedef int32_t InteropInt32; +typedef unsigned int InteropUInt32; // TODO: update unsigned int +typedef int64_t InteropInt64; +typedef uint64_t InteropUInt64; +typedef int8_t InteropInt8; +typedef uint8_t InteropUInt8; +typedef int64_t InteropDate; +typedef int8_t InteropBoolean; +typedef const char* InteropCharPtr; +typedef void* InteropNativePointer; + +struct _InteropVMContext; +typedef struct _InteropVMContext* InteropVMContext; +struct _InteropPipelineContext; +typedef struct _InteropPipelineContext* InteropPipelineContext; +struct _InteropVMObject; +typedef struct _InteropVMObject* InteropVMObject; +struct _InteropNode; +typedef struct _InteropNode* InteropNodeHandle; +typedef struct InteropDeferred { + void* handler; + void* context; + void (*resolve)(struct InteropDeferred* thiz, uint8_t* data, int32_t length); + void (*reject)(struct InteropDeferred* thiz, const char* message); +} InteropDeferred; + +// Binary layout of InteropString must match that of KStringPtrImpl. +typedef struct InteropString { + const char* chars; + InteropInt32 length; +} InteropString; + +typedef struct InteropEmpty { + InteropInt32 dummy; // Empty structs are forbidden in C. +} InteropEmpty; + +typedef struct InteropNumber { + InteropInt8 tag; + union { + InteropFloat32 f32; + InteropInt32 i32; + }; +} InteropNumber; + +// Binary layout of InteropLength must match that of KLength. +typedef struct InteropLength +{ + InteropInt8 type; + InteropFloat32 value; + InteropInt32 unit; + InteropInt32 resource; +} InteropLength; + +typedef struct InteropCustomObject { + char kind[20]; + InteropInt32 id; + // Data of custom object. + union { + InteropInt32 ints[4]; + InteropFloat32 floats[4]; + void* pointers[4]; + InteropString string; + }; +} InteropCustomObject; + +typedef struct InteropUndefined { + InteropInt32 dummy; // Empty structs are forbidden in C. +} InteropUndefined; + +typedef struct InteropVoid { + InteropInt32 dummy; // Empty structs are forbidden in C. +} InteropVoid; + +typedef struct InteropFunction { + InteropInt32 id; +} InteropFunction; +typedef InteropFunction InteropCallback; +typedef InteropFunction InteropErrorCallback; + +typedef struct InteropMaterialized { + InteropNativePointer ptr; +} InteropMaterialized; + +typedef struct InteropCallbackResource { + InteropInt32 resourceId; + void (*hold)(InteropInt32 resourceId); + void (*release)(InteropInt32 resourceId); +} InteropCallbackResource; + +typedef struct InteropBuffer { + InteropCallbackResource resource; + InteropNativePointer data; + InteropInt64 length; +} InteropBuffer; + +#endif // _INTEROP_TYPES_H_ diff --git a/koala-wrapper/koalaui/interop/src/cpp/jni/convertors-jni.cc b/koala-wrapper/koalaui/interop/src/cpp/jni/convertors-jni.cc new file mode 100644 index 000000000..782f2c2e3 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/jni/convertors-jni.cc @@ -0,0 +1,107 @@ +/* + * 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. + */ + + +#define KOALA_INTEROP_MODULE +#include "convertors-jni.h" +#include "signatures.h" +#include "interop-logging.h" +#include "interop-types.h" + +static const char* nativeModule = "org/koalaui/arkoala/InteropNativeModule"; +static const char* nativeModulePrefix = "org/koalaui/arkoala/"; +static const char* callCallbackFromNative = "callCallbackFromNative"; +static const char* callCallbackFromNativeSig = "(I[BI)I"; + +const bool registerByOne = true; + +static bool registerNatives(JNIEnv *env, jclass clazz, const std::vector> impls) { + size_t numMethods = impls.size(); + JNINativeMethod *methods = new JNINativeMethod[numMethods]; + bool result = true; + for (size_t i = 0; i < numMethods; i++) + { + methods[i].name = (char *)std::get<0>(impls[i]).c_str(); + methods[i].signature = (char *)std::get<1>(impls[i]).c_str(); + methods[i].fnPtr = std::get<2>(impls[i]); + if (registerByOne) { + result &= (env->RegisterNatives(clazz, methods + i, 1) >= 0); + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + result = false; + } + } + } + return registerByOne ? true : env->RegisterNatives(clazz, methods, numMethods) >= 0; +} + +constexpr bool splitPerModule = true; + +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { + JNIEnv *env; + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_8) != JNI_OK) { + return JNI_ERR; + } + auto modules = JniExports::getInstance()->getModules(); + jclass defaultNativeModule = env->FindClass(nativeModule); + for (auto it = modules.begin(); it != modules.end(); ++it) { + std::string className = std::string(nativeModulePrefix) + *it; + jclass nativeModule = + (!splitPerModule) ? defaultNativeModule : env->FindClass(className.c_str()); + if (nativeModule == nullptr) { + LOGE("Cannot find managed class %s", className.c_str()); + continue; + } + registerNatives(env, nativeModule, JniExports::getInstance()->getMethods(*it)); + } + if (!setKoalaJniCallbackDispatcher(env, defaultNativeModule, callCallbackFromNative, callCallbackFromNativeSig)) return JNI_ERR; + return JNI_VERSION_1_8; +} + +JniExports *JniExports::getInstance() +{ + static JniExports *instance = nullptr; + if (instance == nullptr) + { + instance = new JniExports(); + } + return instance; +} + +std::vector JniExports::getModules() { + std::vector result; + for (auto it = implementations.begin(); it != implementations.end(); ++it) { + result.push_back(it->first); + } + return result; +} + +const std::vector>& JniExports::getMethods(const std::string& module) { + auto it = implementations.find(module); + if (it == implementations.end()) { + LOGE("Module %s is not registered", module.c_str()); + INTEROP_FATAL("Fatal error: not registered module %s", module.c_str()); + } + return it->second; +} + +void JniExports::addMethod(const char* module, const char *name, const char *type, void *impl) { + auto it = implementations.find(module); + if (it == implementations.end()) { + it = implementations.insert(std::make_pair(module, std::vector>())).first; + } + it->second.push_back(std::make_tuple(name, convertType(name, type), impl)); +} diff --git a/koala-wrapper/koalaui/interop/src/cpp/jni/convertors-jni.h b/koala-wrapper/koalaui/interop/src/cpp/jni/convertors-jni.h new file mode 100644 index 000000000..2ebefafe7 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/jni/convertors-jni.h @@ -0,0 +1,1465 @@ +/* + * 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. + */ + +#pragma once + +#ifdef KOALA_JNI + +#include +#include + +#include +#include +#include +#include +#include + +#include "koala-types.h" + +#define KOALA_JNI_CALL(type) extern "C" JNIEXPORT type JNICALL + +class JniExports { + std::unordered_map>> implementations; + +public: + static JniExports* getInstance(); + + std::vector getModules(); + void addMethod(const char* module, const char* name, const char* type, void* impl); + const std::vector>& getMethods(const std::string& module); +}; + +#define KOALA_QUOTE0(x) #x +#define KOALA_QUOTE(x) KOALA_QUOTE0(x) + +#ifdef _MSC_VER +#define MAKE_JNI_EXPORT(module, name, type) \ + static void __init_##name() { \ + JniExports::getInstance()->addMethod(KOALA_QUOTE(module), "_"#name, type, reinterpret_cast(Java_org_##name)); \ + } \ + namespace { \ + struct __Init_##name { \ + __Init_##name() { __init_##name(); } \ + } __Init_##name##_v; \ + } +#else +#define MAKE_JNI_EXPORT(module, name, type) \ + __attribute__((constructor)) \ + static void __init_jni_##name() { \ + JniExports::getInstance()->addMethod(KOALA_QUOTE(module), "_"#name, type, reinterpret_cast(Java_org_##name)); \ + } +#endif + +template +struct InteropTypeConverter { + using InteropType = T; + static T convertFrom(JNIEnv* env, InteropType value) { return value; } + static InteropType convertTo(JNIEnv* env, T value) { return value; } + static void release(JNIEnv* env, InteropType value, T converted) {} +}; + +template +struct SlowInteropTypeConverter { + using InteropType = T; + static inline T convertFrom(JNIEnv* env, InteropType value) { return value; } + static inline InteropType convertTo(JNIEnv* env, T value) { return value; } + static void release(JNIEnv* env, InteropType value, T converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = jstring; + static inline KStringPtr convertFrom0(JNIEnv* env, InteropType value) { + if (value == nullptr) return KStringPtr(); + jboolean isCopy; + // TODO: use GetStringCritical() instead and utf-8 encode manually. + const char* str_value = env->GetStringUTFChars(value, &isCopy); + int len = env->GetStringUTFLength(value); + KStringPtr result(str_value, len, false); + return result; + } + static KStringPtr convertFrom(JNIEnv* env, InteropType value) { + if (value == nullptr) return KStringPtr(); + KStringPtr result; + // Notice that we use UTF length for buffer size, but counter is expressed in number of Unicode chars. + result.resize( env->GetStringUTFLength(value)); + env->GetStringUTFRegion(value, 0, env->GetStringLength(value), result.data()); + return result; + } + static InteropType convertTo(JNIEnv* env, KStringPtr value) = delete; + static inline void release(JNIEnv* env, InteropType value, const KStringPtr& converted) { + } +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jobject; + static inline KVMObjectHandle convertFrom(JNIEnv* env, InteropType value) { + return reinterpret_cast(value); + } + static InteropType convertTo(JNIEnv* env, KVMObjectHandle value) { + return reinterpret_cast(value); + } + static inline void release(JNIEnv* env, InteropType value, KVMObjectHandle converted) { + } +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jstring; + static inline KStringPtr convertFrom(JNIEnv* env, InteropType value) { + if (value == nullptr) return KStringPtr(); + jboolean isCopy; + const char* str_value = env->GetStringUTFChars(value, &isCopy); + int len = env->GetStringLength(value); + KStringPtr result(str_value, len, false); + return result; + } + static InteropType convertTo(JNIEnv* env, KStringPtr value) { + return env->NewStringUTF(value.c_str()); + } + static inline void release(JNIEnv* env, InteropType value, const KStringPtr& converted) { + env->ReleaseStringUTFChars(value, converted.data()); + } +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jarray; + static inline KInteropBuffer convertFrom(JNIEnv* env, InteropType value) { + if (value == nullptr) return KInteropBuffer(); + KInteropBuffer result({env->GetArrayLength(value), reinterpret_cast(env->GetPrimitiveArrayCritical(value, nullptr))}); + return result; + } + static InteropType convertTo(JNIEnv* env, KInteropBuffer value) { + jarray result = env->NewByteArray(value.length); + void* data = env->GetPrimitiveArrayCritical(result, nullptr); + memcpy(data, value.data, value.length); + env->ReleasePrimitiveArrayCritical(result, data, 0); + return result; + } + static inline void release(JNIEnv* env, InteropType value, const KInteropBuffer& converted) { + env->ReleasePrimitiveArrayCritical(value, converted.data, 0); + } +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jarray; + static inline KInteropReturnBuffer convertFrom(JNIEnv* env, InteropType value) = delete; + static InteropType convertTo(JNIEnv* env, KInteropReturnBuffer value) { + jarray result = env->NewByteArray(value.length); + void* data = env->GetPrimitiveArrayCritical(result, nullptr); + memcpy(data, value.data, value.length); + env->ReleasePrimitiveArrayCritical(result, data, 0); + value.dispose(value.data, value.length); + return result; + } + static inline void release(JNIEnv* env, InteropType value, const KInteropReturnBuffer& converted) = delete; +}; + +template<> +struct InteropTypeConverter { + using InteropType = jbyteArray; + static inline KByte* convertFrom(JNIEnv* env, InteropType value) { + return value ? reinterpret_cast(env->GetPrimitiveArrayCritical(value, nullptr)) : nullptr; + } + static InteropType convertTo(JNIEnv* env, KByte* value) = delete; + static inline void release(JNIEnv* env, InteropType value, KByte* converted) { + if (converted) env->ReleasePrimitiveArrayCritical(value, converted, 0); + } +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jbyteArray; + static inline KByte* convertFrom(JNIEnv* env, InteropType value) { + return value ? reinterpret_cast(env->GetByteArrayElements(value, nullptr)) : nullptr; + } + static InteropType convertTo(JNIEnv* env, KByte* value) = delete; + static inline void release(JNIEnv* env, InteropType value, KByte* converted) { + if (converted) env->ReleaseByteArrayElements(value, reinterpret_cast(converted), 0); + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = jintArray; + static KInt* convertFrom(JNIEnv* env, InteropType value) { + return value ? reinterpret_cast(env->GetPrimitiveArrayCritical(value, nullptr)) : nullptr; + } + static InteropType convertTo(JNIEnv* env, KInt* value) = delete; + static void release(JNIEnv* env, InteropType value, KInt* converted) { + env->ReleasePrimitiveArrayCritical(value, converted, 0); + } +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jintArray; + static KInt* convertFrom(JNIEnv* env, InteropType value) { + return value ? reinterpret_cast(env->GetIntArrayElements(value, nullptr)) : nullptr; + } + static InteropType convertTo(JNIEnv* env, KInt* value) = delete; + static void release(JNIEnv* env, InteropType value, KInt* converted) { + env->ReleaseIntArrayElements(value, reinterpret_cast(converted), 0); + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = jfloatArray; + static KFloat* convertFrom(JNIEnv* env, InteropType value) { + return value ? reinterpret_cast(env->GetPrimitiveArrayCritical(value, nullptr)) : nullptr; + } + static InteropType convertTo(JNIEnv* env, KFloat* value) = delete; + static void release(JNIEnv* env, InteropType value, KFloat* converted) { + env->ReleasePrimitiveArrayCritical(value, converted, 0); + } +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jfloatArray; + static KFloat* convertFrom(JNIEnv* env, InteropType value) { + return value ? reinterpret_cast(env->GetFloatArrayElements(value, nullptr)) : nullptr; + } + static InteropType convertTo(JNIEnv* env, KFloat* value) = delete; + static void release(JNIEnv* env, InteropType value, KFloat* converted) { + env->ReleaseFloatArrayElements(value, reinterpret_cast(converted), 0); + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = jlong; + static KNativePointer convertFrom(JNIEnv* env, InteropType value) { + return reinterpret_cast(value); + } + static InteropType convertTo(JNIEnv* env, KNativePointer value) { + return reinterpret_cast(value); + } + static inline void release(JNIEnv* env, InteropType value, KNativePointer converted) {} +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jlong; + static KNativePointer convertFrom(JNIEnv* env, InteropType value) { + return reinterpret_cast(value); + } + static InteropType convertTo(JNIEnv* env, KNativePointer value) { + return reinterpret_cast(value); + } + static void release(JNIEnv* env, InteropType value, KNativePointer converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = jdouble; + static KInteropNumber convertFrom(JNIEnv* env, InteropType value) { + return KInteropNumber::fromDouble(value); + } + static InteropType convertTo(JNIEnv* env, KInteropNumber value) { + return value.asDouble(); + } + static inline void release(JNIEnv* env, InteropType value, KInteropNumber converted) {} +}; + +template<> +struct SlowInteropTypeConverter { + using InteropType = jdouble; + static KInteropNumber convertFrom(JNIEnv* env, InteropType value) { + return KInteropNumber::fromDouble(value); + } + static InteropType convertTo(JNIEnv* env, KInteropNumber value) { + return value.asDouble(); + } + static void release(JNIEnv* env, InteropType value, KInteropNumber converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = jstring; + static KLength convertFrom(JNIEnv* env, InteropType value) { + KLength result = { 0 }; + + if (value == nullptr) { + result.type = -1; // ARK_RUNTIME_UNEXPECTED + return result; + } + jboolean isCopy; + const char* str_value = env->GetStringUTFChars(value, &isCopy); + int len = env->GetStringLength(value); + KStringPtr kStr(str_value, len, false); + parseKLength(kStr, &result); + env->ReleaseStringUTFChars(value, str_value); + result.type = 2; // ARK_RUNTIME_STRING + result.resource = 0; + + return result; + } + static InteropType convertTo(JNIEnv* env, KLength value) = delete; + static inline void release(JNIEnv* env, InteropType value, KLength converted) {} +}; + +template +inline Type getArgument(JNIEnv* env, typename InteropTypeConverter::InteropType arg) { + return InteropTypeConverter::convertFrom(env, arg); +} + +template +inline void releaseArgument(JNIEnv* env, typename InteropTypeConverter::InteropType arg, Type& data) { + InteropTypeConverter::release(env, arg, data); +} + +#ifndef KOALA_INTEROP_MODULE +#error KOALA_INTEROP_MODULE is undefined +#endif + +#define KOALA_INTEROP_0(name, Ret) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance) { \ + KOALA_MAYBE_LOG(name) \ + return InteropTypeConverter::convertTo(env, impl_##name()); \ + } \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret) + +#define KOALA_INTEROP_1(name, Ret, P0) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) \ + Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0)); \ + releaseArgument(env, _p0, p0); \ + return rv; \ + } \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0) + +#define KOALA_INTEROP_2(name, Ret, P0, P1) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1) + +#define KOALA_INTEROP_3(name, Ret, P0, P1, P2) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2) + +#define KOALA_INTEROP_4(name, Ret, P0, P1, P2, P3) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3) + +#define KOALA_INTEROP_5(name, Ret, P0, P1, P2, P3, P4) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4) + +#define KOALA_INTEROP_6(name, Ret, P0, P1, P2, P3, P4, P5) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5) + +#define KOALA_INTEROP_7(name, Ret, P0, P1, P2, P3, P4, P5, P6) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5, p6)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6) + +#define KOALA_INTEROP_8(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7) + +#define KOALA_INTEROP_9(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8) + +#define KOALA_INTEROP_10(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9) + +#define KOALA_INTEROP_11(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10) + +#define KOALA_INTEROP_12(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11) + +#define KOALA_INTEROP_13(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9"|" #P10 "|" #P11 "|" #P12) + +#define KOALA_INTEROP_14(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + KOALA_JNI_CALL(InteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + auto rv = InteropTypeConverter::convertTo(env, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9"|" #P10 "|" #P11 "|" #P12 "|" #P13) + + +#define KOALA_INTEROP_V0(name) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance) { \ + KOALA_MAYBE_LOG(name) \ + impl_##name(); \ + } \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void") + +#define KOALA_INTEROP_V1(name, P0) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + impl_##name(p0); \ + releaseArgument(env, _p0, p0); \ + } \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0) + +#define KOALA_INTEROP_V2(name, P0, P1) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + impl_##name(p0, p1); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1) + +#define KOALA_INTEROP_V3(name, P0, P1, P2) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + impl_##name(p0, p1, p2); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2) + +#define KOALA_INTEROP_V4(name, P0, P1, P2, P3) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + impl_##name(p0, p1, p2, p3); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3) + +#define KOALA_INTEROP_V5(name, P0, P1, P2, P3, P4) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + impl_##name(p0, p1, p2, p3, p4); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4) + +#define KOALA_INTEROP_V6(name, P0, P1, P2, P3, P4, P5) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + impl_##name(p0, p1, p2, p3, p4, p5); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5) + +#define KOALA_INTEROP_V7(name, P0, P1, P2, P3, P4, P5, P6) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6) + +#define KOALA_INTEROP_V8(name, P0, P1, P2, P3, P4, P5, P6, P7) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7) + +#define KOALA_INTEROP_V9(name, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8) + +#define KOALA_INTEROP_V10(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9) + +#define KOALA_INTEROP_V11(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10) + +#define KOALA_INTEROP_V12(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11) + +#define KOALA_INTEROP_V13(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12) + +#define KOALA_INTEROP_V14(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13) + +#define KOALA_INTEROP_V15(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13, \ + InteropTypeConverter::InteropType _p14) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + P5 p5 = getArgument(env, _p5); \ + P6 p6 = getArgument(env, _p6); \ + P7 p7 = getArgument(env, _p7); \ + P8 p8 = getArgument(env, _p8); \ + P9 p9 = getArgument(env, _p9); \ + P10 p10 = getArgument(env, _p10); \ + P11 p11 = getArgument(env, _p11); \ + P12 p12 = getArgument(env, _p12); \ + P13 p13 = getArgument(env, _p13); \ + P14 p14 = getArgument(env, _p14); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ + releaseArgument(env, _p5, p5); \ + releaseArgument(env, _p6, p6); \ + releaseArgument(env, _p7, p7); \ + releaseArgument(env, _p8, p8); \ + releaseArgument(env, _p9, p9); \ + releaseArgument(env, _p10, p10); \ + releaseArgument(env, _p11, p11); \ + releaseArgument(env, _p12, p12); \ + releaseArgument(env, _p13, p13); \ + releaseArgument(env, _p14, p14); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4 "|" #P5 "|" #P6 "|" #P7 "|" #P8 "|" #P9 "|" #P10 "|" #P11 "|" #P12 "|" #P13 "|" #P14) + +#define KOALA_INTEROP_CTX_0(name, Ret) \ + KOALA_JNI_CALL(SlowInteropTypeConverter::InteropType) \ + Java_org_##name(JNIEnv* env, jclass instance) { \ + KOALA_MAYBE_LOG(name) \ + KVMContext ctx = (KVMContext)env; \ + auto rv = SlowInteropTypeConverter::convertTo(env, impl_##name(ctx)); \ + return rv; \ + } \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret) + +#define KOALA_INTEROP_CTX_1(name, Ret, P0) \ + KOALA_JNI_CALL(SlowInteropTypeConverter::InteropType) \ + Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = SlowInteropTypeConverter::convertTo(env, impl_##name(ctx, p0)); \ + releaseArgument(env, _p0, p0); \ + return rv; \ + } \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0) + +#define KOALA_INTEROP_CTX_2(name, Ret, P0, P1) \ + KOALA_JNI_CALL(SlowInteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0, \ + SlowInteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = SlowInteropTypeConverter::convertTo(env, impl_##name(ctx, p0, p1)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1) + +#define KOALA_INTEROP_CTX_3(name, Ret, P0, P1, P2) \ + KOALA_JNI_CALL(SlowInteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0, \ + SlowInteropTypeConverter::InteropType _p1, \ + SlowInteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = SlowInteropTypeConverter::convertTo(env, impl_##name(ctx, p0, p1, p2)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2) + +#define KOALA_INTEROP_CTX_4(name, Ret, P0, P1, P2, P3) \ + KOALA_JNI_CALL(SlowInteropTypeConverter::InteropType) Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0, \ + SlowInteropTypeConverter::InteropType _p1, \ + SlowInteropTypeConverter::InteropType _p2, \ + SlowInteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + KVMContext ctx = (KVMContext)env; \ + auto rv = SlowInteropTypeConverter::convertTo(env, impl_##name(ctx, p0, p1, p2, p3)); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + return rv; \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, #Ret "|" #P0 "|" #P1 "|" #P2 "|" #P3) + +#define KOALA_INTEROP_CTX_V0(name) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance) { \ + KOALA_MAYBE_LOG(name) \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx); \ + } \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void") + +#define KOALA_INTEROP_CTX_V1(name, P0) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0); \ + releaseArgument(env, _p0, p0); \ + } \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0) + +#define KOALA_INTEROP_CTX_V2(name, P0, P1) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0, \ + SlowInteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1) + +#define KOALA_INTEROP_CTX_V3(name, P0, P1, P2) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0, \ + SlowInteropTypeConverter::InteropType _p1, \ + SlowInteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2) + +#define KOALA_INTEROP_CTX_V4(name, P0, P1, P2, P3) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0, \ + SlowInteropTypeConverter::InteropType _p1, \ + SlowInteropTypeConverter::InteropType _p2, \ + SlowInteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2, p3); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3) + +#define KOALA_INTEROP_CTX_V5(name, P0, P1, P2, P3, P4) \ + KOALA_JNI_CALL(void) Java_org_##name(JNIEnv* env, jclass instance, \ + SlowInteropTypeConverter::InteropType _p0, \ + SlowInteropTypeConverter::InteropType _p1, \ + SlowInteropTypeConverter::InteropType _p2, \ + SlowInteropTypeConverter::InteropType _p3, \ + SlowInteropTypeConverter::InteropType _p4) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(env, _p0); \ + P1 p1 = getArgument(env, _p1); \ + P2 p2 = getArgument(env, _p2); \ + P3 p3 = getArgument(env, _p3); \ + P4 p4 = getArgument(env, _p4); \ + KVMContext ctx = (KVMContext)env; \ + impl_##name(ctx, p0, p1, p2, p3, p4); \ + releaseArgument(env, _p0, p0); \ + releaseArgument(env, _p1, p1); \ + releaseArgument(env, _p2, p2); \ + releaseArgument(env, _p3, p3); \ + releaseArgument(env, _p4, p4); \ +} \ +MAKE_JNI_EXPORT(KOALA_INTEROP_MODULE, name, "void|" #P0 "|" #P1 "|" #P2 "|" #P3 "|" #P4) + +bool setKoalaJniCallbackDispatcher( + JNIEnv* env, + jclass clazz, + const char* dispatcherMethodName, + const char* dispactherMethodSig +); +void getKoalaJniCallbackDispatcher(jclass* clazz, jmethodID* method); + +#define KOALA_INTEROP_CALL_VOID(venv, id, length, args) \ +{ \ + jclass clazz = nullptr; \ + jmethodID method = nullptr; \ + getKoalaJniCallbackDispatcher(&clazz, &method); \ + JNIEnv* jniEnv = reinterpret_cast(venv); \ + jniEnv->PushLocalFrame(1); \ + jbyteArray args_jni = jniEnv->NewByteArray(length); \ + jniEnv->SetByteArrayRegion(args_jni, 0, length, reinterpret_cast(args)); \ + jniEnv->CallStaticIntMethod(clazz, method, id, args_jni, length); \ + jniEnv->GetByteArrayRegion(args_jni, 0, length, reinterpret_cast(args)); \ + jniEnv->PopLocalFrame(nullptr); \ +} + +#define KOALA_INTEROP_CALL_INT(venv, id, length, args) \ +{ \ + jclass clazz = nullptr; \ + jmethodID method = nullptr; \ + getKoalaJniCallbackDispatcher(&clazz, &method); \ + JNIEnv* jniEnv = reinterpret_cast(venv); \ + jniEnv->PushLocalFrame(1); \ + jbyteArray args_jni = jniEnv->NewByteArray(length); \ + jniEnv->SetByteArrayRegion(args_jni, 0, length, reinterpret_cast(args)); \ + int32_t rv = jniEnv->CallStaticIntMethod(clazz, method, id, args_jni, length); \ + jniEnv->GetByteArrayRegion(args_jni, 0, length, reinterpret_cast(args)); \ + jniEnv->PopLocalFrame(nullptr); \ + return rv; \ +} + +#define KOALA_INTEROP_CALL_VOID_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_VOID(venv, id, (argc) * sizeof(int32_t), args) +#define KOALA_INTEROP_CALL_INT_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_INT(venv, id, (argc) * sizeof(int32_t), args) + +#define KOALA_INTEROP_THROW(vmContext, object, ...) \ + do { \ + JNIEnv* env = reinterpret_cast(vmContext); \ + env->Throw(object); \ + return __VA_ARGS__; \ + } while (0) + +#define KOALA_INTEROP_THROW_STRING(vmContext, message, ...) \ + do { \ + JNIEnv* env = reinterpret_cast(vmContext); \ + const static jclass errorClass = env->FindClass("java/lang/RuntimeException"); \ + env->ThrowNew(errorClass, message); \ + } while (0) + +#endif // KOALA_JNI_CALL diff --git a/koala-wrapper/koalaui/interop/src/cpp/jsc/convertors-jsc.cc b/koala-wrapper/koalaui/interop/src/cpp/jsc/convertors-jsc.cc new file mode 100644 index 000000000..b1edbde65 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/jsc/convertors-jsc.cc @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2022-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 <_types/_uint32_t.h> +#include <_types/_uint8_t.h> +#include +#include + +#include "convertors-jsc.h" + +// See https://github.com/BabylonJS/BabylonNative/blob/master/Dependencies/napi/napi-direct/source/js_native_api_javascriptcore.cc +// for convertors logic. + + +KInt* getInt32Elements(JSContextRef context, const JSValueRef arguments) { + return getTypedElements(context, arguments); +} + +uint32_t* getUInt32Elements(JSContextRef context, const JSValueRef arguments) { + return getTypedElements(context, arguments); +} + +float* getFloat32Elements(JSContextRef context, const JSValueRef arguments) { + return getTypedElements(context, arguments); +} + +KByte* getByteElements(JSContextRef context, const JSValueRef arguments) { + return getTypedElements(context, arguments); +} + +KStringArray getKStringArray(JSContextRef context, const JSValueRef arguments) { + return getTypedElements(context, arguments); +} + +KUShort* getUShortElements(JSContextRef context, const JSValueRef arguments) { + return getTypedElements(context, arguments); +} + +KShort* getShortElements(JSContextRef context, const JSValueRef arguments) { + return getTypedElements(context, arguments); +} + +int32_t getInt32(JSContextRef context, JSValueRef value) { + JSValueRef exception {}; + if (JSValueIsNull(context, value)) { + return 0; + } + if (JSValueIsUndefined(context, value)) { + assert(false); + return 0; + } + double result = JSValueToNumber(context, value, &exception); + return static_cast(result); +} + +uint32_t getUInt32(JSContextRef context, JSValueRef value) { + JSValueRef exception {}; + if (JSValueIsNull(context, value)) { + return 0; + } + if (JSValueIsUndefined(context, value)) { + assert(false); + return 0; + } + double result = JSValueToNumber(context, value, &exception); + return static_cast(result); +} + +uint8_t getUInt8(JSContextRef context, JSValueRef value) { + JSValueRef exception {}; + if (JSValueIsNull(context, value)) { + return 0; + } + if (JSValueIsUndefined(context, value)) { + assert(false); + return 0; + } + double result = JSValueToNumber(context, value, &exception); + return static_cast(result); +} + +/* +static JSStringRef bigintToArrayCastFuncName = JSStringCreateWithUTF8CString("__JSC__castFromBigInt"); +static JSStringRef bigintToArrayCastFuncParams[] = { JSStringCreateWithUTF8CString("ptr") }; +static JSStringRef bigintToArrayCastFuncBody = JSStringCreateWithUTF8CString( + "return new Uint32Array([ptr & 0xFFFFFFFFn, (ptr >> 32n) & 0xFFFFFFFFn]);" +); + +static JSStringRef arrayToBigintCastFuncName = JSStringCreateWithUTF8CString("__JSC__castToBigInt"); +static JSStringRef arrayToBigintCastFuncParams[] = { JSStringCreateWithUTF8CString("ptr") }; +static JSStringRef arrayToBigintCastFuncBody = JSStringCreateWithUTF8CString( + "return BigInt(ptr[1]) << 32n | BigInt(ptr[0])" +); +*/ + +#ifdef KOALA_JSC_USE_CALLBACK_CAST + +static JSStringRef bigIntFromPartsFuncName = JSStringCreateWithUTF8CString("__JSC__bigIntFromParts"); +static JSStringRef bigIntFromPartsFuncParams[] = { JSStringCreateWithUTF8CString("hi"), JSStringCreateWithUTF8CString("lo") }; +static JSStringRef bigIntFromPartsFuncBody = JSStringCreateWithUTF8CString( + "return BigInt(hi) << 32n | BigInt(lo);" +); + +static JSObjectRef getGlobalCallback(JSContextRef context, JSStringRef name, JSStringRef params[], JSStringRef body) { + JSObjectRef globalThis = JSContextGetGlobalObject(context); + JSValueRef propname = JSValueMakeString(context, name); + JSValueRef castFunc = JSObjectGetPropertyForKey(context, globalThis, propname, nullptr); + if (JSValueIsUndefined(context, castFunc)) { + JSObjectRef castFuncObj = JSObjectMakeFunction(context, name, 1, params, body, nullptr, 0, nullptr); + JSPropertyAttributes attributes = kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum; + JSObjectSetPropertyForKey(context, globalThis, propname, castFuncObj, attributes, nullptr); + return castFuncObj; + } + return JSValueToObject(context, castFunc, nullptr); +} + +static JSObjectRef getBigIntFromParts(JSContextRef context) { + return getGlobalCallback(context, bigIntFromPartsFuncName, bigIntFromPartsFuncParams, bigIntFromPartsFuncBody); +} + +#endif + +static JSValueRef u64ToBigInt(JSContextRef context, uint64_t value) { + JSValueRef bigint; +#ifdef KOALA_JSC_USE_CALLBACK_CAST + // TODO benchmark this + JSObjectRef bigIntFromParts = getBigIntFromParts(context); + JSValueRef parts[2] = { + JSValueMakeNumber(context, (double) (value >> 32)), + JSValueMakeNumber(context, (double) (value & 0xFFFFFFFF)), + }; + bigint = JSObjectCallAsFunction(context, bigIntFromParts, nullptr, 2, parts, nullptr); +#else + char buffer[128] = {0}; + std::snprintf(buffer, sizeof(buffer) - 1, "%zun", (size_t) value); + JSStringRef script = JSStringCreateWithUTF8CString(buffer); + bigint = JSEvaluateScript(context, script, nullptr, nullptr, 0, nullptr); + JSStringRelease(script); +#endif + return bigint; +} + +static uint64_t bigIntToU64(JSContextRef ctx, JSValueRef value) { + char buf[128]; + JSStringRef strRef = JSValueToStringCopy(ctx, value, nullptr); + size_t len = JSStringGetUTF8CString(strRef, buf, sizeof(buf)); + JSStringRelease(strRef); + assert(len < sizeof(buf)); + char* suf; + uint64_t numValue = std::strtoull(buf, &suf, 10); + assert(*suf == '\0'); + return numValue; +} + +KNativePointer getPointer(JSContextRef context, JSValueRef value) { + uint64_t raw = bigIntToU64(context, value); + return reinterpret_cast(static_cast(raw)); +} + +KNativePointerArray getPointerElements(JSContextRef context, JSValueRef value) { + if (JSValueIsNull(context, value) || JSValueIsUndefined(context, value)) { + return nullptr; + } + + assert(JSValueIsObject(context, value)); + assert(JSValueGetTypedArrayType(context, value, nullptr) == kJSTypedArrayTypeBigUint64Array); + + JSObjectRef typedArray = JSValueToObject(context, value, nullptr); + return reinterpret_cast(JSObjectGetTypedArrayBytesPtr(context, typedArray, nullptr)); +} + +KFloat getFloat(JSContextRef context, JSValueRef value) { + JSValueRef exception {}; + if (JSValueIsNull(context, value)) { + return 0; + } + if (JSValueIsUndefined(context, value)) { + assert(false); + return 0; + } + double result = JSValueToNumber(context, value, &exception); + return static_cast(result); +} + +KShort getShort(JSContextRef context, JSValueRef value) { + JSValueRef exception {}; + if (JSValueIsNull(context, value)) { + return 0; + } + if (JSValueIsUndefined(context, value)) { + assert(false); + return 0; + } + double result = JSValueToNumber(context, value, &exception); + return static_cast(result); +} + +KUShort getUShort(JSContextRef context, JSValueRef value) { + JSValueRef exception {}; + if (JSValueIsNull(context, value)) { + return 0; + } + if (JSValueIsUndefined(context, value)) { + assert(false); + return 0; + } + double result = JSValueToNumber(context, value, &exception); + return static_cast(result); +} + +KStringPtr getString(JSContextRef context, JSValueRef value) { + if (JSValueIsNull(context, value)) { + return KStringPtr(); + } + if (JSValueIsUndefined(context, value)) { + return KStringPtr(); + } + KStringPtr result; + JSStringRef valueString = JSValueToStringCopy(context, value, NULL); + size_t size = JSStringGetMaximumUTF8CStringSize(valueString); + result.resize(size); + JSStringGetUTF8CString(valueString, result.data(), size); + JSStringRelease(valueString); + return result; +} + +KBoolean getBoolean(JSContextRef context, JSValueRef value) { + bool result = JSValueToBoolean(context, value); + return static_cast(result); +} + +JSValueRef makeInt32(JSContextRef context, int32_t value) { + return JSValueMakeNumber(context, value); +} + +JSValueRef makeUInt32(JSContextRef context, uint32_t value) { + return JSValueMakeNumber(context, value); +} + +JSValueRef makePointer(JSContextRef context, KNativePointer value) { + return u64ToBigInt(context, static_cast(reinterpret_cast(value))); +} + +JSValueRef makeFloat(JSContextRef context, KFloat value) { + return JSValueMakeNumber(context, value); +} + +JSValueRef makeBoolean(JSContextRef context, KBoolean value) { + return JSValueMakeBoolean(context, value); +} + +JSValueRef makeVoid(JSContextRef context) { + return JSValueMakeUndefined(context); +} + +Exports* Exports::getInstance() { + static Exports *instance = nullptr; + if (instance == nullptr) { + instance = new Exports(); + } + return instance; +} + +void InitExports(JSGlobalContextRef globalContext) { + JSObjectRef globalObject = JSContextGetGlobalObject(globalContext); + for (auto impl: Exports::getInstance()->getImpls()) { + JSStringRef functionName = JSStringCreateWithUTF8CString(impl.first.c_str()); + JSObjectRef functionObject = JSObjectMakeFunctionWithCallback(globalContext, functionName, impl.second); + JSObjectSetProperty(globalContext, globalObject, functionName, functionObject, kJSPropertyAttributeNone, nullptr); + JSStringRelease(functionName); + } +} diff --git a/koala-wrapper/koalaui/interop/src/cpp/jsc/convertors-jsc.h b/koala-wrapper/koalaui/interop/src/cpp/jsc/convertors-jsc.h new file mode 100644 index 000000000..b100dff7d --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/jsc/convertors-jsc.h @@ -0,0 +1,722 @@ +/* + * Copyright (c) 2022-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. + */ + +#pragma once + +#if defined(linux) +#include // For IDE completion +#else +#include +#endif +#include <_types/_uint8_t.h> +#include +#include +#include + +#include + +#include "koala-types.h" + +template +inline ElemType* getTypedElements(JSContextRef context, const JSValueRef arguments) { + if (JSValueIsNull(context, arguments)) { + return nullptr; + } + if (JSValueIsUndefined(context, arguments)) { + assert(false); + return nullptr; + } + JSValueRef exception {}; + ElemType* data = reinterpret_cast(JSObjectGetTypedArrayBytesPtr(context, + JSValueToObject(context, arguments, &exception), &exception)); + return data; +} + +template +inline ElemType* getTypedElements(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getTypedElements(context, arguments[index]); +} + +uint8_t* getUInt8Elements(JSContextRef context, const JSValueRef arguments); +int32_t* getInt32Elements(JSContextRef context, const JSValueRef arguments); +uint32_t* getUInt32Elements(JSContextRef context, const JSValueRef arguments); +float* getFloat32Elements(JSContextRef context, const JSValueRef arguments); +KByte* getByteElements(JSContextRef context, const JSValueRef arguments); +KUShort* getUShortElements(JSContextRef context, const JSValueRef arguments); +KShort* getShortElements(JSContextRef context, const JSValueRef arguments); +KNativePointerArray getPointerElements(JSContextRef context, const JSValueRef arguments); +KStringArray getKStringArray(JSContextRef context, const JSValueRef arguments); + +uint8_t getUInt8(JSContextRef context, JSValueRef value); +int32_t getInt32(JSContextRef context, JSValueRef value); +uint32_t getUInt32(JSContextRef context, JSValueRef value); +KNativePointer getPointer(JSContextRef context, JSValueRef value); +KFloat getFloat(JSContextRef context, JSValueRef value); +KStringPtr getString(JSContextRef context, JSValueRef value); +KBoolean getBoolean(JSContextRef context, JSValueRef value); +KStringPtr getString(JSContextRef context, JSValueRef value); + +template +inline Type getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) = delete; + +template <> +inline int32_t getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getInt32(context, arguments[index]); +} + +template <> +inline uint32_t getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getUInt32(context, arguments[index]); +} + +template <> +inline uint8_t getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getUInt8(context, arguments[index]); +} + +template <> +inline KNativePointer getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getPointer(context, arguments[index]); +} + +template <> +inline KFloat getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getFloat(context, arguments[index]); +} + +template <> +inline KStringPtr getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getString(context, arguments[index]); +} + +template <> +inline KBoolean getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getBoolean(context, arguments[index]); +} + +template <> +inline KInt* getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getInt32Elements(context, arguments[index]); +} + +template <> +inline float* getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getFloat32Elements(context, arguments[index]); +} + +template <> +inline KByte* getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getByteElements(context, arguments[index]); +} + +template <> +inline KStringArray getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getKStringArray(context, arguments[index]); +} + +template <> +inline KUShort* getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getUShortElements(context, arguments[index]); +} + +template <> +inline KNativePointerArray getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getPointerElements(context, arguments[index]); +} + +template <> +inline KShort* getArgument(JSContextRef context, size_t argumentCount, const JSValueRef arguments[], int index) { + assert(index < argumentCount); + return getShortElements(context, arguments[index]); +} + +JSValueRef makeInt32(JSContextRef context, int32_t value); +JSValueRef makeUInt32(JSContextRef context, uint32_t value); +JSValueRef makePointer(JSContextRef context, KNativePointer value); +JSValueRef makeFloat(JSContextRef context, KFloat value); +JSValueRef makeBoolean(JSContextRef context, KBoolean value); +JSValueRef makeVoid(JSContextRef context); + +template +inline JSValueRef makeResult(JSContextRef context, Type value) = delete; + +template <> +inline JSValueRef makeResult(JSContextRef context, int32_t value) { + return makeInt32(context, value); +} + +template <> +inline JSValueRef makeResult(JSContextRef context, uint32_t value) { + return makeUInt32(context, value); +} + +template <> +inline JSValueRef makeResult(JSContextRef context, KNativePointer value) { + return makePointer(context, value); +} + +template <> +inline JSValueRef makeResult(JSContextRef context, KFloat value) { + return makeFloat(context, value); +} + +template <> +inline JSValueRef makeResult(JSContextRef context, KBoolean value) { + return makeBoolean(context, value); +} + +typedef JSValueRef (*jsc_type_t)(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +class Exports { + std::vector> implementations; + +public: + static Exports* getInstance(); + + void addImpl(const char* name, jsc_type_t impl) { + implementations.push_back(std::make_pair(name, impl)); + } + + const std::vector>& getImpls() { + return implementations; + } +}; + +void InitExports(JSGlobalContextRef globalContext); + +#define MAKE_JSC_EXPORT(name) \ + __attribute__((constructor)) \ + static void __init_##name() { \ + Exports::getInstance()->addImpl("_"#name, Jsc_##name); \ + } + +#define MAKE_JSC_EXPORT_V1(name) \ + __attribute__((constructor)) \ + static void __init_##name() { \ + Exports::getInstance()->addImpl(#name, Jsc_##name); \ + } + +#define KOALA_INTEROP_0(name, Ret) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + return makeResult(ctx, impl_##name()); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_1(name, Ret, P0) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + return makeResult(ctx, impl_##name(p0)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_2(name, Ret, P0, P1) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + return makeResult(ctx, impl_##name(p0, p1)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_3(name, Ret, P0, P1, P2) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + return makeResult(ctx, impl_##name(p0,p1,p2)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_4(name, Ret, P0, P1, P2, P3) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_5(name, Ret, P0, P1, P2, P3, P4) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_6(name, Ret, P0, P1, P2, P3, P4, P5) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_7(name, Ret, P0, P1, P2, P3, P4, P5, P6) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5,p6)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_8(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5,p6,p7)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_9(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_10(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_11(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + P10 p10 = getArgument(ctx, argumentCount, arguments, 10); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_12(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + P10 p10 = getArgument(ctx, argumentCount, arguments, 10); \ + P11 p11 = getArgument(ctx, argumentCount, arguments, 11); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_13(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + P10 p10 = getArgument(ctx, argumentCount, arguments, 10); \ + P11 p11 = getArgument(ctx, argumentCount, arguments, 11); \ + P12 p12 = getArgument(ctx, argumentCount, arguments, 12); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_14(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + P10 p10 = getArgument(ctx, argumentCount, arguments, 10); \ + P11 p11 = getArgument(ctx, argumentCount, arguments, 11); \ + P12 p12 = getArgument(ctx, argumentCount, arguments, 12); \ + P13 p13 = getArgument(ctx, argumentCount, arguments, 13); \ + return makeResult(ctx, impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V0(name) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + impl_##name(); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V1(name, P0) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + impl_##name(p0); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V2(name, P0, P1) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + impl_##name(p0,p1); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V3(name, P0, P1, P2) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + impl_##name(p0,p1,p2); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V4(name, P0, P1, P2, P3) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + impl_##name(p0,p1,p2,p3); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V5(name, P0, P1, P2, P3, P4) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + impl_##name(p0,p1,p2,p3,p4); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V6(name, P0, P1, P2, P3, P4, P5) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + impl_##name(p0,p1,p2,p3,p4,p5); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V7(name, P0, P1, P2, P3, P4, P5, P6) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + impl_##name(p0,p1,p2,p3,p4,p5,p6); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V8(name, P0, P1, P2, P3, P4, P5, P6, P7) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + impl_##name(p0,p1,p2,p3,p4,p5,p6,p7); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V9(name, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V10(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V11(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + P10 p10 = getArgument(ctx, argumentCount, arguments, 10); \ + impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V12(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + P10 p10 = getArgument(ctx, argumentCount, arguments, 10); \ + P11 p11 = getArgument(ctx, argumentCount, arguments, 11); \ + impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V13(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + P10 p10 = getArgument(ctx, argumentCount, arguments, 10); \ + P11 p11 = getArgument(ctx, argumentCount, arguments, 11); \ + P12 p12 = getArgument(ctx, argumentCount, arguments, 12); \ + impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_V14(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + P4 p4 = getArgument(ctx, argumentCount, arguments, 4); \ + P5 p5 = getArgument(ctx, argumentCount, arguments, 5); \ + P6 p6 = getArgument(ctx, argumentCount, arguments, 6); \ + P7 p7 = getArgument(ctx, argumentCount, arguments, 7); \ + P8 p8 = getArgument(ctx, argumentCount, arguments, 8); \ + P9 p9 = getArgument(ctx, argumentCount, arguments, 9); \ + P10 p10 = getArgument(ctx, argumentCount, arguments, 10); \ + P11 p11 = getArgument(ctx, argumentCount, arguments, 11); \ + P12 p12 = getArgument(ctx, argumentCount, arguments, 12); \ + P13 p13 = getArgument(ctx, argumentCount, arguments, 13); \ + impl_##name(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +// todo: implement properly +#define KOALA_INTEROP_CTX_3(name, Ret, P0, P1, P2) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) \ + { \ + printf("TODO: implement KOALA_INTEROP_CTX_3 for jsc"); \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + return makeResult(ctx, impl_##name(nullptr, p0, p1, p2)); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_CTX_4(name, Ret, P0, P1, P2, P4) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) \ + { \ + printf("TODO: implement KOALA_INTEROP_CTX_4 for jsc"); \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + return makeResult(ctx, impl_##name(nullptr, p0, p1, p2, p3)); \ + } \ + MAKE_JSC_EXPORT(name) + +// todo: implement properly +#define KOALA_INTEROP_CTX_V3(name, P0, P1, P2) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + printf("TODO: implement KOALA_INTEROP_CTX_V3 for jsc"); \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + impl_##name(nullptr, p0, p1, p2); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_CTX_V4(name, P0, P1, P2, P3) \ + JSValueRef Jsc_##name(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { \ + printf("TODO: implement KOALA_INTEROP_CTX_V4 for jsc"); \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(ctx, argumentCount, arguments, 0); \ + P1 p1 = getArgument(ctx, argumentCount, arguments, 1); \ + P2 p2 = getArgument(ctx, argumentCount, arguments, 2); \ + P3 p3 = getArgument(ctx, argumentCount, arguments, 3); \ + impl_##name(nullptr, p0, p1, p2, p3); \ + return makeVoid(ctx); \ + } \ + MAKE_JSC_EXPORT(name) + +#define KOALA_INTEROP_THROW(vmContext, object, ...) \ + do { \ + /* TODO: implement*/ assert(false); \ + return __VA_ARGS__; \ + } while (0) + +#define KOALA_INTEROP_THROW_STRING(vmContext, message, ...) \ + do { \ + assert(false); /* TODO: implement*/ \ + return __VA_ARGS__; \ + } while (0) diff --git a/koala-wrapper/koalaui/interop/src/cpp/napi/convertors-napi.cc b/koala-wrapper/koalaui/interop/src/cpp/napi/convertors-napi.cc new file mode 100644 index 000000000..1bb1fc9b5 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/napi/convertors-napi.cc @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2022-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 + +#include "interop-logging.h" + +#ifdef KOALA_INTEROP_MODULE +#undef KOALA_INTEROP_MODULE +#endif +#define KOALA_INTEROP_MODULE InteropNativeModule +#include "convertors-napi.h" + + +// Adapter for NAPI_MODULE +#define NODE_API_MODULE_ADAPTER(modname, regfunc) \ + static napi_value __napi_##regfunc(napi_env env, napi_value exports) { \ + return Napi::RegisterModule(env, exports, regfunc); \ + } \ + NAPI_MODULE(modname, __napi_##regfunc) + +napi_valuetype getValueTypeChecked(napi_env env, napi_value value) { + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + KOALA_NAPI_THROW_IF_FAILED(env, status, napi_undefined); + return type; +} + +bool isTypedArray(napi_env env, napi_value value) { + bool result = false; + napi_status status = napi_is_typedarray(env, value, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, false); + return result; +} + +KBoolean getBoolean(napi_env env, napi_value value) { + if (getValueTypeChecked(env, value) == napi_valuetype::napi_boolean) { + bool result = false; + napi_get_value_bool(env, value, &result); + return static_cast(result); + } + return static_cast(getInt32(env, value) != 0); +} + +KInt getInt32(napi_env env, napi_value value) { + if (getValueTypeChecked(env, value) != napi_valuetype::napi_number) { + napi_throw_error(env, nullptr, "Expected Number"); + return 0; + } + int32_t result = false; + napi_get_value_int32(env, value, &result); + return static_cast(result); +} + +KUInt getUInt32(napi_env env, napi_value value) { + if (getValueTypeChecked(env, value) != napi_valuetype::napi_number) { + napi_throw_error(env, nullptr, "Expected Number"); + return 0; + } + uint32_t result = false; + napi_get_value_uint32(env, value, &result); + return static_cast(result); +} + +KFloat getFloat32(napi_env env, napi_value value) { + if (getValueTypeChecked(env, value) != napi_valuetype::napi_number) { + napi_throw_error(env, nullptr, "Expected Number"); + return 0.0f; + } + double result = false; + napi_get_value_double(env, value, &result); + return static_cast(static_cast(result)); +} + +KDouble getFloat64(napi_env env, napi_value value) { + if (getValueTypeChecked(env, value) != napi_valuetype::napi_number) { + napi_throw_error(env, nullptr, "Expected Number"); + return 0.0; + } + double result = false; + napi_get_value_double(env, value, &result); + return static_cast(result); +} + +KStringPtr getString(napi_env env, napi_value value) { + KStringPtr result {}; + napi_valuetype valueType = getValueTypeChecked(env, value); + if (valueType == napi_valuetype::napi_null || valueType == napi_valuetype::napi_undefined) { + return result; + } + + if (valueType != napi_valuetype::napi_string) { + napi_throw_error(env, nullptr, "Expected String"); + return result; + } + + size_t length = 0; + napi_status status = napi_get_value_string_utf8(env, value, nullptr, 0, &length); + if (status != 0) return result; + result.resize(length); + status = napi_get_value_string_utf8(env, value, result.data(), length + 1, nullptr); + return result; +} + +KNativePointer getPointer(napi_env env, napi_value value) { + napi_valuetype valueType = getValueTypeChecked(env, value); + if (valueType == napi_valuetype::napi_external) { + KNativePointer result = nullptr; + napi_status status = napi_get_value_external(env, value, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, nullptr); + return result; + } + + if (valueType != napi_valuetype::napi_bigint) { + napi_throw_error(env, nullptr, "cannot be coerced to pointer"); + return nullptr; + } + + bool isWithinRange = true; + uint64_t ptrU64 = 0; + napi_status status = napi_get_value_bigint_uint64(env, value, &ptrU64, &isWithinRange); + KOALA_NAPI_THROW_IF_FAILED(env, status, nullptr); + if (!isWithinRange) { + napi_throw_error(env, nullptr, "cannot be coerced to uint64, value is too large"); + return nullptr; + } + return reinterpret_cast(ptrU64); +} + +KLong getInt64(napi_env env, napi_value value) { + if (getValueTypeChecked(env, value) != napi_valuetype::napi_bigint) { + napi_throw_error(env, nullptr, "cannot be coerced to int64"); + return -1; + } + + bool isWithinRange = true; + int64_t ptr64 = 0; + napi_get_value_bigint_int64(env, value, &ptr64, &isWithinRange); + if (!isWithinRange) { + napi_throw_error(env, nullptr, "cannot be coerced to int64, value is too large"); + return -1; + } + return static_cast(ptr64); +} + +KULong getUInt64(napi_env env, napi_value value) { + if (getValueTypeChecked(env, value) != napi_valuetype::napi_bigint) { + napi_throw_error(env, nullptr, "cannot be coerced to uint64"); + return -1; + } + + bool isWithinRange = true; + uint64_t ptr64 = 0; + napi_get_value_bigint_uint64(env, value, &ptr64, &isWithinRange); + if (!isWithinRange) { + napi_throw_error(env, nullptr, "cannot be coerced to uint64, value is too large"); + return -1; + } + return static_cast(ptr64); +} + +napi_value makeString(napi_env env, const KStringPtr& value) { + napi_value result; + napi_status status; + status = napi_create_string_utf8(env, value.isNull() ? "" : value.data(), value.length(), &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeString(napi_env env, const std::string& value) { + napi_value result; + napi_status status; + status = napi_create_string_utf8(env, value.c_str(), value.length(), &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeBoolean(napi_env env, int8_t value) { + napi_value result; + napi_status status; + status = napi_get_boolean(env, value != 0, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeInt32(napi_env env, int32_t value) { + napi_value result; + napi_status status; + status = napi_create_int32(env, value, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeUInt32(napi_env env, uint32_t value) { + napi_value result; + napi_status status; + status = napi_create_uint32(env, value, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeInt64(napi_env env, int64_t value) { + napi_value result; + napi_status status; + status = napi_create_bigint_int64(env, value, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeUInt64(napi_env env, uint64_t value) { + napi_value result; + napi_status status; + status = napi_create_bigint_uint64(env, value, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeFloat32(napi_env env, float value) { + napi_value result; + napi_status status; + status = napi_create_double(env, value, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makePointer(napi_env env, void* value) { + napi_value result; + napi_status status; + status = napi_create_bigint_uint64(env, static_cast(reinterpret_cast(value)), &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeVoid(napi_env env) { + napi_value result; + napi_status status; + status = napi_get_undefined(env, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +napi_value makeObject(napi_env env, napi_value object) { + napi_value result; + napi_status status; + status = napi_create_object(env, &result); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + return result; +} + +#if _MSC_VER >= 1932 // Visual Studio 2022 version 17.2+ +# pragma comment(linker, "/alternatename:__imp___std_init_once_complete=__imp_InitOnceComplete") +# pragma comment(linker, "/alternatename:__imp___std_init_once_begin_initialize=__imp_InitOnceBeginInitialize") +#endif + +Exports* Exports::getInstance() { + static Exports *instance = nullptr; + if (instance == nullptr) { + instance = new Exports(); + } + return instance; +} + +std::vector Exports::getModules() { + std::vector result; + for (auto it = implementations.begin(); it != implementations.end(); ++it) { + result.push_back(it->first); + } + return result; +} + +void Exports::addMethod(const char* module, const char* name, napi_type_t impl) { + auto it = implementations.find(module); + if (it == implementations.end()) { + it = implementations.insert(std::make_pair(module, std::vector>())).first; + } + it->second.push_back(std::make_pair(name, impl)); + +} + +const std::vector>& Exports::getMethods(const std::string& module) { + auto it = implementations.find(module); + if (it == implementations.end()) { + LOGE("Module %s is not registered", module.c_str()); + INTEROP_FATAL("Fatal error"); + } + return it->second; +} + +// +// Callback dispatcher +// +// TODO Should we get rid of explicit Node_* declrations and hide the naming convention behind the macro definitions? + +static napi_ref g_koalaNapiCallbackDispatcher = nullptr; + +// TODO: shall we pass name in globalThis instead of object reference? +napi_value Node_SetCallbackDispatcher(napi_env env, napi_callback_info cbinfo) { + fprintf(stderr, "Node_SetCallbackDispatcher!\n"); + + CallbackInfo info(env, cbinfo); + napi_value dispatcher = info[0]; + napi_value result = makeVoid(env); + napi_status status = napi_create_reference(env, dispatcher, 1, &g_koalaNapiCallbackDispatcher); + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + + return result; +} +MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, SetCallbackDispatcher) + +napi_value Node_CleanCallbackDispatcher(napi_env env, napi_callback_info cbinfo) { + napi_value result = makeVoid(env); + if (g_koalaNapiCallbackDispatcher) { + napi_status status = napi_delete_reference(env, g_koalaNapiCallbackDispatcher); + g_koalaNapiCallbackDispatcher = nullptr; + KOALA_NAPI_THROW_IF_FAILED(env, status, result); + } + return result; +} +MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, CleanCallbackDispatcher) + +napi_value getKoalaNapiCallbackDispatcher(napi_env env) { + if (!g_koalaNapiCallbackDispatcher) { + abort(); + } + napi_value value; + napi_status status = napi_get_reference_value(env, g_koalaNapiCallbackDispatcher, &value); + KOALA_NAPI_THROW_IF_FAILED(env, status, makeVoid(env)); + return value; +} + +// +// Module initialization +// + +using ModuleRegisterCallback = napi_value (*)(napi_env env, napi_value exports); + +/** + * Sets a new callback and returns its previous value. + */ +ModuleRegisterCallback ProvideModuleRegisterCallback(ModuleRegisterCallback value = nullptr) { + static const ModuleRegisterCallback DEFAULT_CB = [](napi_env env, napi_value exports) { return exports; }; + static ModuleRegisterCallback curCallback = DEFAULT_CB; + + ModuleRegisterCallback prevCallback = curCallback; + curCallback = value ? value : DEFAULT_CB; + return prevCallback; +} + +static constexpr bool splitModules = true; + +static napi_value InitModule(napi_env env, napi_value exports) { + LOG("InitModule: " QUOTE(INTEROP_LIBRARY_NAME) "\n"); + Exports* inst = Exports::getInstance(); + napi_status status; + napi_value target = exports; + for (const auto &module : inst->getModules()) { + if (splitModules) { + status = napi_create_object(env, &target); + KOALA_NAPI_THROW_IF_FAILED(env, status, exports); + status = napi_set_named_property(env, exports, module.c_str(), target); + KOALA_NAPI_THROW_IF_FAILED(env, status, exports); + } + + for (const auto &impl : inst->getMethods(module)) { + napi_value implFunc; + status = napi_create_function(env, impl.first.c_str(), NAPI_AUTO_LENGTH, impl.second, nullptr, &implFunc); + KOALA_NAPI_THROW_IF_FAILED(env, status, exports); + status = napi_set_named_property(env, target, impl.first.c_str(), implFunc); + KOALA_NAPI_THROW_IF_FAILED(env, status, exports); + } + } + return ProvideModuleRegisterCallback()(env, exports); +} + +NAPI_MODULE(INTEROP_LIBRARY_NAME, InitModule) diff --git a/koala-wrapper/koalaui/interop/src/cpp/napi/convertors-napi.h b/koala-wrapper/koalaui/interop/src/cpp/napi/convertors-napi.h new file mode 100644 index 000000000..720d423f1 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/napi/convertors-napi.h @@ -0,0 +1,1374 @@ +/* + * Copyright (c) 2022-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 _CONVERTORS_NAPI_H_ +#define _CONVERTORS_NAPI_H_ + +#ifdef KOALA_NAPI + +#include +#include +#include + +#ifndef KOALA_NAPI_OHOS +#include +#else +#include +#include +#endif +#include "koala-types.h" +#include "interop-types.h" + +// TODO: switch to more generic convertors eventually. +template +struct InteropTypeConverter { + using InteropType = T; + static T convertFrom(napi_env env, InteropType value) { return value; } + static InteropType convertTo(napi_env env, T value) { return value; } + static void release(napi_env env, InteropType value, T converted) {} +}; + +template +inline typename InteropTypeConverter::InteropType makeResult(napi_env env, Type value) { + return InteropTypeConverter::convertTo(env, value); +} + +template +inline Type getArgument(napi_env env, typename InteropTypeConverter::InteropType arg) { + return InteropTypeConverter::convertFrom(env, arg); +} + +template +inline void releaseArgument(napi_env env, typename InteropTypeConverter::InteropType arg, Type data) { + InteropTypeConverter::release(env, arg, data); +} + +template<> +struct InteropTypeConverter { + using InteropType = napi_value; + static KInteropBuffer convertFrom(napi_env env, InteropType value) { + KInteropBuffer result = { 0 }; + bool isArrayBuffer = false; + napi_is_arraybuffer(env, value, &isArrayBuffer); + if (isArrayBuffer) { + napi_get_arraybuffer_info(env, value, &result.data, (size_t*)&result.length); + } else { + bool isDataView = false; + napi_is_dataview(env, value, &isDataView); + if (isDataView) { + napi_get_dataview_info(env, value, (size_t*)&result.length, &result.data, nullptr, nullptr); + } + } + return result; + } + static InteropType convertTo(napi_env env, KInteropBuffer value) { + KInteropBuffer* copy = new KInteropBuffer(value); + napi_value result; + napi_status status = napi_create_external_arraybuffer( + env, + value.data, + value.length, + [](napi_env env, void* finalize_data, void* finalize_hint) { + KInteropBuffer* buffer = reinterpret_cast(finalize_hint); + buffer->dispose(buffer->resourceId); + delete buffer; + }, + (void*)copy, + &result + ); + if (status != napi_ok) { + // do smth here + } + return result; + }; + static void release(napi_env env, InteropType value, KInteropBuffer converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = napi_value; + static KStringPtr convertFrom(napi_env env, InteropType value) { + if (value == nullptr) return KStringPtr(); + KStringPtr result; + size_t length = 0; + napi_status status = napi_get_value_string_utf8(env, value, nullptr, 0, &length); + if (status != 0) return result; + result.resize(length); + status = napi_get_value_string_utf8(env, value, result.data(), length + 1, nullptr); + return result; + } + static InteropType convertTo(napi_env env, const KStringPtr& value) { + napi_value result; + napi_create_string_utf8(env, value.c_str(), value.length(), &result); + return result; + } + static void release(napi_env env, InteropType value, const KStringPtr& converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = napi_value; + static KInteropNumber convertFrom(napi_env env, InteropType interopValue) { + double value = 0.0; + napi_get_value_double(env, interopValue, &value); + return KInteropNumber::fromDouble(value); + } + static InteropType convertTo(napi_env env, KInteropNumber value) { + napi_value result; + napi_create_double(env, value.asDouble(), &result); + return result; + } + static void release(napi_env env, InteropType value, KInteropNumber converted) {} +}; + +template<> +struct InteropTypeConverter { + using InteropType = napi_value; + static inline KVMObjectHandle convertFrom(napi_env env, InteropType value) { + return reinterpret_cast(value); + } + static InteropType convertTo(napi_env env, KVMObjectHandle value) { + return reinterpret_cast(value); + } + static inline void release(napi_env env, InteropType value, KVMObjectHandle converted) { + } +}; + +template<> +struct InteropTypeConverter { + using InteropType = napi_value; + static inline KInteropReturnBuffer convertFrom(napi_env env, InteropType value) = delete; + static void disposer(napi_env env, void* data, void* hint) { + KInteropReturnBuffer* bufferCopy = (KInteropReturnBuffer*)hint; + bufferCopy->dispose(bufferCopy->data, bufferCopy->length); + delete bufferCopy; + } + static InteropType convertTo(napi_env env, KInteropReturnBuffer value) { + napi_value result = nullptr; + napi_value arrayBuffer = nullptr; + auto clone = new KInteropReturnBuffer(); + *clone = value; + napi_create_external_arraybuffer(env, value.data, value.length, disposer, clone, &arrayBuffer); + napi_create_typedarray(env, napi_uint8_array, value.length, arrayBuffer, 0, &result); + return result; + } + static inline void release(napi_env env, InteropType value, const KInteropReturnBuffer& converted) = delete; +}; + + +#define KOALA_INTEROP_THROW(vmcontext, object, ...) \ + do { \ + napi_env env = (napi_env)vmcontext; \ + napi_handle_scope scope = nullptr; \ + napi_open_handle_scope(env, &scope); \ + napi_throw((napi_env)vmcontext, object); \ + napi_close_handle_scope(env, scope); \ + return __VA_ARGS__; \ + } while (0) + +#define KOALA_INTEROP_THROW_STRING(vmContext, message, ...) \ + do { \ + napi_value value; \ + napi_create_string_utf8((napi_env)vmContext, message, strlen(message), &value); \ + KOALA_INTEROP_THROW(vmContext, value, __VA_ARGS__); \ + } while (0) + +#define NAPI_ASSERT_INDEX(info, index, result) \ + do { \ + if (static_cast(index) >= info.Length()) { \ + napi_throw_error(info.Env(), nullptr, "No such element");\ + return result; \ + } \ + } while (0) + +// Helpers from node-addon-api +#define KOALA_NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) { \ + const napi_extended_error_info* errorInfo; \ + napi_get_last_error_info(env, &errorInfo); \ + napi_throw_error(env, nullptr, errorInfo->error_message); \ + return __VA_ARGS__; \ + } +#define KOALA_NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) { \ + const napi_extended_error_info* errorInfo; \ + napi_get_last_error_info(env, &errorInfo); \ + napi_throw_error(env, nullptr, errorInfo->error_message); \ + return; \ + } + +class CallbackInfo { +public: + CallbackInfo(napi_env env, napi_callback_info info) : _env(env) { + size_t size = 0; + napi_status status; + status = napi_get_cb_info(env, info, &size, nullptr, nullptr, nullptr); + KOALA_NAPI_THROW_IF_FAILED_VOID(env, status); + if (size > 0) { + args.resize(size); // TODO statically allocate small array for common case with few arguments passed + status = napi_get_cb_info(env, info, &size, args.data(), nullptr, nullptr); + KOALA_NAPI_THROW_IF_FAILED_VOID(env, status); + } + } + + napi_value operator[](size_t idx) const { + if (idx >= Length()) { + napi_value result; + napi_get_undefined(_env, &result); + return result; + } + return args[idx]; + } + + napi_env Env() const { + return _env; + } + + size_t Length() const { + return args.size(); + } +private: + napi_env _env; + // napi_callback_info _info; + std::vector args; +}; + +template +inline napi_typedarray_type getNapiType() = delete; + +template <> +inline napi_typedarray_type getNapiType() { + return napi_float32_array; +} + +template <> +inline napi_typedarray_type getNapiType() { + return napi_int8_array; +} + +template <> +inline napi_typedarray_type getNapiType() { + return napi_uint8_array; +} + +template <> +inline napi_typedarray_type getNapiType() { + return napi_int16_array; +} + +template <> +inline napi_typedarray_type getNapiType() { + return napi_uint16_array; +} + +template <> +inline napi_typedarray_type getNapiType() { + return napi_int32_array; +} + +template <> +inline napi_typedarray_type getNapiType() { + return napi_uint32_array; +} + +template <> +inline napi_typedarray_type getNapiType() { + return napi_biguint64_array; +} + +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) { + napi_valuetype valueType = getValueTypeChecked(env, value); + if (valueType == napi_null) { + return nullptr; + } + if (!isTypedArray(env, value)) { + napi_throw_error(env, nullptr, "Expected TypedArray"); + return nullptr; + } + 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); + KOALA_NAPI_THROW_IF_FAILED(env, status, nullptr); + if (type != getNapiType()) { + printf("Array type mismatch. Expected %d got %d\n", getNapiType(), type); + napi_throw_error(env, nullptr, "Array type mismatch"); + return nullptr; + } + return reinterpret_cast(data); +} + +template +inline ElemType* getTypedElements(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, nullptr); + return getTypedElements(info.Env(), info[index]); +} + +inline uint8_t* getUInt8Elements(const CallbackInfo& info, int index) { + return getTypedElements(info, index); +} + +inline int8_t* getInt8Elements(const CallbackInfo& info, int index) { + return getTypedElements(info, index); +} + +inline uint16_t* getUInt16Elements(const CallbackInfo& info, int index) { + return getTypedElements(info, index); +} + +inline int16_t* getInt16Elements(const CallbackInfo& info, int index) { + return getTypedElements(info, index); +} + +inline uint32_t* getUInt32Elements(const CallbackInfo& info, int index) { + return getTypedElements(info, index); +} + +inline uint32_t* getUInt32Elements(napi_env env, napi_value value) { + return getTypedElements(env, value); +} + +inline int32_t* getInt32Elements(const CallbackInfo& info, int index) { + return getTypedElements(info, index); +} + +inline float* getFloat32Elements(const CallbackInfo& info, int index) { + return getTypedElements(info, index); +} + +inline KNativePointer* getPointerElements(const CallbackInfo& info, int index) { + return getTypedElements(info, index); +} + +KInt getInt32(napi_env env, napi_value value); +inline int32_t getInt32(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, 0); + return getInt32(info.Env(), info[index]); +} +KUInt getUInt32(napi_env env, napi_value value); +inline uint32_t getUInt32(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, 0); + return getUInt32(info.Env(), info[index]); +} +KFloat getFloat32(napi_env env, napi_value value); +inline float getFloat32(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, 0.0f); + return getFloat32(info.Env(), info[index]); +} +KDouble getFloat64(napi_env env, napi_value value); +inline KDouble getFloat64(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, 0.0); + return getFloat64(info.Env(), info[index]); +} +KStringPtr getString(napi_env env, napi_value value); +inline KStringPtr getString(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, KStringPtr()); + return getString(info.Env(), info[index]); +} +void* getPointer(napi_env env, napi_value value); +inline void* getPointer(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, nullptr); + return getPointer(info.Env(), info[index]); +} +KULong getUInt64(napi_env env, napi_value value); +inline KULong getUInt64(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, 0); + return getUInt64(info.Env(), info[index]); +} +KLong getInt64(napi_env env, napi_value value); +inline KLong getInt64(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, 0); + return getInt64(info.Env(), info[index]); +} +KBoolean getBoolean(napi_env env, napi_value value); +inline KBoolean getBoolean(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, false); + return getBoolean(info.Env(), info[index]); +} + +template +inline Type getArgument(const CallbackInfo& info, int index) = delete; + +template <> +inline KBoolean getArgument(const CallbackInfo& info, int index) { + return getBoolean(info, index); +} + +template <> +inline KUInt getArgument(const CallbackInfo& info, int index) { + return getUInt32(info, index); +} + +template <> +inline KInt getArgument(const CallbackInfo& info, int index) { + return getInt32(info, index); +} + +template <> +inline KInteropNumber getArgument(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, { 0 }); + return getArgument(info.Env(), info[index]); +} + +template <> +inline KLength getArgument(const CallbackInfo& info, int index) { + KLength result = { 0 }; + NAPI_ASSERT_INDEX(info, index, result); + auto value = info[index]; + napi_valuetype type; + auto status = napi_typeof(info.Env(), value, &type); + if (status != 0) return result; + switch (type) { + case napi_number: { + result.value = getFloat32(info.Env(), value); + result.unit = 1; + result.type = 0; + break; + } + case napi_string: { + KStringPtr string = getString(info.Env(), value); + parseKLength(string, &result); + result.type = 1; + result.resource = 0; + break; + } + case napi_object: { + result.value = 0; + result.unit = 1; + result.type = 2; + napi_value field; + napi_status status = napi_get_named_property(info.Env(), value, "id", &field); + if (status == 0) { + status = napi_get_value_int32(info.Env(), field, &result.resource); + if (status != 0) result.resource = 0; + } else { + result.resource = 0; + } + break; + } + default: + INTEROP_FATAL("Error, unexpected KLength type"); + } + return result; +} + + +template <> +inline KInteropBuffer getArgument(const CallbackInfo& info, int index) { + NAPI_ASSERT_INDEX(info, index, { 0 }); + return getArgument((napi_env)info.Env(), (napi_value)info[index]); +} + +template <> +inline KFloat getArgument(const CallbackInfo& info, int index) { + return getFloat32(info, index); +} + +template <> +inline KDouble getArgument(const CallbackInfo& info, int index) { + return getFloat64(info, index); +} + +template <> +inline KNativePointer getArgument(const CallbackInfo& info, int index) { + return getPointer(info, index); +} + +template <> +inline KLong getArgument(const CallbackInfo& info, int index) { + return getInt64(info, index); +} + +template <> +inline KULong getArgument(const CallbackInfo& info, int index) { + return getUInt64(info, index); +} + +template <> +inline KNativePointerArray getArgument(const CallbackInfo& info, int index) { + return getPointerElements(info, index); +} + +// template <> +// inline napi_value getArgument(const CallbackInfo& info, int index) { +// return getObject(info, index); +// } + +template <> +inline uint8_t* getArgument(const CallbackInfo& info, int index) { + return getUInt8Elements(info, index); +} + +template <> +inline const uint8_t* getArgument(const CallbackInfo& info, int index) { + return getUInt8Elements(info, index); +} + +template <> +inline int8_t* getArgument(const CallbackInfo& info, int index) { + return getInt8Elements(info, index); +} + +template <> +inline int16_t* getArgument(const CallbackInfo& info, int index) { + return getInt16Elements(info, index); +} + +template <> +inline uint16_t* getArgument(const CallbackInfo& info, int index) { + return getUInt16Elements(info, index); +} + +template <> +inline int32_t* getArgument(const CallbackInfo& info, int index) { + return getInt32Elements(info, index); +} + +template <> +inline uint32_t* getArgument(const CallbackInfo& info, int index) { + return getUInt32Elements(info, index); +} + +template <> +inline float* getArgument(const CallbackInfo& info, int index) { + return getFloat32Elements(info, index); +} + +template <> +inline KStringPtr getArgument(const CallbackInfo& info, int index) { + return getString(info, index); +} + +napi_value makeString(napi_env env, KStringPtr value); +napi_value makeString(napi_env env, const std::string& value); +napi_value makeBoolean(napi_env env, KBoolean value); +napi_value makeInt32(napi_env env, int32_t value); +napi_value makeUInt32(napi_env env, uint32_t value); +napi_value makeInt64(napi_env env, int32_t value); +napi_value makeUInt64(napi_env env, uint32_t value); +napi_value makeFloat32(napi_env env, float value); +napi_value makePointer(napi_env env, void* value); +napi_value makeVoid(napi_env env); +// napi_value makeObject(napi_env env, napi_value object); + +inline napi_value makeVoid(const CallbackInfo& info) { + return makeVoid(info.Env()); +} + +template +inline napi_value makeResult(const CallbackInfo& info, Type value) = delete; + +template <> +inline napi_value makeResult(const CallbackInfo& info, KBoolean value) { + return makeBoolean(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, int32_t value) { + return makeInt32(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, uint32_t value) { + return makeUInt32(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, int64_t value) { + return makeInt64(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, uint64_t value) { + return makeUInt64(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, float value) { + return makeFloat32(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, KNativePointer value) { + return makePointer(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, KVMObjectHandle value) { + return InteropTypeConverter::convertTo(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, KStringPtr value) { + return InteropTypeConverter::convertTo(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, KInteropBuffer value) { + return InteropTypeConverter::convertTo(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, KInteropReturnBuffer value) { + return InteropTypeConverter::convertTo(info.Env(), value); +} + +template <> +inline napi_value makeResult(const CallbackInfo& info, KInteropNumber value) { + return InteropTypeConverter::convertTo(info.Env(), value); +} + +typedef napi_value (*napi_type_t)(napi_env, napi_callback_info); + +class Exports { + std::unordered_map>> implementations; + +public: + static Exports* getInstance(); + + std::vector getModules(); + void addMethod(const char* module, const char* name, napi_type_t impl); + const std::vector>& getMethods(const std::string& module); +}; + +#define __QUOTE(x) #x +#define QUOTE(x) __QUOTE(x) + +#ifdef _MSC_VER +#define MAKE_NODE_EXPORT(module, name) \ + static void __init_##name() { \ + Exports::getInstance()->addMethod(QUOTE(module), "_"#name, Node_##name); \ + } \ + namespace { \ + struct __Init_##name { \ + __Init_##name() { __init_##name(); } \ + } __Init_##name##_v; \ + } +#else +#define MAKE_NODE_EXPORT(module, name) \ + __attribute__((constructor)) \ + static void __init_##name() { \ + Exports::getInstance()->addMethod(QUOTE(module), "_"#name, Node_##name); \ + } +#endif + +#ifndef KOALA_INTEROP_MODULE +#error KOALA_INTEROP_MODULE is undefined +#endif + +#define MAKE_INTEROP_NODE_EXPORT(name) MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_0(name, Ret) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + return makeResult(info, impl_##name()); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_1(name, Ret, P0) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + return makeResult(info, impl_##name(p0)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_2(name, Ret, P0, P1) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + return makeResult(info, impl_##name(p0, p1)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_3(name, Ret, P0, P1, P2) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + return makeResult(info, impl_##name(p0, p1, p2)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_4(name, Ret, P0, P1, P2, P3) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + return makeResult(info, impl_##name(p0, p1, p2, p3)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_5(name, Ret, P0, P1, P2, P3, P4) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_6(name, Ret, P0, P1, P2, P3, P4, P5) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_7(name, Ret, P0, P1, P2, P3, P4, P5, P6) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5, p6)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_8(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_9(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_10(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_11(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_12(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + P11 p11 = getArgument(info, 11); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_13(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + P11 p11 = getArgument(info, 11); \ + P12 p12 = getArgument(info, 12); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_14(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + P11 p11 = getArgument(info, 11); \ + P12 p12 = getArgument(info, 12); \ + P13 p13 = getArgument(info, 13); \ + return makeResult(info, impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V0(name) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + impl_##name(); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V1(name, P0) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + impl_##name(p0); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V2(name, P0, P1) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + impl_##name(p0, p1); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V3(name, P0, P1, P2) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + impl_##name(p0, p1, p2); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V4(name, P0, P1, P2, P3) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + impl_##name(p0, p1, p2, p3); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V5(name, P0, P1, P2, P3, P4) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + impl_##name(p0, p1, p2, p3, p4); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V6(name, P0, P1, P2, P3, P4, P5) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + impl_##name(p0, p1, p2, p3, p4, p5); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V7(name, P0, P1, P2, P3, P4, P5, P6) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V8(name, P0, P1, P2, P3, P4, P5, P6, P7) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V9(name, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(impl_##name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V10(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V11(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(impl_##name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V12(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(impl_##name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + P11 p11 = getArgument(info, 11); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V13(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(impl_##name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + P11 p11 = getArgument(info, 11); \ + P12 p12 = getArgument(info, 12); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V14(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + P11 p11 = getArgument(info, 11); \ + P12 p12 = getArgument(info, 12); \ + P13 p13 = getArgument(info, 13); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_V15(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + P5 p5 = getArgument(info, 5); \ + P6 p6 = getArgument(info, 6); \ + P7 p7 = getArgument(info, 7); \ + P8 p8 = getArgument(info, 8); \ + P9 p9 = getArgument(info, 9); \ + P10 p10 = getArgument(info, 10); \ + P11 p11 = getArgument(info, 11); \ + P12 p12 = getArgument(info, 12); \ + P13 p13 = getArgument(info, 13); \ + P14 p14 = getArgument(info, 14); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_0(name, Ret) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(impl_##name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + return makeResult(info, impl_##name(ctx)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_1(name, Ret, P0) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(impl_##name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + return makeResult(info, impl_##name(ctx, p0)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_2(name, Ret, P0, P1) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + return makeResult(info, impl_##name(ctx, p0, p1)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_3(name, Ret, P0, P1, P2) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + return makeResult(info, impl_##name(ctx, p0, p1, p2)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_4(name, Ret, P0, P1, P2, P3) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + return makeResult(info, impl_##name(ctx, p0, p1, p2, p3)); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_V0(name) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + impl_##name(ctx); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + + +#define KOALA_INTEROP_CTX_V1(name, P0) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + impl_##name(ctx, p0); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_V2(name, P0, P1) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + impl_##name(ctx, p0, p1); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_V3(name, P0, P1, P2) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + impl_##name(ctx, p0, p1, p2); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_V4(name, P0, P1, P2, P3) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + impl_##name(ctx, p0, p1, p2, p3); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define KOALA_INTEROP_CTX_V5(name, P0, P1, P2, P3, P4) \ + napi_value Node_##name(napi_env env, napi_callback_info cbinfo) { \ + KOALA_MAYBE_LOG(name) \ + CallbackInfo info(env, cbinfo); \ + KVMContext ctx = reinterpret_cast((napi_env)info.Env()); \ + P0 p0 = getArgument(info, 0); \ + P1 p1 = getArgument(info, 1); \ + P2 p2 = getArgument(info, 2); \ + P3 p3 = getArgument(info, 3); \ + P4 p4 = getArgument(info, 4); \ + impl_##name(ctx, p0, p1, p2, p3, p4); \ + return makeVoid(info); \ + } \ + MAKE_NODE_EXPORT(KOALA_INTEROP_MODULE, name) + +#define NODEJS_GET_AND_THROW_LAST_ERROR(env) \ + do { \ + const napi_extended_error_info *error_info; \ + napi_get_last_error_info((env), &error_info); \ + bool is_pending; \ + napi_is_exception_pending((env), &is_pending); \ + /* If an exception is already pending, don't rethrow it */ \ + if (!is_pending) { \ + const char* error_message = error_info->error_message != NULL ? \ + error_info->error_message : \ + "empty error message"; \ + napi_throw_error((env), NULL, error_message); \ + } \ + } while (0) + +napi_value getKoalaNapiCallbackDispatcher(napi_env env); +// TODO: can/shall we cache bridge reference? + +#define KOALA_INTEROP_CALL_VOID(venv, id, length, args) \ +{ \ + napi_env env = reinterpret_cast(venv); \ + napi_value bridge = getKoalaNapiCallbackDispatcher(env), \ + global = nullptr, return_val = nullptr; \ + napi_handle_scope scope = nullptr; \ + napi_open_handle_scope(env, &scope); \ + napi_status status = napi_get_global(env, &global); \ + napi_value node_args[3]; \ + napi_create_int32(env, id, &node_args[0]); \ + napi_value buffer = nullptr; \ + napi_create_external_arraybuffer(env, \ + args, length, \ + [](napi_env, void* data, void* hint) {}, nullptr, &buffer); \ + napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &node_args[1]); \ + napi_create_int32(env, length, &node_args[2]); \ + status = napi_call_function(env, global, bridge, 3, node_args, &return_val); \ + if (status != napi_ok) NODEJS_GET_AND_THROW_LAST_ERROR((env)); \ + napi_close_handle_scope(env, scope); \ +} + +#define KOALA_INTEROP_CALL_INT(venv, id, length, args) \ +{ \ + napi_env env = reinterpret_cast(venv); \ + napi_value bridge = getKoalaNapiCallbackDispatcher(env), \ + global = nullptr, return_val = nullptr; \ + napi_handle_scope scope = nullptr; \ + napi_open_handle_scope(env, &scope); \ + napi_status status = napi_get_global(env, &global); \ + napi_value node_args[3]; \ + napi_create_int32(env, id, &node_args[0]); \ + napi_value buffer = nullptr; \ + napi_create_external_arraybuffer(env, \ + args, length, \ + [](napi_env, void* data, void* hint) {}, nullptr, &buffer); \ + napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &node_args[1]); \ + napi_create_int32(env, length, &node_args[2]); \ + status = napi_call_function(env, global, bridge, 3, node_args, &return_val); \ + if (status != napi_ok) NODEJS_GET_AND_THROW_LAST_ERROR((env)); \ + int result; \ + status = napi_get_value_int32(env, return_val, &result); \ + napi_close_handle_scope(env, scope); \ + return result; \ +} + +#define KOALA_INTEROP_CALL_VOID_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_VOID(venv, id, (argc) * sizeof(int32_t), args) +#define KOALA_INTEROP_CALL_INT_INTS32(venv, id, argc, args) KOALA_INTEROP_CALL_INT(venv, id, (argc) * sizeof(int32_t), args) + +#endif // KOALA_NAPI + +#endif // _CONVERTORS_NAPI_H_ \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/napi/win-dynamic-node.cc b/koala-wrapper/koalaui/interop/src/cpp/napi/win-dynamic-node.cc new file mode 100644 index 000000000..6ec8fcc34 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/napi/win-dynamic-node.cc @@ -0,0 +1,672 @@ +/* + * 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 "node_api.h" + +#define NAPI_CDECL __cdecl + +#define NAPI_FUNCTIONS(op) \ + op(napi_module_register) \ + op(napi_create_function) \ + op(napi_set_named_property) \ + op(napi_create_string_utf8) \ + op(napi_add_env_cleanup_hook) \ + op(napi_get_last_error_info) \ + op(napi_get_value_bigint_int64) \ + op(napi_get_value_bigint_uint64) \ + op(napi_create_object) \ + op(napi_get_arraybuffer_info) \ + op(napi_create_bigint_uint64) \ + op(napi_is_typedarray) \ + op(napi_add_finalizer) \ + op(napi_get_typedarray_info) \ + op(napi_set_property) \ + op(napi_get_value_bool) \ + op(napi_coerce_to_string) \ + op(napi_get_value_uint32) \ + op(napi_get_value_int32) \ + op(napi_throw) \ + op(napi_get_cb_info) \ + op(napi_create_error) \ + op(napi_get_value_string_utf8) \ + op(napi_define_properties) \ + op(napi_delete_reference) \ + op(napi_get_reference_value) \ + op(napi_open_handle_scope) \ + op(napi_close_handle_scope) \ + op(napi_open_escapable_handle_scope) \ + op(napi_close_escapable_handle_scope) \ + op(napi_is_exception_pending) \ + op(napi_create_type_error) \ + op(napi_escape_handle) \ + op(napi_get_and_clear_last_exception) \ + op(napi_fatal_error) \ + op(napi_create_double) \ + op(napi_typeof) \ + op(napi_get_property) \ + op(napi_get_named_property) \ + op(napi_create_reference) \ + op(napi_get_global) \ + op(napi_has_property) \ + op(napi_get_undefined) \ + op(napi_get_value_double) \ + op(napi_close_callback_scope) \ + op(napi_async_destroy) \ + op(napi_call_function) \ + op(napi_get_value_external) \ + op(napi_throw_error) \ + op(napi_create_int32) \ + op(napi_create_external_arraybuffer) \ + op(napi_create_typedarray) \ + op(napi_create_string_latin1) \ + op(napi_create_async_work) \ + op(napi_delete_async_work) \ + op(napi_queue_async_work) \ + op(napi_resolve_deferred) \ + op(napi_reject_deferred) \ + op(napi_create_promise) \ + op(napi_create_threadsafe_function) \ + op(napi_acquire_threadsafe_function) \ + op(napi_release_threadsafe_function) \ + op(napi_call_threadsafe_function) \ + op(napi_is_dataview) \ + op(napi_is_arraybuffer) \ + op(napi_get_dataview_info)\ + op(napi_get_boolean)\ + op(napi_create_uint32)\ + op(napi_create_bigint_int64)\ + +#define DECL_NAPI_IMPL(fn_name, ...) decltype(&fn_name) p_##fn_name; + +NAPI_FUNCTIONS(DECL_NAPI_IMPL) + +bool LoadNapiFunctions() { + static bool isLoaded = false; + if (isLoaded) return true; + HMODULE nodeModule = GetModuleHandle(NULL); + FARPROC fn_addr = GetProcAddress(nodeModule, "napi_module_register"); + + if (fn_addr == NULL) { + nodeModule = GetModuleHandleA("node.dll"); + if (nodeModule == NULL) return false; + fn_addr = GetProcAddress(nodeModule, "napi_module_register"); + if (fn_addr == NULL) { + return false; + } + } + bool apiLoadFailed = false; + +#define GET_NAPI_IMPL(fn_name) \ + fn_addr = GetProcAddress(nodeModule, #fn_name); \ + if (fn_addr == NULL) apiLoadFailed = true; \ + p_##fn_name = (decltype(p_##fn_name))fn_addr; + + // Assign the addresses of the needed functions to the "p*" named pointers. + NAPI_FUNCTIONS(GET_NAPI_IMPL); + + // If any required APIs failed to load, return false + if (apiLoadFailed) return false; + + isLoaded = true; + + return true; +} + +NAPI_EXTERN void NAPI_CDECL +napi_module_register(napi_module* mod) { + LoadNapiFunctions(); + p_napi_module_register(mod); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_get_last_error_info(napi_env env, const napi_extended_error_info** result) { + LoadNapiFunctions(); + return p_napi_get_last_error_info(env, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_value_bigint_int64( + napi_env env, napi_value value, int64_t* result, bool* lossless) { + LoadNapiFunctions(); + return p_napi_get_value_bigint_int64(env, value, result, lossless); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_value_bigint_uint64( + napi_env env, napi_value value, uint64_t* result, bool* lossless) { + LoadNapiFunctions(); + return p_napi_get_value_bigint_uint64(env, value, result, lossless); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_object(napi_env env, napi_value* result) { + LoadNapiFunctions(); + return p_napi_create_object(env, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_arraybuffer_info(napi_env env, napi_value arraybuffer, void** data, size_t* byte_length) { + LoadNapiFunctions(); + return p_napi_get_arraybuffer_info(env, arraybuffer, data, byte_length); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_create_bigint_uint64(napi_env env, uint64_t value, napi_value* result) { + LoadNapiFunctions(); + return p_napi_create_bigint_uint64(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_is_typedarray(napi_env env, napi_value value, bool* result) { + LoadNapiFunctions(); + return p_napi_is_typedarray(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_add_finalizer(napi_env env, + napi_value js_object, + void* finalize_data, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result) { + LoadNapiFunctions(); + return p_napi_add_finalizer(env, js_object, finalize_data, finalize_cb, finalize_hint, result); +} + + +NAPI_EXTERN napi_status NAPI_CDECL +napi_get_typedarray_info(napi_env env, + napi_value typedarray, + napi_typedarray_type* type, + size_t* length, + void** data, + napi_value* arraybuffer, + size_t* byte_offset) { + LoadNapiFunctions(); + return p_napi_get_typedarray_info(env, typedarray, type, length, data, arraybuffer, byte_offset); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_set_property(napi_env env, + napi_value object, + napi_value key, + napi_value value) { + LoadNapiFunctions(); + return p_napi_set_property(env, object, key, value); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_value_bool(napi_env env, + napi_value value, + bool* result) { + LoadNapiFunctions(); + return p_napi_get_value_bool(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_coerce_to_string(napi_env env, + napi_value value, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_coerce_to_string(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_value_int32(napi_env env, + napi_value value, + int32_t* result) { + LoadNapiFunctions(); + return p_napi_get_value_int32(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_cb_info( + napi_env env, + napi_callback_info cbinfo, + size_t* argc, + napi_value* argv, + napi_value* this_arg, + void** data) { + LoadNapiFunctions(); + return p_napi_get_cb_info(env, cbinfo, argc, argv, this_arg, data); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_string_utf8(napi_env env, + const char* str, + size_t length, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_create_string_utf8(env, str, length, result); +} + + +NAPI_EXTERN napi_status NAPI_CDECL napi_throw(napi_env env, napi_value error) { + LoadNapiFunctions(); + return p_napi_throw(env, error); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_create_error(env, code, msg, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_value_string_utf8( + napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result) { + LoadNapiFunctions(); + return p_napi_get_value_string_utf8(env, value, buf, bufsize, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_define_properties(napi_env env, + napi_value object, + size_t property_count, + const napi_property_descriptor* properties) { + LoadNapiFunctions(); + return p_napi_define_properties(env, object, property_count, properties); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_delete_reference(napi_env env, + napi_ref ref) { + LoadNapiFunctions(); + return p_napi_delete_reference(env, ref); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_reference_value(napi_env env, + napi_ref ref, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_get_reference_value(env, ref, result); +} +NAPI_EXTERN napi_status NAPI_CDECL +napi_open_handle_scope(napi_env env, napi_handle_scope* result) { + LoadNapiFunctions(); + return p_napi_open_handle_scope(env, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_close_handle_scope(napi_env env, napi_handle_scope scope) { + LoadNapiFunctions(); + return p_napi_close_handle_scope(env, scope); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_open_escapable_handle_scope( + napi_env env, napi_escapable_handle_scope* result) { + return p_napi_open_escapable_handle_scope(env, result); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_close_escapable_handle_scope( + napi_env env, napi_escapable_handle_scope scope) { + LoadNapiFunctions(); + return p_napi_close_escapable_handle_scope(env, scope); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_is_exception_pending(napi_env env, + bool* result) { + LoadNapiFunctions(); + return p_napi_is_exception_pending(env, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_property(napi_env env, + napi_value object, + napi_value key, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_get_property(env, object, key, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_value_uint32(napi_env env, + napi_value value, + uint32_t* result) { + LoadNapiFunctions(); + return p_napi_get_value_uint32(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_typeof(napi_env env, + napi_value value, + napi_valuetype* result) { + LoadNapiFunctions(); + return p_napi_typeof(env, value, result); +} +NAPI_EXTERN napi_status NAPI_CDECL +napi_get_and_clear_last_exception(napi_env env, napi_value* result) { + LoadNapiFunctions(); + return p_napi_get_and_clear_last_exception(env, result); +} +NAPI_EXTERN NAPI_NO_RETURN void NAPI_CDECL +napi_fatal_error(const char* location, + size_t location_len, + const char* message, + size_t message_len) { + LoadNapiFunctions(); + p_napi_fatal_error(location, location_len, message, message_len); + // Not reachable, but not represented in type signature. + exit(0); +} +NAPI_EXTERN napi_status NAPI_CDECL +napi_get_value_external(napi_env env, napi_value value, void** result) { + LoadNapiFunctions(); + return p_napi_get_value_external(env, value, result); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_create_double(napi_env env, + double value, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_create_double(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_type_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_create_type_error(env, code, msg, result); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_get_named_property(napi_env env, + napi_value object, + const char* utf8name, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_get_named_property(env, object, utf8name, result); +} +NAPI_EXTERN napi_status NAPI_CDECL +napi_create_reference(napi_env env, + napi_value value, + uint32_t initial_refcount, + napi_ref* result) { + LoadNapiFunctions(); + return p_napi_create_reference(env, value, initial_refcount, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_escape_handle(napi_env env, + napi_escapable_handle_scope scope, + napi_value escapee, + napi_value* result); +NAPI_EXTERN napi_status NAPI_CDECL napi_get_global(napi_env env, + napi_value* result) { + + LoadNapiFunctions(); + return p_napi_get_global(env, result); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_has_property(napi_env env, + napi_value object, + napi_value key, + bool* result) { + LoadNapiFunctions(); + return p_napi_has_property(env, object, key, result); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_create_function(napi_env env, + const char* utf8name, + size_t length, + napi_callback cb, + void* data, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_create_function(env, utf8name, length, cb, data, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_escape_handle(napi_env env, + napi_escapable_handle_scope scope, + napi_value escapee, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_escape_handle(env, scope, escapee, result); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_get_undefined(napi_env env, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_get_undefined(env, result); +} +NAPI_EXTERN napi_status NAPI_CDECL napi_get_value_double(napi_env env, + napi_value value, + double* result) { + LoadNapiFunctions(); + return p_napi_get_value_double(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_close_callback_scope(napi_env env, napi_callback_scope scope) { + LoadNapiFunctions(); + return p_napi_close_callback_scope(env, scope); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_async_destroy(napi_env env, napi_async_context async_context) { + LoadNapiFunctions(); + return p_napi_async_destroy(env, async_context); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_call_function(napi_env env, + napi_value recv, + napi_value func, + size_t argc, + const napi_value* argv, + napi_value* result) { + LoadNapiFunctions(); + return p_napi_call_function(env, recv, func, argc, argv, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_throw_error(napi_env env, + const char* code, + const char* msg) + { + LoadNapiFunctions(); + return p_napi_throw_error(env, code, msg); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_int32(napi_env env, + int32_t value, + napi_value* result) + { + LoadNapiFunctions(); + return p_napi_create_int32(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_boolean(napi_env env, + int32_t value, + napi_value* result) +{ +LoadNapiFunctions(); +return p_napi_create_int32(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_boolean(napi_env env, + bool value, + napi_value* result) +{ +LoadNapiFunctions(); +return p_napi_get_boolean(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_uint32(napi_env env, + uint32_t value, + napi_value* result) +{ + LoadNapiFunctions(); +return p_napi_create_uint32(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_bigint_int64(napi_env env, + int64_t value, + napi_value* result) +{ + LoadNapiFunctions(); + return p_napi_create_bigint_int64(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_external_arraybuffer( + napi_env env, + void* external_data, + size_t byte_length, + napi_finalize finalize_cb, + void* finalize_hint, + napi_value* result) +{ + LoadNapiFunctions(); + return p_napi_create_external_arraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_typedarray( + napi_env env, + napi_typedarray_type type, + size_t length, + napi_value array_buffer, + size_t byte_offset, + napi_value* result +) +{ + LoadNapiFunctions(); + return p_napi_create_typedarray(env, type, length, array_buffer, byte_offset, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_string_latin1( + napi_env env, + const char* str, + size_t length, + napi_value* result +) +{ + LoadNapiFunctions(); + return p_napi_create_string_latin1(env, str, length, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_async_work( + napi_env env, + napi_value async_resource, + napi_value async_resource_name, + napi_async_execute_callback execute, + napi_async_complete_callback complete, + void* data, + napi_async_work* result +) +{ + LoadNapiFunctions(); + return p_napi_create_async_work(env, async_resource, async_resource_name, execute, complete, data, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_delete_async_work( + napi_env env, + napi_async_work work +) +{ + LoadNapiFunctions(); + return p_napi_delete_async_work(env, work); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_queue_async_work( + napi_env env, + napi_async_work work +) +{ + LoadNapiFunctions(); + return p_napi_queue_async_work(env, work); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_promise( + napi_env env, + napi_deferred* deferred, + napi_value* promise) +{ + LoadNapiFunctions(); + return p_napi_create_promise(env, deferred, promise); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_resolve_deferred( + napi_env env, + napi_deferred deferred, + napi_value resolution) +{ + LoadNapiFunctions(); + return p_napi_resolve_deferred(env, deferred, resolution); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_reject_deferred( + napi_env env, + napi_deferred deferred, + napi_value rejection) +{ + LoadNapiFunctions(); + return p_napi_reject_deferred(env, deferred, rejection); +} + +NAPI_EXTERN napi_status NAPI_CDECL napi_create_threadsafe_function( + napi_env env, + napi_value func, + napi_value async_resource, + napi_value async_resource_name, + size_t max_queue_size, + size_t initial_thread_count, + void* thread_finalize_data, + napi_finalize thread_finalize_cb, + void* context, + napi_threadsafe_function_call_js call_js_cb, + napi_threadsafe_function* result) +{ + LoadNapiFunctions(); + return p_napi_create_threadsafe_function(env, func, async_resource, async_resource_name, max_queue_size, initial_thread_count, thread_finalize_data, thread_finalize_cb, context, call_js_cb, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_acquire_threadsafe_function(napi_threadsafe_function func) +{ + LoadNapiFunctions(); + return p_napi_acquire_threadsafe_function(func); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_release_threadsafe_function(napi_threadsafe_function func, napi_threadsafe_function_release_mode mode) +{ + LoadNapiFunctions(); + return p_napi_release_threadsafe_function(func, mode); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_call_threadsafe_function( + napi_threadsafe_function func, + void* data, + napi_threadsafe_function_call_mode is_blocking) +{ + LoadNapiFunctions(); + return p_napi_call_threadsafe_function(func, data, is_blocking); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_is_dataview(napi_env env, + napi_value value, + bool* result) { + LoadNapiFunctions(); + return p_napi_is_dataview(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_is_arraybuffer(napi_env env, + napi_value value, + bool* result) { + LoadNapiFunctions(); + return p_napi_is_arraybuffer(env, value, result); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_get_dataview_info(napi_env env, + napi_value dataview, + size_t* bytelength, + void** data, + napi_value* arraybuffer, + size_t* byte_offset) { + LoadNapiFunctions(); + return p_napi_get_dataview_info(env, dataview, bytelength, data, arraybuffer, byte_offset); +} + +NAPI_EXTERN napi_status NAPI_CDECL +napi_set_named_property(napi_env env, + napi_value object, + const char* utf8name, + napi_value value) { + LoadNapiFunctions(); + return p_napi_set_named_property(env, object, utf8name, value); +} diff --git a/koala-wrapper/koalaui/interop/src/cpp/ohos/hilog/log.h b/koala-wrapper/koalaui/interop/src/cpp/ohos/hilog/log.h new file mode 100644 index 000000000..7452137c2 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ohos/hilog/log.h @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2021-2022 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 HIVIEWDFX_HILOG_H +#define HIVIEWDFX_HILOG_H +/** + * @addtogroup HiLog + * @{ + * + * @brief Provides logging functions. + * + * For example, you can use these functions to output logs of the specified log type, service domain, log tag, + * and log level. + * + * @syscap SystemCapability.HiviewDFX.HiLog + * + * @since 8 + */ + +/** + * @file log.h + * + * @brief Defines the logging functions of the HiLog module. + * + * Before outputting logs, you must define the service domain, and log tag, use the function with + * the specified log type and level, and specify the privacy identifier.\n + *
  • Service domain: used to identify the subsystem and module of a service. Its value is a hexadecimal + * integer ranging from 0x0 to 0xFFFF. \n + *
  • Log tag: a string used to identify the class, file, or service.
  • \n + *
  • Log level: DEBUG, INFO, WARN, ERROR, and FATAL
  • \n + *
  • Parameter format: a printf format string that starts with a % character, including format specifiers + * and variable parameters.
  • \n + *
  • Privacy identifier: {public} or {private} added between the % character and the format specifier in + * each parameter. Note that each parameter has a privacy identifier. If no privacy identifier is added, + * the parameter is considered to be private.
\n + * + * Sample code:\n + * Defining the service domain and log tag:\n + * #include \n + * #define LOG_DOMAIN 0x0201\n + * #define LOG_TAG "MY_TAG"\n + * Outputting logs:\n + * HILOG_WARN({@link LOG_APP}, "Failed to visit %{private}s, reason:%{public}d.", url, errno);\n + * Output result:\n + * 05-06 15:01:06.870 1051 1051 W 0201/MY_TAG: Failed to visit , reason:503.\n + * + * @since 8 + */ +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Defines the service domain for a log file. + * + * The service domain is used to identify the subsystem and module of a service. Its value is a hexadecimal integer + * ranging from 0x0 to 0xFFFF. If the value is beyond the range, its significant bits are automatically truncated. \n + * + * @since 8 + */ +#ifndef LOG_DOMAIN +#define LOG_DOMAIN 0 +#endif + +/** + * @brief Defines a string constant used to identify the class, file, or service. + * + * @since 8 + */ +#ifndef LOG_TAG +#define LOG_TAG NULL +#endif + +/** + * @brief Enumerates log types. + * + * Currently, LOG_APP is available. \n + * + * @since 8 + */ +typedef enum { + /** Third-party application logs */ + LOG_APP = 0, +} LogType; + +/** + * @brief Enumerates log levels. + * + * You are advised to select log levels based on their respective usage scenarios:\n + *
  • DEBUG: used for debugging and disabled from commercial releases
  • \n + *
  • INFO: used for logging important system running status and steps in key processes
  • \n + *
  • WARN: used for logging unexpected exceptions that have little impact on user experience and can + * automatically recover. Logs at this level are generally output when such exceptions are detected and + * captured.
  • \n + *
  • ERROR: used for logging malfunction that affects user experience and cannot automatically + * recover
  • \n + *
  • FATAL: used for logging major exceptions that have severely affected user experience and should + * not occur.
\n + * + * @since 8 + */ +typedef enum { + /** Debug level to be used by {@link OH_LOG_DEBUG} */ + LOG_DEBUG = 3, + /** Informational level to be used by {@link OH_LOG_INFO} */ + LOG_INFO = 4, + /** Warning level to be used by {@link OH_LOG_WARN} */ + LOG_WARN = 5, + /** Error level to be used by {@link OH_LOG_ERROR} */ + LOG_ERROR = 6, + /** Fatal level to be used by {@link OH_LOG_FATAL} */ + LOG_FATAL = 7, +} LogLevel; + +/** + * @brief Outputs logs. + * + * You can use this function to output logs based on the specified log type, log level, service domain, log tag, + * and variable parameters determined by the format specifier and privacy identifier in the printf format. + * + * @param type Indicates the log type. The type for third-party applications is defined by {@link LOG_APP}. + * @param level Indicates the log level, which can be LOG_DEBUG, LOG_INFO, LOG_WARN, + * LOG_ERROR, and LOG_FATAL. + * @param domain Indicates the service domain of logs. Its value is a hexadecimal integer ranging from 0x0 to 0xFFFF. + * @param tag Indicates the log tag, which is a string used to identify the class, file, or service behavior. + * @param fmt Indicates the format string, which is an enhancement of a printf format string and supports the privacy + * identifier. Specifically, {public} or {private} is added between the % character and the format specifier + * in each parameter. \n + * @param ... Indicates a list of parameters. The number and type of parameters must map onto the format specifiers + * in the format string. + * @return Returns 0 or a larger value if the operation is successful; returns a value smaller + * than 0 otherwise. + * @since 8 + */ +int OH_LOG_Print(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...) + __attribute__((__format__(os_log, 5, 6))); + +/** + * @brief Checks whether logs of the specified service domain, log tag, and log level can be output. + * + * @param domain Indicates the service domain of logs. + * @param tag Indicates the log tag. + * @param level Indicates the log level. + * @return Returns true if the specified logs can be output; returns false otherwise. + * @since 8 + */ +bool OH_LOG_IsLoggable(unsigned int domain, const char *tag, LogLevel level); + +/** + * @brief Outputs debug logs. This is a function-like macro. + * + * Before calling this function, define the log service domain and log tag. Generally, you need to define them at + * the beginning of the source file. \n + * + * @param type Indicates the log type. The type for third-party applications is defined by {@link LOG_APP}. + * @param fmt Indicates the format string, which is an enhancement of a printf format string and supports the + * privacy identifier. Specifically, {public} or {private} is added between the % character and the format specifier + * in each parameter. \n + * @param ... Indicates a list of parameters. The number and type of parameters must map onto the format specifiers + * in the format string. + * @see OH_LOG_Print + * @since 8 + */ +#define OH_LOG_DEBUG(type, ...) ((void)OH_LOG_Print((type), LOG_DEBUG, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +/** + * @brief Outputs informational logs. This is a function-like macro. + * + * Before calling this function, define the log service domain and log tag. Generally, you need to define them + * at the beginning of the source file. \n + * + * @param type Indicates the log type. The type for third-party applications is defined by {@link LOG_APP}. + * @param fmt Indicates the format string, which is an enhancement of a printf format string and supports the privacy + * identifier. Specifically, {public} or {private} is added between the % character and the format specifier in + * each parameter. \n + * @param ... Indicates a list of parameters. The number and type of parameters must map onto the format specifiers + * in the format string. + * @see OH_LOG_Print + * @since 8 + */ +#define OH_LOG_INFO(type, ...) ((void)OH_LOG_Print((type), LOG_INFO, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +/** + * @brief Outputs warning logs. This is a function-like macro. + * + * Before calling this function, define the log service domain and log tag. Generally, you need to define them + * at the beginning of the source file. \n + * + * @param type Indicates the log type. The type for third-party applications is defined by {@link LOG_APP}. + * @param fmt Indicates the format string, which is an enhancement of a printf format string and supports the + * privacy identifier. Specifically, {public} or {private} is added between the % character and the format specifier + * in each parameter. \n + * @param ... Indicates a list of parameters. The number and type of parameters must map onto the format specifiers + * in the format string. + * @see OH_LOG_Print + * @since 8 + */ +#define OH_LOG_WARN(type, ...) ((void)OH_LOG_Print((type), LOG_WARN, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +/** + * @brief Outputs error logs. This is a function-like macro. + * + * Before calling this function, define the log service domain and log tag. Generally, you need to define + * them at the beginning of the source file. \n + * + * @param type Indicates the log type. The type for third-party applications is defined by {@link LOG_APP}. + * @param fmt Indicates the format string, which is an enhancement of a printf format string and supports the privacy + * identifier. Specifically, {public} or {private} is added between the % character and the format specifier in each + * parameter. \n + * @param ... Indicates a list of parameters. The number and type of parameters must map onto the format specifiers + * in the format string. + * @see OH_LOG_Print + * @since 8 + */ +#define OH_LOG_ERROR(type, ...) ((void)OH_LOG_Print((type), LOG_ERROR, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +/** + * @brief Outputs fatal logs. This is a function-like macro. + * + * Before calling this function, define the log service domain and log tag. Generally, you need to define them at + * the beginning of the source file. \n + * + * @param type Indicates the log type. The type for third-party applications is defined by {@link LOG_APP}. + * @param fmt Indicates the format string, which is an enhancement of a printf format string and supports the privacy + * identifier. Specifically, {public} or {private} is added between the % character and the format specifier in + * each parameter. \n + * @param ... Indicates a list of parameters. The number and type of parameters must map onto the format specifiers + * in the format string. + * @see OH_LOG_Print + * @since 8 + */ +#define OH_LOG_FATAL(type, ...) ((void)OH_LOG_Print((type), LOG_FATAL, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +/** + * @brief Defines the function pointer type for the user-defined log processing function. + * + * @param type Indicates the log type. The type for third-party applications is defined by {@link LOG_APP}. + * @param level Indicates the log level, which can be LOG_DEBUG, LOG_INFO, LOG_WARN, + * LOG_ERROR, and LOG_FATAL. + * @param domain Indicates the service domain of logs. Its value is a hexadecimal integer ranging from 0x0 to 0xFFFF. + * @param tag Indicates the log tag, which is a string used to identify the class, file, or service behavior. + * @param msg Indicates the log message itself, which is a formatted log string. + * @since 11 + */ +typedef void (*LogCallback)(const LogType type, const LogLevel level, const unsigned int domain, const char *tag, + const char *msg); + +/** + * @brief Set the user-defined log processing function. + * + * After calling this function, the callback function implemented by the user can receive all hilogs of the + * current process. + * Note that it will not change the default behavior of hilog logs of the current process, no matter whether this + * interface is called or not. \n + * + * @param callback Indicates the callback function implemented by the user. If you do not need to process hilog logs, + * you can transfer a null pointer. + * @since 11 + */ +void OH_LOG_SetCallback(LogCallback callback); + +#ifdef __cplusplus +} +#endif +/** @} */ + +#ifdef HILOG_RAWFORMAT +#include "hilog/log_inner.h" +#endif + +#endif // HIVIEWDFX_HILOG_C_H diff --git a/koala-wrapper/koalaui/interop/src/cpp/ohos/oh_sk_log.cc b/koala-wrapper/koalaui/interop/src/cpp/ohos/oh_sk_log.cc new file mode 100644 index 000000000..6aa01fe5e --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ohos/oh_sk_log.cc @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022-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 +#include +#include +#include +#include "oh_sk_log.h" + +static const char* KOALAUI_OHOS_LOG_ROOT = "/data/storage/el2/base/files/logs"; + +#define APPLY_LOG_FILE_PATTERN(buf, t, ms, pid) \ + sprintf(buf, "%s/%d_%d_%d_%ld.pid%d.log", \ + KOALAUI_OHOS_LOG_ROOT, t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, ms.tv_sec, pid) + +const char* oh_sk_log_type_str(oh_sk_log_type type) { + switch (type) { + case Log_Debug: return "D"; + case Log_Info: return "I"; + case Log_Warn: return "W"; + case Log_Error: return "E"; + case Log_Fatal: return "F"; + } +} + +void oh_sk_file_log(oh_sk_log_type type, const char* msg, ...) { + time_t t = time(nullptr); + struct tm lt = *localtime(&t); + struct timeval ms{}; + gettimeofday(&ms, nullptr); + + static char* path = nullptr; + if (!path) { + path = new char[strlen(KOALAUI_OHOS_LOG_ROOT) + 100]; + APPLY_LOG_FILE_PATTERN(path, lt, ms, getpid()); + mkdir(KOALAUI_OHOS_LOG_ROOT, 0777); + } + + std::unique_ptr file(fopen(path, "a"), fclose); + if (!file) return; + + fprintf(file.get(), "%02d-%02d %02d:%02d:%02d.%03ld %s koala: ", + lt.tm_mon + 1, lt.tm_mday, lt.tm_hour, lt.tm_min, lt.tm_sec, ms.tv_usec / 1000, + oh_sk_log_type_str(type)); + + va_list args; + va_start(args, msg); + vfprintf(file.get(), msg, args); + va_end(args); + + fprintf(file.get(), "\n"); +} diff --git a/koala-wrapper/koalaui/interop/src/cpp/ohos/oh_sk_log.h b/koala-wrapper/koalaui/interop/src/cpp/ohos/oh_sk_log.h new file mode 100644 index 000000000..961e2c0f1 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/ohos/oh_sk_log.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022-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. + */ + +#pragma once + +#include + +typedef enum { + Log_Debug, + Log_Info, + Log_Warn, + Log_Error, + Log_Fatal +} oh_sk_log_type; + +void oh_sk_file_log(oh_sk_log_type type, const char* msg, ...); +const char* oh_sk_log_type_str(oh_sk_log_type type); + +#ifdef OH_SK_LOG_TO_FILE + +#define OH_SK_LOG_INFO(msg) oh_sk_file_log(oh_sk_log_type::Log_Info, msg) +#define OH_SK_LOG_INFO_A(msg, ...) oh_sk_file_log(oh_sk_log_type::Log_Info, msg, ##__VA_ARGS__) +#define OH_SK_LOG_ERROR(msg) oh_sk_file_log(oh_sk_log_type::Log_Error, msg) +#define OH_SK_LOG_ERROR_A(msg, ...) oh_sk_file_log(oh_sk_log_type::Log_Error, msg, ##__VA_ARGS__) +#define OH_SK_LOG_DEBUG(msg) oh_sk_file_log(oh_sk_log_type::Log_Debug, msg) +#define OH_SK_LOG_DEBUG_A(msg, ...) oh_sk_file_log(oh_sk_log_type::Log_Debug, msg, ##__VA_ARGS__) +#define OH_SK_LOG_WARN(msg) oh_sk_file_log(oh_sk_log_type::Log_Warn, msg) +#define OH_SK_LOG_WARN_A(msg, ...) oh_sk_file_log(oh_sk_log_type::Log_Warn, msg, ##__VA_ARGS__) +#define OH_SK_LOG_FATAL(msg) oh_sk_file_log(oh_sk_log_type::Log_Fatal, msg) +#define OH_SK_LOG_FATAL_A(msg, ...) oh_sk_file_log(oh_sk_log_type::Log_Fatal, msg, ##__VA_ARGS__) + +#else + +#define OH_SK_LOG_INFO(msg) OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Koala", msg) +#define OH_SK_LOG_INFO_A(msg, ...) OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Koala", msg, ##__VA_ARGS__) +#define OH_SK_LOG_ERROR(msg) OH_LOG_Print(LOG_APP, LOG_ERROR, 0xFF00, "Koala", msg) +#define OH_SK_LOG_ERROR_A(msg, ...) OH_LOG_Print(LOG_APP, LOG_ERROR, 0xFF00, "Koala", msg, ##__VA_ARGS__) +#define OH_SK_LOG_DEBUG(msg) OH_LOG_Print(LOG_APP, LOG_DEBUG, 0xFF00, "Koala", msg) +#define OH_SK_LOG_DEBUG_A(msg, ...) OH_LOG_Print(LOG_APP, LOG_DEBUG, 0xFF00, "Koala", msg, ##__VA_ARGS__) +#define OH_SK_LOG_WARN(msg) OH_LOG_Print(LOG_APP, LOG_WARN, 0xFF00, "Koala", msg) +#define OH_SK_LOG_WARN_A(msg, ...) OH_LOG_Print(LOG_APP, LOG_WARN, 0xFF00, "Koala", msg, ##__VA_ARGS__) +#define OH_SK_LOG_FATAL(msg) OH_LOG_Print(LOG_APP, LOG_FATAL, 0xFF00, "Koala", msg) +#define OH_SK_LOG_FATAL_A(msg, ...) OH_LOG_Print(LOG_APP, LOG_FATAL, 0xFF00, "Koala", msg, ##__VA_ARGS__) + +#endif diff --git a/koala-wrapper/koalaui/interop/src/cpp/profiler.h b/koala-wrapper/koalaui/interop/src/cpp/profiler.h new file mode 100644 index 000000000..a3b9da38c --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/profiler.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022-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 _KOALA_PROFILER_ +#define _KOALA_PROFILER_ + +#include +#include + +#include +#include +#include +#include +#include + +struct InteropProfilerRecord { + int64_t time; + int64_t count; + InteropProfilerRecord(int64_t time, int64_t count) : time(time), count(count) {} +}; + +class InteropProfiler { + private: + std::unordered_map records; + static InteropProfiler* _instance; + InteropProfiler() {} + + public: + static InteropProfiler* instance() { + if (!_instance) _instance = new InteropProfiler(); + return _instance; + } + + void record(const char* name, int64_t ns) { + auto it = records.find(name); + if (it == records.end()) { + records.insert({name, InteropProfilerRecord(ns, 1)}); + } else { + it->second.time += ns; + it->second.count++; + } + } + + std::string report() { + std::vector> elems(records.begin(), records.end()); + std::sort(elems.begin(), elems.end(), + [](const std::pair&a, const std::pair&b) { + return b.second.time < a.second.time; + }); + int64_t total = 0; + std::for_each(elems.begin(), elems.end(), [&total](const std::pair&a) { + total += a.second.time; + }); + std::string result; + std::for_each(elems.begin(), elems.end(), [total, &result](const std::pair&a) { + auto ns = a.second.time; + auto count = a.second.count; + char buffer[1024]; + snprintf(buffer, sizeof buffer, "for %s[%lld]: %.01f%% (%lld)\n", a.first.c_str(), (long long)count, (double)ns / total * 100.0, (long long)ns); + result += buffer; + }); + return result; + } + + void reset() { + records.clear(); + } +}; + + +class InteropMethodCall { + private: + const char* name; + std::chrono::steady_clock::time_point begin; + public: + InteropMethodCall(const char* name) : name(name) { + begin = std::chrono::steady_clock::now(); + } + ~InteropMethodCall() { + auto end = std::chrono::steady_clock::now(); + int64_t ns = std::chrono::duration_cast(end - begin).count(); + InteropProfiler::instance()->record(name, ns); + } +}; + +#endif // _KOALA_PROFILER_ \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/tracer.h b/koala-wrapper/koalaui/interop/src/cpp/tracer.h new file mode 100644 index 000000000..f3b7ad20b --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/tracer.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022-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 _KOALA_TRACER_ +#define _KOALA_TRACER_ + +#ifdef KOALA_OHOS +#include +#define KOALA_TRACE(msg, str) OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Koala", msg, str) +// Also do +// hdc shell hilog -p off +// hdc shell hilog -Q pidoff +// to see the output. +#define KOALA_TRACE_PUBLIC "%{public}s" +#else +#include +#define KOALA_TRACE(msg, str) fprintf(stderr, "Koala: " msg "\n", str) +#define KOALA_TRACE_PUBLIC "%s" +#endif + +class InteropMethodCall { + private: + const char* name; + public: + InteropMethodCall(const char* name) : name(name) { + KOALA_TRACE(">>> " KOALA_TRACE_PUBLIC, name); + } + ~InteropMethodCall() { + KOALA_TRACE("<<< " KOALA_TRACE_PUBLIC, name); + } +}; + +#endif // _KOALA_TRACER_ \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/cpp/types/koala-types.h b/koala-wrapper/koalaui/interop/src/cpp/types/koala-types.h new file mode 100644 index 000000000..2c5e88754 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/types/koala-types.h @@ -0,0 +1,225 @@ +/* + * 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 _KOALA_TYPES_H +#define _KOALA_TYPES_H + +#include +#include +#include +#include + +struct KStringPtrImpl { + KStringPtrImpl(const char* str) : _value(nullptr), _owned(true) { + int len = str ? strlen(str) : 0; + assign(str, len); + } + KStringPtrImpl(const char* str, int len, bool owned) : _value(nullptr), _owned(owned) { + assign(str, len); + } + KStringPtrImpl() : _value(nullptr), _length(0), _owned(true) {} + + KStringPtrImpl(const KStringPtrImpl& other) = delete; + KStringPtrImpl& operator=(const KStringPtrImpl& other) = delete; + + KStringPtrImpl(KStringPtrImpl&& other) { + this->_value = other.release(); + this->_owned = other._owned; + other._owned = false; + this->_length = other._length; + } + + ~KStringPtrImpl() { if (_value && _owned) free(_value); } + + bool isNull() const { return _value == nullptr; } + const char* c_str() const { return _value; } + char* data() const { return _value; } + int length() const { return _length; } + + void resize(int size) { + _length = size; + if (!_owned) return; + // Ignore old content. + if (_value && _owned) free(_value); + _value = reinterpret_cast(malloc(size + 1)); + _value[size] = 0; + } + + void assign(const char* data) { + assign(data, data ? strlen(data) : 0); + } + + void assign(const char* data, int len) { + if (_value && _owned) free(_value); + if (data) { + if (_owned) { + _value = reinterpret_cast(malloc(len + 1)); + memcpy(_value, data, len); + _value[len] = 0; + } else { + _value = const_cast(data); + } + } else { + _value = nullptr; + } + _length = len; + } + + protected: + char* release() { + char* result = this->_value; + this->_value = nullptr; + return result; + } + private: + char* _value; + int _length; + bool _owned; +}; + +struct KInteropNumber { + int8_t tag; + union { + int32_t i32; + float f32; + }; + static inline KInteropNumber fromDouble(double value) { + KInteropNumber result = { 0 }; + // TODO: boundary check + if (value == std::floor(value)) { + result.tag = 102; // ARK_TAG_INT32 + result.i32 = (int)value; + } else { + result.tag = 103; // ARK_TAG_FLOAT32 + result.f32 = (float)value; + } + return result; + } + inline double asDouble() { + if (tag == 102) // ARK_TAG_INT32 + return (double)i32; + else + return (double)f32; + } +}; + +typedef int8_t KBoolean; +typedef uint8_t KByte; +typedef int16_t KChar; +typedef int16_t KShort; +typedef uint16_t KUShort; +typedef int32_t KInt; +typedef uint32_t KUInt; +typedef float KFloat; +typedef int64_t KLong; +typedef uint64_t KULong; +typedef double KDouble; +typedef void* KNativePointer; +typedef KStringPtrImpl KStringPtr; +typedef float* KFloatArray; +typedef const uint8_t* KStringArray; +typedef void** KNativePointerArray; + +struct KInteropBuffer { + KLong length; + KNativePointer data; + + KInt resourceId; + void (*dispose)(KInt /* resourceId for now */); +}; + +struct KInteropReturnBuffer { + KInt length; + KNativePointer data; + void (*dispose)(KNativePointer data, KInt length); +}; + +struct KLength { + KByte type; + KFloat value; + KInt unit; + KInt resource; +}; + +inline void parseKLength(const KStringPtrImpl &string, KLength *result) +{ + char *suffixPtr = nullptr; + + float value = std::strtof(string.c_str(), &suffixPtr); + + if (!suffixPtr || suffixPtr == string.c_str()) + { + // not a numeric value + result->unit = -1; + return; + } + result->value = value; + if (suffixPtr[0] == '\0' || (suffixPtr[0] == 'v' && suffixPtr[1] == 'p')) + { + result->unit = 1; + } + else if (suffixPtr[0] == '%') + { + result->unit = 3; + } + else if (suffixPtr[0] == 'p' && suffixPtr[1] == 'x') + { + result->unit = 0; + } + else if (suffixPtr[0] == 'l' && suffixPtr[1] == 'p' && suffixPtr[2] == 'x') + { + result->unit = 4; + } + else if (suffixPtr[0] == 'f' && suffixPtr[1] == 'p') + { + result->unit = 2; + } + else + { + result->unit = -1; + } +} + +struct _KVMContext; +typedef _KVMContext *KVMContext; + +// BEWARE: this MUST never be used in user code, only in very rare service code. +struct _KVMObject; +typedef _KVMObject *KVMObjectHandle; + +typedef struct KVMDeferred { + void* handler; + void* context; + void (*resolve)(KVMDeferred* thiz, uint8_t* data, int32_t length); + void (*reject)(KVMDeferred* thiz, const char* message); +} KVMDeferred; + +template T* ptr(KNativePointer ptr) { + return reinterpret_cast(ptr); +} + +template T& ref(KNativePointer ptr) { + return *reinterpret_cast(ptr); +} + +inline KNativePointer nativePtr(void* pointer) { + return reinterpret_cast(pointer); +} + +template KNativePointer fnPtr(void (*pointer)(T*)) { + return reinterpret_cast(pointer); +} + +#endif /* _KOALA_TYPES_H */ diff --git a/koala-wrapper/koalaui/interop/src/cpp/types/signatures.cc b/koala-wrapper/koalaui/interop/src/cpp/types/signatures.cc new file mode 100644 index 000000000..7f556adaf --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/types/signatures.cc @@ -0,0 +1,157 @@ +/* + * 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 "stdio.h" +#include +#include + +#include "signatures.h" +#include "interop-types.h" + +// For types with the same name on ets and jni +#define KOALA_INTEROP_TYPEDEF(func, lang, CPP_TYPE, SIG_TYPE, CODE_TYPE) \ + if (std::strcmp(func, "sigType") == 0) if (type == CPP_TYPE) return SIG_TYPE; \ + if (std::strcmp(func, "codeType") == 0) if (type == CPP_TYPE) return CODE_TYPE; + +// For types with distinct names on ets and jni +#define KOALA_INTEROP_TYPEDEF_LS(func, lang, CPP_TYPE, ETS_SIG_TYPE, ETS_CODE_TYPE, JNI_SIG_TYPE, JNI_CODE_TYPE) \ + if (std::strcmp(func, "sigType") == 0 && std::strcmp(lang, "ets") == 0) if (type == CPP_TYPE) return ETS_SIG_TYPE; \ + if (std::strcmp(func, "codeType") == 0 && std::strcmp(lang, "ets") == 0) if (type == CPP_TYPE) return ETS_CODE_TYPE; \ + if (std::strcmp(func, "sigType") == 0 && std::strcmp(lang, "jni") == 0) if (type == CPP_TYPE) return JNI_SIG_TYPE; \ + if (std::strcmp(func, "codeType") == 0 && std::strcmp(lang, "jni") == 0) if (type == CPP_TYPE) return JNI_CODE_TYPE; + +#define KOALA_INTEROP_TYPEDEFS(func, lang) \ + KOALA_INTEROP_TYPEDEF(func, lang, "void", "V", "void") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KBoolean", "Z", "boolean") \ + KOALA_INTEROP_TYPEDEF(func, lang, "OH_Boolean", "Z", "boolean") \ + KOALA_INTEROP_TYPEDEF(func, lang, "Ark_Boolean", "Z", "boolean") \ + KOALA_INTEROP_TYPEDEF(func, lang, "int32_t", "I", "int") \ + KOALA_INTEROP_TYPEDEF(func, lang, "uint32_t", "I", "int") \ + KOALA_INTEROP_TYPEDEF(func, lang, "int", "I", "int") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KInt", "I", "int") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KUInt", "I", "int") \ + KOALA_INTEROP_TYPEDEF(func, lang, "OH_Int32", "I", "int") \ + KOALA_INTEROP_TYPEDEF(func, lang, "OH_Int64", "J", "long") \ + KOALA_INTEROP_TYPEDEF(func, lang, "Ark_Int32", "I", "int") \ + KOALA_INTEROP_TYPEDEF(func, lang, "Ark_Int64", "J", "long") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KNativePointer", "J", "long") \ + KOALA_INTEROP_TYPEDEF(func, lang, "Ark_NativePointer", "J", "long") \ + KOALA_INTEROP_TYPEDEF(func, lang, "OH_NativePointer", "J", "long") \ + KOALA_INTEROP_TYPEDEF(func, lang, "float", "F", "float") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KFloat", "F", "float") \ + KOALA_INTEROP_TYPEDEF(func, lang, "Ark_Float32", "F", "float") \ + KOALA_INTEROP_TYPEDEF(func, lang, "double", "D", "double") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KDouble", "D", "double") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KInteropNumber", "D", "double") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KVMObjectHandle", "Ljava/lang/Object;", "Object") \ + KOALA_INTEROP_TYPEDEF(func, lang, "uint8_t*", "[B", "byte[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KByte*", "[B", "byte[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KInteropBuffer", "[B", "byte[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KShort*", "[S", "short[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KUShort*", "[S", "short[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "int32_t*", "[I", "int[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KInt*", "[I", "int[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KNativePointerArray", "[J", "long[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KInteropReturnBuffer", "[B", "byte[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "float*", "[F", "float[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KFloatArray", "[F", "float[]") \ + KOALA_INTEROP_TYPEDEF(func, lang, "KFloat*", "[F", "float[]") \ + KOALA_INTEROP_TYPEDEF_LS(func, lang, "KStringPtr", "Lstd/core/String;", "String", "Ljava/lang/String;", "String") \ + KOALA_INTEROP_TYPEDEF_LS(func, lang, "KStringArray", "[Lstd/core/String;", "String[]", "[Ljava/lang/String;", "String[]") \ + KOALA_INTEROP_TYPEDEF_LS(func, lang, "KLength", "Lstd/core/String;", "String", "Ljava/lang/String;", "String") + +std::string sigType(const std::string &type) { +#if KOALA_USE_PANDA_VM + KOALA_INTEROP_TYPEDEFS("sigType", "ets") +#elif KOALA_USE_JAVA_VM + KOALA_INTEROP_TYPEDEFS("sigType", "jni") +#endif + INTEROP_FATAL("Unhandled type: %s\n", type.c_str()); + return type; +} + +std::string codeType(const std::string &type) { +#if KOALA_USE_PANDA_VM + KOALA_INTEROP_TYPEDEFS("codeType", "ets") +#elif KOALA_USE_JAVA_VM + KOALA_INTEROP_TYPEDEFS("codeType", "jni") +#endif + INTEROP_FATAL("Unhandled type: %s\n", type.c_str()); + return ""; +} + +std::string convertType(const char* name, const char* koalaType) { + std::string result; + size_t current = 0, last = 0; + std::string input(koalaType); + std::vector tokens; + while ((current = input.find('|', last)) != std::string::npos) + { + auto token = input.substr(last, current - last); + tokens.push_back(token); + last = current + 1; + } + tokens.push_back(input.substr(last, input.length() - last)); + +#if KOALA_USE_PANDA_VM + + for (int i = 1; i < (int)tokens.size(); i++) + { + result.append(sigType(tokens[i])); + } + result.append(":"); + result.append(sigType(tokens[0])); + +#elif KOALA_USE_JAVA_VM + + result.append("("); + for (int i = 1; i < (int)tokens.size(); i++) + { + result.append(sigType(tokens[i])); + } + result.append(")"); + result.append(sigType(tokens[0])); + +#endif + +#ifdef KOALA_BUILD_FOR_SIGNATURES + #ifdef KOALA_USE_PANDA_VM + std::string params; + for (int i = 1; i < (int)tokens.size(); i++) + { + params.append("arg"); + params.append(std::to_string(i)); + params.append(": "); + params.append(codeType(tokens[i])); + if (i < (int)(tokens.size() - 1)) + params.append(", "); + } + fprintf(stderr, " static native %s(%s): %s;\n", name, params.c_str(), codeType(tokens[0]).c_str()); + #elif KOALA_USE_JAVA_VM + std::string params; + for (int i = 1; i < (int)tokens.size(); i++) + { + params.append(codeType(tokens[i])); + params.append(" arg"); + params.append(std::to_string(i)); + if (i < (int)(tokens.size() - 1)) + params.append(", "); + } + fprintf(stderr, " public static native %s %s(%s);\n", codeType(tokens[0]).c_str(), name, params.c_str()); + #endif +#endif + + return result; +} diff --git a/koala-wrapper/koalaui/interop/src/cpp/types/signatures.h b/koala-wrapper/koalaui/interop/src/cpp/types/signatures.h new file mode 100644 index 000000000..48a76f3d8 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/types/signatures.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SIGNATURES_H +#define _SIGNATURES_H + +#include + +std::string sigType(const std::string &type); +std::string codeType(const std::string &type); +std::string convertType(const char* name, const char* koalaType); + +#endif // _SIGNATURES_H diff --git a/koala-wrapper/koalaui/interop/src/cpp/vmloader.cc b/koala-wrapper/koalaui/interop/src/cpp/vmloader.cc new file mode 100644 index 000000000..995d2623c --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/vmloader.cc @@ -0,0 +1,638 @@ +/* + * 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 "interop-logging.h" +#include "dynamic-loader.h" +#include "koala-types.h" + +// DO NOT USE KOALA INTEROP MECHANISMS IN THIS FILE! + +#ifdef KOALA_JNI +#include "jni.h" +#endif + +#ifdef KOALA_ETS_NAPI +#include "etsapi.h" +#endif + +#if defined(KOALA_LINUX) || defined(KOALA_MACOS) || defined(KOALA_OHOS) +#include "sys/stat.h" +#include "dirent.h" +#endif + +#define OHOS_USER_LIBS "/data/storage/el1/bundle/libs" +#ifdef KOALA_OHOS_ARM32 +#define USE_SYSTEM_ARKVM 1 +#elif KOALA_OHOS_ARM64 +#define USE_SYSTEM_ARKVM 1 +#else +#define USE_SYSTEM_ARKVM 0 +#endif + +#if USE_SYSTEM_ARKVM +#define SYSTEM_ARK_STDLIB_PATH "/system/etc/etsstdlib.abc" +#endif + +void traverseDir(std::string root, std::vector& paths, int depth = 0); + +struct VMLibInfo { + const char* sdkPath; + const char* platform; + const char* lib; + const char* createVM; +}; + +#ifdef KOALA_JNI +const VMLibInfo javaVMLib = { + getenv("JAVA_HOME"), + #if defined(KOALA_LINUX) || defined(KOALA_MACOS) + "lib/server" + #elif KOALA_WINDOWS + "bin/server" + #else + #error "Unknown platform" + #endif + , + "jvm", + "JNI_CreateJavaVM", +}; +#endif + +#ifdef KOALA_ETS_NAPI +const VMLibInfo pandaVMLib = { + // sdkPath + #if defined(KOALA_OHOS) + #ifdef KOALA_OHOS_ARM32 + "/system/lib" + #elif KOALA_OHOS_ARM64 + "/system/lib64" + #else + OHOS_USER_LIBS + #endif + #else + getenv("PANDA_HOME") + #endif + , + + // platform + #ifdef KOALA_LINUX + #ifdef KOALA_LINUX_ARM64 + "linux_arm64_host_tools/lib" + #else + "linux_host_tools/lib" + #endif + #elif KOALA_MACOS + "macos_host_tools/lib" + #elif KOALA_WINDOWS + "_host_tools/lib" + #elif KOALA_OHOS_ARM64 + "arm64" + #elif KOALA_OHOS_ARM32 + "arm" + #else + #error "Unknown platform" + #endif + , + + // lib + "arkruntime" + , + + // createVM + "ETS_CreateVM" +}; +#endif + +struct VMInitArgs { + int version; + int nOptions; + void* options; +}; + +#define JAVA_VM_KIND 1 +#define PANDA_VM_KIND 2 +#define ES2PANDA_KIND 3 + +struct ForeignVMContext { + void* currentVMContext; + int32_t (*callSync)(void* vmContext, int32_t callback, int8_t* data, int32_t length); +}; + +struct VMEntry { + int vmKind; + void* env; + void* app; + void* enter; + void* emitEvent; + void* restartWith; + ForeignVMContext foreignVMContext; +}; + +VMEntry g_vmEntry = {}; + +typedef int (*createVM_t)(void** pVM, void** pEnv, void* vmInitArgs); +typedef int (*getVMs_t)(void** pVM, int32_t bufLen, int32_t* nVMs); + +#ifdef KOALA_WINDOWS +#define DLL_EXPORT __declspec(dllexport) +#else +#define DLL_EXPORT __attribute__ ((visibility ("default"))) +#endif + +int loadES2Panda(const char* appClassPath, const char* appLibPath) { + fprintf(stderr, "native: es2panda %s\n", appClassPath); + return 0; +} + +static int ArkMobileLog(int id, int level, const char *component, const char *fmt, const char *msg) { + LOGE("ArkMobileLog: %" LOG_PUBLIC "s", msg); + return 0; +} + +extern "C" DLL_EXPORT KInt LoadVirtualMachine(KInt vmKind, const char* appClassPath, const char* appLibPath, const ForeignVMContext* foreignVMContext) { + if (vmKind == ES2PANDA_KIND) { + return loadES2Panda(appClassPath, appLibPath); + } + + const VMLibInfo* thisVM = + #ifdef KOALA_JNI + (vmKind == JAVA_VM_KIND) ? &javaVMLib : + #endif + #ifdef KOALA_ETS_NAPI + (vmKind == PANDA_VM_KIND) ? &pandaVMLib : + #endif + nullptr; + + if (!thisVM) { + LOGE("Unknown VM kind: %" LOG_PUBLIC "d\n (possibly %" LOG_PUBLIC "s is compiled without expected flags)", vmKind, __FILE__); + return -1; + } + + LOGI("Starting VM %" LOG_PUBLIC "d with classpath=%" LOG_PUBLIC "s native=%" LOG_PUBLIC "s", vmKind, appClassPath, appLibPath); + + std::string libPath = +#if USE_SYSTEM_ARKVM + std::string(thisVM->sdkPath) + "/" + libName(thisVM->lib) +#elif defined(KOALA_LINUX) || defined(KOALA_MACOS) || defined(KOALA_WINDOWS) + std::string(thisVM->sdkPath) + "/" + std::string(thisVM->platform) + "/" + libName(thisVM->lib) +#elif defined(KOALA_OHOS) + std::string(OHOS_USER_LIBS) + "/" + libName(thisVM->lib) +#else + #error "Library path not specified for this platform" +#endif + ; + void *handle = loadLibrary(libPath); + if (!handle) { + LOGE("Cannot load library %" LOG_PUBLIC "s: %" LOG_PUBLIC "s\n", libPath.c_str(), libraryError()); + return -1; + } + + createVM_t createVM = (createVM_t)findSymbol(handle, thisVM->createVM); + getVMs_t getVMs = (getVMs_t)findSymbol(handle, "ETS_GetCreatedVMs"); + + if (!createVM) { + LOGE("Cannot find %" LOG_PUBLIC "s\n", thisVM->createVM); + return -1; + } + + void* vm = nullptr; + void* env = nullptr; + int32_t nVMs = 0; + int result = 0; + +#ifdef KOALA_JNI + if (vmKind == JAVA_VM_KIND) { + JavaVMInitArgs javaVMArgs; + javaVMArgs.version = JNI_VERSION_10; + javaVMArgs.ignoreUnrecognized = false; + std::vector javaVMOptions; + javaVMOptions = { + {(char*)strdup((std::string("-Djava.class.path=") + appClassPath).c_str())}, + {(char*)strdup((std::string("-Djava.library.path=") + appLibPath).c_str())}, + }; + javaVMArgs.nOptions = javaVMOptions.size(); + javaVMArgs.options = javaVMOptions.data(); + g_vmEntry.vmKind = JAVA_VM_KIND; + result = createVM(&vm, &env, &javaVMArgs); + } +#endif + +#ifdef KOALA_ETS_NAPI + if (vmKind == PANDA_VM_KIND) { + EtsVMInitArgs pandaVMArgs; + pandaVMArgs.version = ETS_NAPI_VERSION_1_0; + std::vector etsVMOptions; + std::vector files; + traverseDir(std::string(appClassPath), files); + std::sort(files.begin(), files.end()); + etsVMOptions = { +#if USE_SYSTEM_ARKVM + {EtsOptionType::ETS_BOOT_FILE, SYSTEM_ARK_STDLIB_PATH}, +#elif defined(KOALA_OHOS) + {EtsOptionType::ETS_BOOT_FILE, (std::string(OHOS_USER_LIBS) + "/" + "etsstdlib.abc").c_str() }, + +#elif defined(KOALA_LINUX) || defined(KOALA_MACOS) || defined(KOALA_WINDOWS) + {EtsOptionType::ETS_BOOT_FILE, (char*)strdup((std::string(thisVM->sdkPath) + "/ets/etsstdlib.abc").c_str())}, +#endif + }; + for (const std::string& path : files) { + etsVMOptions.push_back({EtsOptionType::ETS_BOOT_FILE, (char*)strdup(path.c_str())}); + } + etsVMOptions.push_back({EtsOptionType::ETS_NATIVE_LIBRARY_PATH, (char*)strdup(std::string(appLibPath).c_str())}); + etsVMOptions.push_back({EtsOptionType::ETS_VERIFICATION_MODE, "on-the-fly"}); + etsVMOptions.push_back({EtsOptionType::ETS_NO_JIT, nullptr}); + etsVMOptions.push_back({EtsOptionType::ETS_MOBILE_LOG, (void*)ArkMobileLog}); + etsVMOptions.push_back({EtsOptionType::ETS_AOT, nullptr}); + // etsVMOptions.push_back({EtsOptionType::ETS_LOG_LEVEL, "info"}); + pandaVMArgs.nOptions = etsVMOptions.size(); + pandaVMArgs.options = etsVMOptions.data(); + g_vmEntry.vmKind = PANDA_VM_KIND; + + result = getVMs ? getVMs(&vm, 1, &nVMs) : 0; + if (nVMs != 0) { + __EtsVM* vmInstance = (__EtsVM*)vm; + EtsEnv* pEnv = nullptr; + vmInstance->GetEnv(&pEnv, ETS_NAPI_VERSION_1_0); + env = static_cast(pEnv); + } else { + result = createVM(&vm, &env, &pandaVMArgs); + } + + } +#endif + + if (result != 0) { + LOGE("Error creating a VM of kind %" LOG_PUBLIC "d: %" LOG_PUBLIC "d\n", vmKind, result); + return result; + } + g_vmEntry.env = env; + g_vmEntry.foreignVMContext = *foreignVMContext; + return 0; +} + +struct AppInfo { + const char* className; + const char* createMethodName; + const char* createMethodSig; + const char* startMethodName; + const char* startMethodSig; + const char* enterMethodName; + const char* enterMethodSig; + const char* emitEventMethodName; + const char* emitEventMethodSig; + const char* restartWithMethodName; + const char* restartWithMethodSig; +}; + +#ifdef KOALA_JNI +const AppInfo javaAppInfo = { + "org/koalaui/arkoala/Application", + "createApplication", + "(Ljava/lang/String;Ljava/lang/String;)Lorg/koalaui/arkoala/Application;", + "start", + "()J", + "enter", + "(IIJ)Z", + "emitEvent", + "(IIII)Ljava/lang/String;", +}; +#endif + +#ifdef KOALA_ETS_NAPI +const AppInfo pandaAppInfo = { + "@koalaui/arkts-arkui/Application/Application", + "createApplication", + "Lstd/core/String;Lstd/core/String;Z:L@koalaui/arkts-arkui/Application/Application;", + "start", + ":J", + "enter", + "IIJ:Z", + "emitEvent", + "IIII:Lstd/core/String;", +}; +const AppInfo harnessAppInfo = { + "@koalaui/ets-harness/src/EtsHarnessApplication/EtsHarnessApplication", + "createApplication", + "Lstd/core/String;Lstd/core/String;Z:L@koalaui/ets-harness/src/EtsHarnessApplication/EtsHarnessApplication;", + "start", + ":J", + "enter", + "II:Z", + "emitEvent", + "IIII:Lstd/core/String;", + "restartWith", + "Lstd/core/String;:V" +}; +#endif + +extern "C" DLL_EXPORT KNativePointer StartApplication(const char* appUrl, const char* appParams) { + const auto isTestEnv = std::string(appUrl) == "EtsHarness"; + const AppInfo* appInfo = + #ifdef KOALA_JNI + (g_vmEntry.vmKind == JAVA_VM_KIND) ? &javaAppInfo : + #endif + #ifdef KOALA_ETS_NAPI + (g_vmEntry.vmKind == PANDA_VM_KIND) ? isTestEnv ? &harnessAppInfo : &pandaAppInfo : + #endif + nullptr; + + if (!appInfo) { + LOGE("No appInfo provided for VM kind %" LOG_PUBLIC "d (recompile vmloader.cc with the missing flags)\n", g_vmEntry.vmKind); + return nullptr; + } + + LOGI("Starting application %" LOG_PUBLIC "s with params %" LOG_PUBLIC "s", appUrl, appParams); + +#ifdef KOALA_JNI + if (g_vmEntry.vmKind == JAVA_VM_KIND) { + JNIEnv* jEnv = (JNIEnv*)(g_vmEntry.env); + jclass appClass = jEnv->FindClass(appInfo->className); + if (!appClass) { + LOGE("Cannot load main class %s\n", appInfo->className); + return nullptr; + } + jmethodID create = jEnv->GetStaticMethodID(appClass, appInfo->createMethodName, appInfo->createMethodSig); + if (!create) { + LOGE("Cannot find create method %s\n", appInfo->createMethodName); + return nullptr; + } + auto app = jEnv->NewGlobalRef(jEnv->CallStaticObjectMethod(appClass, create, jEnv->NewStringUTF(appUrl), jEnv->NewStringUTF(appParams))); + g_vmEntry.app = app; + auto start = jEnv->GetMethodID(appClass, appInfo->startMethodName, appInfo->startMethodSig); + if (!start) { + LOGE("Cannot find start method \"%s %s\"\n", appInfo->startMethodName, appInfo->startMethodSig); + return nullptr; + } + g_vmEntry.enter = (void*)(jEnv->GetMethodID(appClass, appInfo->enterMethodName, appInfo->enterMethodSig)); + if (!g_vmEntry.enter) { + LOGE("Cannot find enter method %s\n", appInfo->enterMethodName); + return nullptr; + } + g_vmEntry.emitEvent = (void*)(jEnv->GetMethodID(appClass, appInfo->emitEventMethodName, appInfo->emitEventMethodSig)); + if (!g_vmEntry.emitEvent) { + LOGE("Cannot find emitEvent method %s\n", appInfo->emitEventMethodName); + return nullptr; + } + return reinterpret_cast(jEnv->CallLongMethod( + app, start)); + } +#endif +#ifdef KOALA_ETS_NAPI + if (g_vmEntry.vmKind == PANDA_VM_KIND) { + EtsEnv* etsEnv = (EtsEnv*)g_vmEntry.env; + ets_class appClass = etsEnv->FindClass(appInfo->className); + if (!appClass) { + LOGE("Cannot load main class %" LOG_PUBLIC "s\n", appInfo->className); + return nullptr; + } + ets_method create = etsEnv->GetStaticp_method(appClass, appInfo->createMethodName, appInfo->createMethodSig); + if (!create) { + LOGE("Cannot find create method %" LOG_PUBLIC "s\n", appInfo->createMethodName); + if (etsEnv->ErrorCheck()) { + etsEnv->ErrorDescribe(); + etsEnv->ErrorClear(); + } + return nullptr; + } +#if defined (KOALA_OHOS_ARM64) + auto useNativeLog = true; +#else + auto useNativeLog = false; +#endif + auto app = etsEnv->NewGlobalRef(etsEnv->CallStaticObjectMethod( + appClass, create, + etsEnv->NewStringUTF(appUrl), etsEnv->NewStringUTF(appParams), + useNativeLog + )); + if (!app) { + LOGE("createApplication returned null"); + if (etsEnv->ErrorCheck()) { + etsEnv->ErrorDescribe(); + etsEnv->ErrorClear(); + } + return nullptr; + } + g_vmEntry.app = (void*)app; + auto start = etsEnv->Getp_method(appClass, appInfo->startMethodName, appInfo->startMethodSig); + g_vmEntry.enter = (void*)(etsEnv->Getp_method(appClass, appInfo->enterMethodName, nullptr /*appInfo->enterMethodSig */)); + if (!g_vmEntry.enter) { + LOGE("Cannot find enter method %" LOG_PUBLIC "s", appInfo->enterMethodName); + if (etsEnv->ErrorCheck()) { + etsEnv->ErrorDescribe(); + etsEnv->ErrorClear(); + } + return nullptr; + } + g_vmEntry.emitEvent = (void*)(etsEnv->Getp_method(appClass, appInfo->emitEventMethodName, appInfo->emitEventMethodSig)); + if (!g_vmEntry.emitEvent) { + LOGE("Cannot find enter emitEvent %" LOG_PUBLIC "s", appInfo->emitEventMethodSig); + if (etsEnv->ErrorCheck()) { + etsEnv->ErrorDescribe(); + etsEnv->ErrorClear(); + } + return nullptr; + } + if (isTestEnv) { + g_vmEntry.restartWith = (void*)(etsEnv->Getp_method(appClass, appInfo->restartWithMethodName, appInfo->restartWithMethodSig)); + if (!g_vmEntry.restartWith) { + LOGE("Cannot find enter restartWith %" LOG_PUBLIC "s", appInfo->restartWithMethodSig); + if (etsEnv->ErrorCheck()) { + etsEnv->ErrorDescribe(); + etsEnv->ErrorClear(); + } + return nullptr; + } + } + // TODO: pass app entry point! + return reinterpret_cast(etsEnv->CallLongMethod((ets_object)(app), start)); + } +#endif + return nullptr; +} + +extern "C" DLL_EXPORT KBoolean RunApplication(const KInt arg0, const KInt arg1) { +#ifdef KOALA_JNI + if (g_vmEntry.vmKind == JAVA_VM_KIND) { + JNIEnv* jEnv = (JNIEnv*)(g_vmEntry.env); + auto result = jEnv->CallBooleanMethod( + (jobject)(g_vmEntry.app), + (jmethodID)(g_vmEntry.enter), + (jint)arg0, + (jint)arg1, + (int64_t)(intptr_t)(&g_vmEntry.foreignVMContext) + ); + if (jEnv->ExceptionCheck()) { + jEnv->ExceptionDescribe(); + jEnv->ExceptionClear(); + } + return result; + } +#endif +#ifdef KOALA_ETS_NAPI + if (g_vmEntry.vmKind == PANDA_VM_KIND) { + EtsEnv* etsEnv = (EtsEnv*)(g_vmEntry.env); + if (!g_vmEntry.enter) { + LOGE("Cannot find enter method"); + return -1; + } + auto result = etsEnv->CallBooleanMethod( + (ets_object)(g_vmEntry.app), + (ets_method)(g_vmEntry.enter), + (ets_int)arg0, + (ets_int)arg1, + (int64_t)(intptr_t)(&g_vmEntry.foreignVMContext) + ); + if (etsEnv->ErrorCheck()) { + LOGE("Calling enter() method gave an error"); + etsEnv->ErrorDescribe(); + etsEnv->ErrorClear(); + } + return result; + } + #endif + return 1; +} + +extern "C" DLL_EXPORT const char* EmitEvent(const KInt type, const KInt target, const KInt arg0, const KInt arg1) { +#ifdef KOALA_JNI + if (g_vmEntry.vmKind == JAVA_VM_KIND) { + JNIEnv* jEnv = (JNIEnv*)(g_vmEntry.env); + if (!g_vmEntry.emitEvent) { + LOGE("Cannot find emitEvent method"); + return "-1"; + } + auto rv = (jstring)jEnv->CallObjectMethod( + (jobject)(g_vmEntry.app), + (jmethodID)(g_vmEntry.emitEvent), + (jint)type, + (jint)target, + (jint)arg0, + (jint)arg1 + ); + if (jEnv->ExceptionCheck()) { + jEnv->ExceptionDescribe(); + jEnv->ExceptionClear(); + } + const char *result = jEnv->GetStringUTFChars(rv, 0); + return result; + } +#endif +#ifdef KOALA_ETS_NAPI + if (g_vmEntry.vmKind == PANDA_VM_KIND) { + EtsEnv* etsEnv = (EtsEnv*)(g_vmEntry.env); + if (!g_vmEntry.emitEvent) { + LOGE("Cannot find emitEvent method"); + return "-1"; + } + auto rv = (ets_string)etsEnv->CallObjectMethod( + (ets_object)(g_vmEntry.app), + (ets_method)(g_vmEntry.emitEvent), + (ets_int)type, + (ets_int)target, + (ets_int)arg0, + (ets_int)arg1 + ); + if (etsEnv->ErrorCheck()) { + LOGE("Calling emitEvent() method gave an error"); + etsEnv->ErrorDescribe(); + etsEnv->ErrorClear(); + } + const char *result = etsEnv->GetStringUTFChars(rv, 0); + return result; + } + #endif + return "-1"; +} + +extern "C" DLL_EXPORT void RestartWith(const char* page) { +#ifdef KOALA_JNI + if (g_vmEntry.vmKind == JAVA_VM_KIND) { + JNIEnv* jEnv = (JNIEnv*)(g_vmEntry.env); + if (!g_vmEntry.restartWith) { + LOGE("Cannot find restartWith method"); + return; + } + jEnv->CallVoidMethod( + (jobject)(g_vmEntry.app), + (jmethodID)(g_vmEntry.restartWith), + jEnv->NewStringUTF(page) + ); + if (jEnv->ExceptionCheck()) { + jEnv->ExceptionDescribe(); + jEnv->ExceptionClear(); + } + } +#endif +#ifdef KOALA_ETS_NAPI + if (g_vmEntry.vmKind == PANDA_VM_KIND) { + EtsEnv* etsEnv = (EtsEnv*)(g_vmEntry.env); + if (!g_vmEntry.restartWith) { + LOGE("Cannot find restartWith method"); + return; + } + etsEnv->CallVoidMethod( + (ets_object)(g_vmEntry.app), + (ets_method)(g_vmEntry.restartWith), + etsEnv->NewStringUTF(page) + ); + if (etsEnv->ErrorCheck()) { + LOGE("Calling restartWith() method gave an error"); + etsEnv->ErrorDescribe(); + etsEnv->ErrorClear(); + } + } + #endif +} + +void traverseDir(std::string root, std::vector& paths, int depth) { + if (depth >= 50) { + return; + } +#if defined(KOALA_LINUX) || defined(KOALA_MACOS) || defined(KOALA_OHOS) + std::string suffix = ".abc"; + #if defined(KOALA_OHOS) + suffix += ".so"; + #endif + DIR* directory = opendir(root.c_str()); + if (!directory) { + LOGE("Cannot open dir %" LOG_PUBLIC "s\n", root.c_str()); + return; + } + struct dirent* ent = NULL; + struct stat statbuf; + + LOGI("Searching for *%" LOG_PUBLIC "s in %" LOG_PUBLIC "s\n", suffix.c_str(), root.c_str()); + while ((ent = readdir(directory)) != nullptr) { + std::string filename = std::string(ent->d_name); + if (filename == "." || filename == "..") { + continue; + } + std::string filepath = root + "/" + filename; + int rv = stat(filepath.c_str(), &statbuf); + if (rv < 0) continue; + if (filepath.size() >= suffix.size() && filepath.substr(filepath.size() - suffix.size()) == suffix && (statbuf.st_mode & S_IFMT) == S_IFREG) { + paths.push_back(filepath); + } + if ((statbuf.st_mode & S_IFMT) == S_IFDIR) { + traverseDir(filepath, paths, depth + 1); + } + } + closedir(directory); +#endif +} diff --git a/koala-wrapper/koalaui/interop/src/cpp/wasm/convertors-wasm.h b/koala-wrapper/koalaui/interop/src/cpp/wasm/convertors-wasm.h new file mode 100644 index 000000000..eea97a98e --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/cpp/wasm/convertors-wasm.h @@ -0,0 +1,778 @@ +/* + * Copyright (c) 2022-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. + */ + +#pragma once + +#include "koala-types.h" + +#include +#include +#define KOALA_INTEROP_EXPORT EMSCRIPTEN_KEEPALIVE extern "C" + +template +struct InteropTypeConverter { + using InteropType = T; + static T convertFrom(InteropType value) { return value; } + static InteropType convertTo(T value) { return value; } +}; + +template<> +struct InteropTypeConverter { + using InteropType = const uint8_t*; + static KStringPtr convertFrom(InteropType value) { + KStringPtr result; + if (value == nullptr) { + return KStringPtr(); + } else { + int len = (value[0] | (value[1] << 8) | (value[2] << 16) | (value[3] << 24)); + return KStringPtr((const char*)(value + 4), len, true); + } + } + static InteropType convertTo(KStringPtr value) = delete; +}; + +template +inline T getArgument(typename InteropTypeConverter::InteropType arg) { + return InteropTypeConverter::convertFrom(arg); +} + +template +inline typename InteropTypeConverter::InteropType makeResult(T value) { + return InteropTypeConverter::convertTo(value); +} + +// TODO: Rewrite all others to typed convertors. + +#define KOALA_INTEROP_0(name, Ret) \ +KOALA_INTEROP_EXPORT Ret name() { \ + KOALA_MAYBE_LOG(name) \ + return makeResult(impl_##name()); \ +} + +#define KOALA_INTEROP_1(name, Ret, P0) \ +KOALA_INTEROP_EXPORT Ret name(InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + return makeResult(impl_##name(p0)); \ +} + +#define KOALA_INTEROP_2(name, Ret, P0, P1) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + return makeResult(impl_##name(p0, p1)); \ +} + +#define KOALA_INTEROP_3(name, Ret, P0, P1, P2) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + return makeResult(impl_##name(p0, p1, p2)); \ +} + +#define KOALA_INTEROP_4(name, Ret, P0, P1, P2, P3) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + return makeResult(impl_##name(p0, p1, p2, p3)); \ +} + +#define KOALA_INTEROP_5(name, Ret, P0, P1, P2, P3, P4) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4)); \ +} + +#define KOALA_INTEROP_6(name, Ret, P0, P1, P2, P3, P4, P5) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5)); \ +} + +#define KOALA_INTEROP_7(name, Ret, P0, P1, P2, P3, P4, P5, P6) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6)); \ +} + +#define KOALA_INTEROP_8(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7)); \ +} + +#define KOALA_INTEROP_9(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8)); \ +} + +#define KOALA_INTEROP_10(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)); \ +} + +#define KOALA_INTEROP_11(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)); \ +} + +#define KOALA_INTEROP_12(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11)); \ +} + +#define KOALA_INTEROP_13(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + P12 p12 = getArgument(_p12); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12)); \ +} + +#define KOALA_INTEROP_14(name, Ret, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3, \ + InteropTypeConverter::InteropType _p4, \ + InteropTypeConverter::InteropType _p5, \ + InteropTypeConverter::InteropType _p6, \ + InteropTypeConverter::InteropType _p7, \ + InteropTypeConverter::InteropType _p8, \ + InteropTypeConverter::InteropType _p9, \ + InteropTypeConverter::InteropType _p10, \ + InteropTypeConverter::InteropType _p11, \ + InteropTypeConverter::InteropType _p12, \ + InteropTypeConverter::InteropType _p13 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + P12 p12 = getArgument(_p12); \ + P13 p13 = getArgument(_p13); \ + return makeResult(impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13)); \ +} + + + +#define KOALA_INTEROP_V0(name) \ +KOALA_INTEROP_EXPORT void name() { \ + KOALA_MAYBE_LOG(name) \ + impl_##name(); \ + return; \ +} + +#define KOALA_INTEROP_V1(name, P0) \ +KOALA_INTEROP_EXPORT void name(typename InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + impl_##name(p0); \ + return; \ +} + +#define KOALA_INTEROP_V2(name, P0, P1) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + impl_##name(p0, p1); \ + return; \ +} + +#define KOALA_INTEROP_V3(name, P0, P1, P2) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + impl_##name(p0, p1, p2); \ + return; \ +} + +#define KOALA_INTEROP_V4(name, P0, P1, P2, P3) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + impl_##name(p0, p1, p2, p3); \ + return; \ +} + +#define KOALA_INTEROP_V5(name, P0, P1, P2, P3, P4) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + impl_##name(p0, p1, p2, p3, p4); \ + return; \ +} + +#define KOALA_INTEROP_V6(name, P0, P1, P2, P3, P4, P5) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + impl_##name(p0, p1, p2, p3, p4, p5); \ + return; \ +} + +#define KOALA_INTEROP_V7(name, P0, P1, P2, P3, P4, P5, P6) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6); \ + return; \ +} + +#define KOALA_INTEROP_V8(name, P0, P1, P2, P3, P4, P5, P6, P7) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7); \ + return; \ +} + +#define KOALA_INTEROP_V9(name, P0, P1, P2, P3, P4, P5, P6, P7, P8) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8); \ + return; \ +} + +#define KOALA_INTEROP_V10(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \ + return; \ +} + +#define KOALA_INTEROP_V11(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9, \ + typename InteropTypeConverter::InteropType _p10 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); \ + return; \ +} + +#define KOALA_INTEROP_V12(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9, \ + typename InteropTypeConverter::InteropType _p10, \ + typename InteropTypeConverter::InteropType _p11 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); \ + return; \ +} + +#define KOALA_INTEROP_V13(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9, \ + typename InteropTypeConverter::InteropType _p10, \ + typename InteropTypeConverter::InteropType _p11, \ + typename InteropTypeConverter::InteropType _p12 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + P12 p12 = getArgument(_p12); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); \ + return; \ +} + +#define KOALA_INTEROP_V14(name, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) \ +KOALA_INTEROP_EXPORT void name( \ + typename InteropTypeConverter::InteropType _p0, \ + typename InteropTypeConverter::InteropType _p1, \ + typename InteropTypeConverter::InteropType _p2, \ + typename InteropTypeConverter::InteropType _p3, \ + typename InteropTypeConverter::InteropType _p4, \ + typename InteropTypeConverter::InteropType _p5, \ + typename InteropTypeConverter::InteropType _p6, \ + typename InteropTypeConverter::InteropType _p7, \ + typename InteropTypeConverter::InteropType _p8, \ + typename InteropTypeConverter::InteropType _p9, \ + typename InteropTypeConverter::InteropType _p10, \ + typename InteropTypeConverter::InteropType _p11, \ + typename InteropTypeConverter::InteropType _p12, \ + typename InteropTypeConverter::InteropType _p13 \ +) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + P4 p4 = getArgument(_p4); \ + P5 p5 = getArgument(_p5); \ + P6 p6 = getArgument(_p6); \ + P7 p7 = getArgument(_p7); \ + P8 p8 = getArgument(_p8); \ + P9 p9 = getArgument(_p9); \ + P10 p10 = getArgument(_p10); \ + P11 p11 = getArgument(_p11); \ + P12 p12 = getArgument(_p12); \ + P13 p13 = getArgument(_p13); \ + impl_##name(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); \ + return; \ +} + +#define KOALA_INTEROP_CTX_1(name, Ret, P0) \ +KOALA_INTEROP_EXPORT Ret name(InteropTypeConverter::InteropType _p0) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + return makeResult(impl_##name(nullptr, p0)); \ +} + +#define KOALA_INTEROP_CTX_2(name, Ret, P0, P1) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + return makeResult(impl_##name(nullptr, p0, p1)); \ +} + +#define KOALA_INTEROP_CTX_3(name, Ret, P0, P1, P2) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + return makeResult(impl_##name(nullptr, p0, p1, p2)); \ +} + +#define KOALA_INTEROP_CTX_4(name, Ret, P0, P1, P2, P3) \ +KOALA_INTEROP_EXPORT Ret name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + return makeResult(impl_##name(nullptr, p0, p1, p2, p3)); \ +} + +#define KOALA_INTEROP_CTX_V3(name, P0, P1, P2) \ +KOALA_INTEROP_EXPORT void name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + impl_##name(nullptr, p0, p1, p2); \ +} + +#define KOALA_INTEROP_CTX_V4(name, P0, P1, P2, P3) \ +KOALA_INTEROP_EXPORT void name( \ + InteropTypeConverter::InteropType _p0, \ + InteropTypeConverter::InteropType _p1, \ + InteropTypeConverter::InteropType _p2, \ + InteropTypeConverter::InteropType _p3) { \ + KOALA_MAYBE_LOG(name) \ + P0 p0 = getArgument(_p0); \ + P1 p1 = getArgument(_p1); \ + P2 p2 = getArgument(_p2); \ + P3 p3 = getArgument(_p3); \ + impl_##name(nullptr, p0, p1, p2, p3); \ +} + +#define KOALA_INTEROP_THROW(vmContext, object, ...) \ + do { \ + assert(false); /* TODO: implement*/ \ + return __VA_ARGS__; \ + } while (0) + +#define KOALA_INTEROP_THROW_STRING(vmContext, message, ...) \ + do { \ + assert(false); /* TODO: implement*/ \ + return __VA_ARGS__; \ + } while (0) diff --git a/koala-wrapper/koalaui/interop/src/interop/DeserializerBase.ts b/koala-wrapper/koalaui/interop/src/interop/DeserializerBase.ts new file mode 100644 index 000000000..af06948a3 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/DeserializerBase.ts @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CustomTextDecoder, float32, int32, int64 } from "@koalaui/common" +import { Tags, CallbackResource } from "./SerializerBase"; +import { pointer } from "./InteropTypes" +import { InteropNativeModule } from "./InteropNativeModule" + +export class DeserializerBase { + private position = 0 + private readonly buffer: ArrayBuffer + private readonly length: int32 + private view: DataView + private static textDecoder = new CustomTextDecoder() + private static customDeserializers: CustomDeserializer | undefined = undefined + + static registerCustomDeserializer(deserializer: CustomDeserializer) { + let current = DeserializerBase.customDeserializers + if (current == undefined) { + DeserializerBase.customDeserializers = deserializer + } else { + while (current.next != undefined) { + current = current.next + } + current.next = deserializer + } + } + + constructor(buffer: ArrayBuffer, length: int32) { + this.buffer = buffer + this.length = length + this.view = new DataView(this.buffer) + } + + static get( + factory: (args: Uint8Array, length: int32) => T, + args: Uint8Array, length: int32): T { + + // TBD: Use cache + return factory(args, length); + } + + asArray(position?: number, length?: number): Uint8Array { + return new Uint8Array(this.buffer, position, length) + } + + currentPosition(): int32 { + return this.position + } + + resetCurrentPosition(): void { + this.position = 0 + } + + private checkCapacity(value: int32) { + if (value > this.length) { + throw new Error(`${value} is less than remaining buffer length`) + } + } + + readInt8(): int32 { + this.checkCapacity(1) + const value = this.view.getInt8(this.position) + this.position += 1 + return value + } + + readInt32(): int32 { + this.checkCapacity(4) + const value = this.view.getInt32(this.position, true) + this.position += 4 + return value + } + + readInt64(): int64 { + this.checkCapacity(8) + const value = this.view.getBigInt64(this.position, true) + this.position += 8 + return Number(value) + } + + readPointer(): pointer { + this.checkCapacity(8) + const value = this.view.getBigInt64(this.position, true) + this.position += 8 + return value + } + + readFloat32(): float32 { + this.checkCapacity(4) + const value = this.view.getFloat32(this.position, true) + this.position += 4 + return value + } + + readBoolean(): boolean { + this.checkCapacity(1) + const value = this.view.getInt8(this.position) + this.position += 1 + return value == 1 + } + + readFunction(): any { + // TODO: not exactly correct. + const id = this.readInt32() + return id + } + + readMaterialized(): object { + const ptr = this.readPointer() + return { ptr: ptr } + } + + readString(): string { + const length = this.readInt32() + this.checkCapacity(length) + // read without null-terminated byte + const value = DeserializerBase.textDecoder.decode(this.asArray(this.position, length - 1)); + this.position += length + return value + } + + readCustomObject(kind: string): any { + let current = DeserializerBase.customDeserializers + while (current) { + if (current.supports(kind)) { + return current.deserialize(this, kind) + } + current = current.next + } + // consume tag + const tag = this.readInt8() + return undefined + } + + readNumber(): number | undefined { + const tag = this.readInt8() + switch (tag) { + case Tags.UNDEFINED: + return undefined; + case Tags.INT32: + return this.readInt32() + case Tags.FLOAT32: + return this.readFloat32() + default: + throw new Error(`Unknown number tag: ${tag}`) + break + } + } + + readCallbackResource(): CallbackResource { + return { + resourceId: this.readInt32(), + hold: this.readPointer(), + release: this.readPointer(), + } + } + + static lengthUnitFromInt(unit: int32): string { + let suffix: string + switch (unit) { + case 0: + suffix = "px" + break + case 1: + suffix = "vp" + break + case 3: + suffix = "%" + break + case 4: + suffix = "lpx" + break + default: + suffix = "" + } + return suffix + } + readBuffer(): ArrayBuffer { + const resource = this.readCallbackResource() + const data = this.readPointer() + const length = this.readInt64() + + return InteropNativeModule._MaterializeBuffer(data, length, resource.resourceId, resource.hold, resource.release) + } +} + +export abstract class CustomDeserializer { + protected constructor(protected supported: Array) { + } + + supports(kind: string): boolean { + return this.supported.includes(kind) + } + + abstract deserialize(serializer: DeserializerBase, kind: string): any + + next: CustomDeserializer | undefined = undefined +} + +class DateDeserializer extends CustomDeserializer { + constructor() { + super(["Date"]); + } + + deserialize(serializer: DeserializerBase, kind: string): any { + return new Date(serializer.readString()) + } +} +DeserializerBase.registerCustomDeserializer(new DateDeserializer()) diff --git a/koala-wrapper/koalaui/interop/src/interop/Finalizable.ts b/koala-wrapper/koalaui/interop/src/interop/Finalizable.ts new file mode 100644 index 000000000..dc0e8a980 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/Finalizable.ts @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Wrapper, nullptr, isNullPtr } from "./Wrapper" +import { finalizerRegister, finalizerUnregister, Thunk } from "@koalaui/common" +import { InteropNativeModule } from "./InteropNativeModule" +import { pointer } from "./InteropTypes" + +export class NativeThunk implements Thunk { + finalizer: pointer + obj: pointer + name: string|undefined + + constructor(obj: pointer, finalizer: pointer, name?: string) { + this.finalizer = finalizer + this.obj = obj + this.name = name + } + + clean() { + if (!isNullPtr(this.obj)) { + this.destroyNative(this.obj, this.finalizer) + } + this.obj = nullptr + } + + destroyNative(ptr: pointer, finalizer: pointer): void { + InteropNativeModule._InvokeFinalizer(ptr, finalizer) + } +} + +/** + * Class with the custom finalizer, usually used to release a native peer. + * Do not use directly, only via subclasses. + */ +export class Finalizable extends Wrapper { + finalizer: pointer + cleaner?: NativeThunk = undefined + managed: boolean + constructor(ptr: pointer, finalizer: pointer, managed: boolean = true) { + super(ptr) + this.finalizer = finalizer + this.managed = managed + const handle = this.createHandle() + + if (this.managed) { + // TODO: reenable exception. + if (this.ptr == nullptr) return // throw new Error("Can't have nullptr ptr ${}") + if (this.finalizer == nullptr) throw new Error("Managed finalizer is 0") + + const thunk = this.makeNativeThunk(ptr, finalizer, handle) + finalizerRegister(this, thunk) + this.cleaner = thunk + } + } + + createHandle(): string | undefined { + return undefined + } + + makeNativeThunk(ptr: pointer, finalizer: pointer, handle: string | undefined): NativeThunk { + return new NativeThunk(ptr, finalizer, handle) + } + + close() { + if (isNullPtr(this.ptr)) { + throw new Error(`Closing a closed object: ` + this.toString()) + } else if (this.cleaner == null) { + throw new Error(`No thunk assigned to ` + this.toString()) + } else { + finalizerUnregister(this) + this.cleaner.clean() + this.cleaner = undefined + this.ptr = nullptr + } + } + + release(): pointer { + finalizerUnregister(this) + if (this.cleaner) + this.cleaner.obj = nullptr + let result = this.ptr + this.ptr = nullptr + return result + } + + resetPeer(pointer: pointer) { + if (this.managed) throw new Error("Can only reset peer for an unmanaged object") + this.ptr = pointer + } + + use(body: (value: Finalizable) => R): R { + let result = body(this) + this.close() + return result + } +} diff --git a/koala-wrapper/koalaui/interop/src/interop/InteropNativeModule.ts b/koala-wrapper/koalaui/interop/src/interop/InteropNativeModule.ts new file mode 100644 index 000000000..b3677da97 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/InteropNativeModule.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common"; +import { KPointer, KStringPtr, KUint8ArrayPtr } from "./InteropTypes"; +import { loadNativeModuleLibrary } from "./loadLibraries"; + +export class InteropNativeModule { + public static _SetCallbackDispatcher(dispatcher: (id: int32, args: Uint8Array, length: int32) => int32): void { throw "method not loaded" } + public static _CleanCallbackDispatcher(): void { throw "method not loaded" } + + public static _GetGroupedLog(index: int32): KPointer { throw "method not loaded" } + public static _StartGroupedLog(index: int32): void { throw "method not loaded" } + public static _StopGroupedLog(index: int32): void { throw "method not loaded" } + public static _AppendGroupedLog(index: int32, message: string): void { throw "method not loaded" } + public static _PrintGroupedLog(index: int32): void { throw "method not loaded" } + public static _GetStringFinalizer(): KPointer { throw "method not loaded" } + public static _InvokeFinalizer(ptr1: KPointer, ptr2: KPointer): void { throw "method not loaded" } + public static _GetPtrVectorElement(ptr1: KPointer, arg: int32): KPointer { throw "method not loaded" } + public static _StringLength(ptr1: KPointer): int32 { throw "method not loaded" } + public static _StringData(ptr1: KPointer, arr: KUint8ArrayPtr, i: int32): void { throw "method not loaded" } + public static _StringMake(str1: KStringPtr): KPointer { throw "method not loaded" } + public static _GetPtrVectorSize(ptr1: KPointer): int32 { throw "method not loaded" } + public static _ManagedStringWrite(str1: string, arr: Uint8Array, arg: int32): int32 { throw "method not loaded" } + public static _NativeLog(str1: string): void { throw "method not loaded" } + public static _Utf8ToString(data: KUint8ArrayPtr, offset: int32, length: int32): string { throw "method not loaded" } + public static _StdStringToString(cstring: KPointer): string { throw "method not loaded" } + public static _CheckCallbackEvent(buffer: KUint8ArrayPtr, bufferLength: int32): int32 { throw "method not loaded" } + public static _HoldCallbackResource(resourceId: int32): void { throw "method not loaded" } + public static _ReleaseCallbackResource(resourceId: int32): void { throw "method not loaded" } + public static _CallCallback(callbackKind: int32, args: Uint8Array, argsSize: int32): void { throw "method not loaded" } + public static _CallCallbackSync(callbackKind: int32, args: Uint8Array, argsSize: int32): void { throw "method not loaded" } + public static _CallCallbackResourceHolder(holder: KPointer, resourceId: int32): void { throw "method not loaded" } + public static _CallCallbackResourceReleaser(releaser: KPointer, resourceId: int32): void { throw "method not loaded" } + public static _MaterializeBuffer(data: KPointer, length: int32, resourceId: int32, hold: KPointer, release: KPointer): ArrayBuffer { throw "method not loaded" } + public static _GetNativeBufferPointer(data: ArrayBuffer): KPointer { throw "method not loaded" } + + public static _LoadVirtualMachine(arg0: int32, arg1: string, arg2: string): int32 { throw "method not loaded" } + public static _RunApplication(arg0: int32, arg1: int32): number { throw "method not loaded" } + public static _StartApplication(appUrl: string, appParams: string): KPointer { throw "method not loaded" } + public static _EmitEvent(eventType: int32, target: int32, arg0: int32, arg1: int32): void { throw "method not loaded" } + public static _CallForeignVM(foreignContext: KPointer, kind: int32, args: Uint8Array, argsSize: int32): int32 { throw "method not loaded" } +} + +export function loadInteropNativeModule() { + loadNativeModuleLibrary("InteropNativeModule", InteropNativeModule) +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/interop/InteropOps.ts b/koala-wrapper/koalaui/interop/src/interop/InteropOps.ts new file mode 100644 index 000000000..71d84f0a4 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/InteropOps.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common" +import { withStringResult } from "./Platform" +import { KInt, KStringPtr, KUint8ArrayPtr, pointer } from "./InteropTypes" + +export type CallbackType = (args: Uint8Array, length: int32) => int32 + +class CallbackRecord { + constructor( + public readonly callback: CallbackType, + public readonly autoDisposable: boolean + ) { } +} + +class CallbackRegistry { + + static INSTANCE = new CallbackRegistry() + + private callbacks = new Map() + private id = 1024 + + constructor() { + this.callbacks.set(0, new CallbackRecord( + (args: Uint8Array, length: int32): int32 => { + console.log(`Callback 0 called with args = ${args} and length = ${length}`) + throw new Error(`Null callback called`) + }, false) + ) + } + + wrap(callback: CallbackType, autoDisposable: boolean): int32 { + const id = this.id++ + this.callbacks.set(id, new CallbackRecord(callback, autoDisposable)) + return id + } + + wrapSystem(id: number, callback: CallbackType, autoDisposable: boolean): int32 { + this.callbacks.set(id, new CallbackRecord(callback, autoDisposable)) + return id + } + + call(id: int32, args: Uint8Array, length: int32): int32 { + const record = this.callbacks.get(id) + if (!record) { + console.log(`Callback ${id} is not known`) + // throw new Error(`Disposed or unwrapped callback called (id = ${id})`) + return 0; // todo + } + if (record.autoDisposable) { + this.dispose(id) + } + return record.callback(args, length) + } + + dispose(id: int32) { + this.callbacks.delete(id) + } +} + +export function wrapCallback(callback: CallbackType, autoDisposable: boolean = true): int32 { + return CallbackRegistry.INSTANCE.wrap(callback, autoDisposable) +} + +export function wrapSystemCallback(id:number, callback: CallbackType): int32 { + return CallbackRegistry.INSTANCE.wrapSystem(id, callback, false) +} + +export function disposeCallback(id: int32) { + CallbackRegistry.INSTANCE.dispose(id) +} + +export function callCallback(id: int32, args: Uint8Array, length: int32): int32 { + return CallbackRegistry.INSTANCE.call(id, args, length) +} diff --git a/koala-wrapper/koalaui/interop/src/interop/InteropTypes.ts b/koala-wrapper/koalaui/interop/src/interop/InteropTypes.ts new file mode 100644 index 000000000..7373008e6 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/InteropTypes.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { int32, int64, float32, float64 } from "@koalaui/common" + +export type KStringPtr = int32 | string | null +export type KStringArrayPtr = int32 | Uint8Array | null +export type KInt32ArrayPtr = int32 | Int32Array | null +export type KFloat32ArrayPtr = int32 | Float32Array | null +export type KUint8ArrayPtr = int32 | Uint8Array | null +export type KInt = int32 +export type KUInt = int32 +export type KLong = int64 +export type KFloat = float32 +export type KDouble = float64 +export type KBoolean = int32 +export type KPointer = number | bigint +export type pointer = KPointer +export type KNativePointer = KPointer +export type KInteropReturnBuffer = Uint8Array \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/interop/MaterializedBase.ts b/koala-wrapper/koalaui/interop/src/interop/MaterializedBase.ts new file mode 100644 index 000000000..c1aa09b05 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/MaterializedBase.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Finalizable } from "./Finalizable" + +export interface MaterializedBase { + getPeer(): Finalizable | undefined +} diff --git a/koala-wrapper/koalaui/interop/src/interop/NativeBuffer.ts b/koala-wrapper/koalaui/interop/src/interop/NativeBuffer.ts new file mode 100644 index 000000000..d3b23d72e --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/NativeBuffer.ts @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { pointer } from './InteropTypes' +import { int32, int64 } from '@koalaui/common' + +// stub wrapper for KInteropBuffer +export class NativeBuffer extends ArrayBuffer { + public data:pointer = 0 + public length: int64 = 0 + public resourceId: int32 = 0 + public hold:pointer = 0 + public release: pointer = 0 + + constructor(data:pointer, length: int64, resourceId: int32, hold:pointer, release: pointer) { + super(length) + this.data = data + this.length = length + this.resourceId = resourceId + this.hold = hold + this.release = release + } + + static wrap(data:pointer, length: int64, resourceId: int32, hold:pointer, release: pointer): NativeBuffer { + return new NativeBuffer(data, length, resourceId, hold, release) + } +} diff --git a/koala-wrapper/koalaui/interop/src/interop/NativeString.ts b/koala-wrapper/koalaui/interop/src/interop/NativeString.ts new file mode 100644 index 000000000..8e04674be --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/NativeString.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Finalizable } from "./Finalizable" +import { InteropNativeModule } from "./InteropNativeModule" +import { pointer } from "./InteropTypes" + +export class NativeString extends Finalizable { + constructor(ptr: pointer) { + super(ptr, InteropNativeModule._GetStringFinalizer()) + } + static Make(value: string): NativeString { + return new NativeString(InteropNativeModule._StringMake(value)) + } + toString(): string { + return InteropNativeModule._StdStringToString(this.ptr) + } +} diff --git a/koala-wrapper/koalaui/interop/src/interop/Platform.ts b/koala-wrapper/koalaui/interop/src/interop/Platform.ts new file mode 100644 index 000000000..fb74d312c --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/Platform.ts @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common" +import { isNullPtr, nullptr, Wrapper } from "./Wrapper" +import { decodeToString } from "#common/wrappers/arrays" +import { setCallbackRegistry } from "#common/wrappers/Callback" +import { KPointer } from "./InteropTypes" + +export abstract class NativeStringBase extends Wrapper { + constructor(ptr: KPointer) { + super(ptr) + } + + protected abstract bytesLength(): int32 + protected abstract getData(data: Uint8Array): void + + toString(): string { + let length = this.bytesLength() + let data = new Uint8Array(length) + this.getData(data) + return decodeToString(data) + } + + abstract close(): void +} + +export abstract class ArrayDecoder { + abstract getArraySize(blob: KPointer): int32 + abstract disposeArray(blob: KPointer): void + abstract getArrayElement(blob: KPointer, index: int32): T + + decode(blob: KPointer): Array { + const size = this.getArraySize(blob) + const result = new Array(size) + for (let index = 0; index < size; index++) { + result[index] = this.getArrayElement(blob, index) + } + this.disposeArray(blob) + return result + } +} + + +// TODO: the semicolons after methods in these interfaces are to +// workaround ArkTS compiler parser bug +export interface CallbackRegistry { + registerCallback(callback: any, obj: any): KPointer; +} + +export interface PlatformDefinedData { + nativeString(ptr: KPointer): NativeStringBase; + nativeStringArrayDecoder(): ArrayDecoder; + callbackRegistry(): CallbackRegistry | undefined; +} + +let platformData: PlatformDefinedData|undefined = undefined + +export function providePlatformDefinedData(platformDataParam: PlatformDefinedData) { + platformData = platformDataParam + let registry = platformDataParam.callbackRegistry() + if (registry) setCallbackRegistry(registry) +} + +export function withStringResult(ptr: KPointer): string|undefined { + if (isNullPtr(ptr)) return undefined + let managedString = platformData!.nativeString(ptr) + let result = managedString?.toString() + managedString?.close() + return result +} + +export function withStringArrayResult(ptr: KPointer): Array { + if (ptr == nullptr) return new Array() + let managedStringArray = platformData!.nativeStringArrayDecoder().decode(ptr) + return managedStringArray.map((nativeString:NativeStringBase) => nativeString.toString()) +} diff --git a/koala-wrapper/koalaui/interop/src/interop/SerializerBase.ts b/koala-wrapper/koalaui/interop/src/interop/SerializerBase.ts new file mode 100644 index 000000000..c1df42d43 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/SerializerBase.ts @@ -0,0 +1,296 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { float32, int32, int64 } from "@koalaui/common" +import { pointer, KPointer } from "./InteropTypes" +import { wrapCallback } from "./InteropOps" +import { InteropNativeModule } from "./InteropNativeModule" +import { ResourceHolder, ResourceId } from "../arkts/ResourceManager" + +// imports required interfaces (now generation is disabled) +// import { Resource } from "@arkoala/arkui" +/** + * Value representing possible JS runtime object type. + * Must be synced with "enum RuntimeType" in C++. + */ +export enum RuntimeType { + UNEXPECTED = -1, + NUMBER = 1, + STRING = 2, + OBJECT = 3, + BOOLEAN = 4, + UNDEFINED = 5, + BIGINT = 6, + FUNCTION = 7, + SYMBOL = 8, + MATERIALIZED = 9, +} + +/** + * Value representing object type in serialized data. + * Must be synced with "enum Tags" in C++. + */ +export enum Tags { + UNDEFINED = 101, + INT32 = 102, + FLOAT32 = 103, + STRING = 104, + LENGTH = 105, + RESOURCE = 106, + OBJECT = 107, +} + +export function runtimeType(value: any): int32 { + let type = typeof value + if (type == "number") return RuntimeType.NUMBER + if (type == "string") return RuntimeType.STRING + if (type == "undefined") return RuntimeType.UNDEFINED + if (type == "object") return RuntimeType.OBJECT + if (type == "boolean") return RuntimeType.BOOLEAN + if (type == "bigint") return RuntimeType.BIGINT + if (type == "function") return RuntimeType.FUNCTION + if (type == "symbol") return RuntimeType.SYMBOL + + throw new Error(`bug: ${value} is ${type}`) +} + +export function isResource(value: unknown): boolean { + return value !== undefined + && typeof value === 'object' + && value !== null + && value.hasOwnProperty("bundleName") + && value.hasOwnProperty("moduleName") +} + +// Poor man's instanceof, fails on subclasses +export function isInstanceOf(className: string, value: object | undefined): boolean { + return value?.constructor.name === className +} + +export function registerCallback(value: object|undefined): int32 { + return wrapCallback((args: Uint8Array, length: int32) => { + // TBD: deserialize the callback arguments and call the callback + return 42 + }) +} + +export function registerMaterialized(value: object|undefined): number { + // TODO: fix me! + return 42 +} + +export interface CallbackResource { + resourceId: int32 + hold: pointer + release: pointer +} + +/* Serialization extension point */ +export abstract class CustomSerializer { + constructor(protected supported: Array) {} + supports(kind: string): boolean { return this.supported.includes(kind) } + abstract serialize(serializer: SerializerBase, value: any, kind: string): void + next: CustomSerializer | undefined = undefined +} + +export class SerializerBase { + private position = 0 + private buffer: ArrayBuffer + private view: DataView + + private static customSerializers: CustomSerializer | undefined = undefined + static registerCustomSerializer(serializer: CustomSerializer) { + if (SerializerBase.customSerializers == undefined) { + SerializerBase.customSerializers = serializer + } else { + let current = SerializerBase.customSerializers + while (current.next != undefined) { current = current.next } + current.next = serializer + } + } + constructor() { + this.buffer = new ArrayBuffer(96) + this.view = new DataView(this.buffer) + } + public release() { + this.releaseResources() + this.position = 0 + } + asArray(): Uint8Array { + return new Uint8Array(this.buffer) + } + length(): int32 { + return this.position + } + currentPosition(): int32 { return this.position } + + private checkCapacity(value: int32) { + if (value < 1) { + throw new Error(`${value} is less than 1`) + } + let buffSize = this.buffer.byteLength + if (this.position > buffSize - value) { + const minSize = this.position + value + const resizedSize = Math.max(minSize, Math.round(3 * buffSize / 2)) + let resizedBuffer = new ArrayBuffer(resizedSize) + // TODO: can we grow without new? + new Uint8Array(resizedBuffer).set(new Uint8Array(this.buffer)) + this.buffer = resizedBuffer + this.view = new DataView(resizedBuffer) + } + } + private heldResources: ResourceId[] = [] + holdAndWriteCallback(callback: object, hold: KPointer = 0, release: KPointer = 0, call: KPointer = 0, callSync: KPointer = 0): ResourceId { + const resourceId = ResourceHolder.instance().registerAndHold(callback) + this.heldResources.push(resourceId) + this.writeInt32(resourceId) + this.writePointer(hold) + this.writePointer(release) + this.writePointer(call) + this.writePointer(callSync) + return resourceId + } + holdAndWriteCallbackForPromiseVoid(hold: KPointer = 0, release: KPointer = 0, call: KPointer = 0, callSync = 0): [Promise, ResourceId] { + let resourceId: ResourceId + const promise = new Promise((resolve, reject) => { + const callback = (err: string[]|undefined) => { + if (err !== undefined) + reject(err) + else + resolve() + } + resourceId = this.holdAndWriteCallback(callback, hold, release, call, callSync) + }) + return [promise, resourceId] + } + holdAndWriteCallbackForPromise(hold: KPointer = 0, release: KPointer = 0, call: KPointer = 0): [Promise, ResourceId] { + let resourceId: ResourceId + const promise = new Promise((resolve, reject) => { + const callback = (value: T|undefined, err: string[]|undefined) => { + if (err !== undefined) + reject(err) + else + resolve(value!) + } + resourceId = this.holdAndWriteCallback(callback, hold, release, call) + }) + return [promise, resourceId] + } + writeCallbackResource(resource: CallbackResource) { + this.writeInt32(resource.resourceId) + this.writePointer(resource.hold) + this.writePointer(resource.release) + } + private releaseResources() { + for (const resourceId of this.heldResources) + InteropNativeModule._ReleaseCallbackResource(resourceId) + // todo think about effective array clearing/pushing + this.heldResources = [] + } + writeCustomObject(kind: string, value: any) { + let current = SerializerBase.customSerializers + while (current) { + if (current.supports(kind)) { + current.serialize(this, value, kind) + return + } + current = current.next + } + console.log(`Unsupported custom serialization for ${kind}, write undefined`) + this.writeInt8(Tags.UNDEFINED) + } + writeNumber(value: number|undefined) { + this.checkCapacity(5) + if (value == undefined) { + this.view.setInt8(this.position, Tags.UNDEFINED) + this.position++ + return + } + if (value == Math.round(value)) { + this.view.setInt8(this.position, Tags.INT32) + this.view.setInt32(this.position + 1, value, true) + this.position += 5 + return + } + this.view.setInt8(this.position, Tags.FLOAT32) + this.view.setFloat32(this.position + 1, value, true) + this.position += 5 + } + writeInt8(value: int32) { + this.checkCapacity(1) + this.view.setInt8(this.position, value) + this.position += 1 + } + writeInt32(value: int32) { + this.checkCapacity(4) + this.view.setInt32(this.position, value, true) + this.position += 4 + } + writeInt64(value: int64) { + this.checkCapacity(8) + this.view.setBigInt64(this.position, BigInt(value), true) + this.position += 8 + } + writePointer(value: pointer) { + this.checkCapacity(8) + this.view.setBigInt64(this.position, BigInt(value ?? 0), true) + this.position += 8 + } + writeFloat32(value: float32) { + this.checkCapacity(4) + this.view.setFloat32(this.position, value, true) + this.position += 4 + } + writeBoolean(value: boolean|undefined) { + this.checkCapacity(1) + this.view.setInt8(this.position, value == undefined ? RuntimeType.UNDEFINED : +value) + this.position++ + } + writeFunction(value: object | undefined) { + this.writeInt32(registerCallback(value)) + } + writeString(value: string) { + this.checkCapacity(4 + value.length * 4) // length, data + let encodedLength = + InteropNativeModule._ManagedStringWrite(value, new Uint8Array(this.view.buffer, 0), this.position + 4) + this.view.setInt32(this.position, encodedLength, true) + this.position += encodedLength + 4 + } + writeBuffer(buffer: ArrayBuffer) { + const resourceId = ResourceHolder.instance().registerAndHold(buffer) + this.writeCallbackResource({ + resourceId, + hold: 0, + release: 0 + }) + const ptr = InteropNativeModule._GetNativeBufferPointer(buffer) + this.writePointer(ptr) + this.writeInt64(buffer.byteLength) + } +} + +class DateSerializer extends CustomSerializer { + constructor() { + super(["Date"]) + } + + serialize(serializer: SerializerBase, value: object, kind: string): void { + serializer.writeString((value as Date).toISOString()) + } +} +SerializerBase.registerCustomSerializer(new DateSerializer()) + +export function unsafeCast(value: unknown) { + return value as unknown as T +} diff --git a/koala-wrapper/koalaui/interop/src/interop/Wrapper.ts b/koala-wrapper/koalaui/interop/src/interop/Wrapper.ts new file mode 100644 index 000000000..4b7dbc124 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/Wrapper.ts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ptrToString, nullptr, isSamePtr } from "#common/wrappers/Wrapper" +import { className } from "@koalaui/common" +import { KPointer } from "./InteropTypes" + +export { isNullPtr, nullptr, ptrToBits, bitsToPtr, isSamePtr, ptrToString } from "#common/wrappers/Wrapper" + +/** + * An object holding reference to the native pointer. + */ +export class Wrapper { + ptr: KPointer + constructor(ptr: KPointer) { + if (ptr == null) + throw new Error(`Init <${className(this)}> with null native peer`) + this.ptr = ptr + } + toString(): string { + return `[native object <${className(this)}> at ${ptrToString(this.ptr)}]` + } +} + +export function getPtr(value: Wrapper|undefined): KPointer { + return value?.ptr ?? nullptr +} + +export function ptrEqual(a: Wrapper|undefined, b: Wrapper|undefined): boolean { + if (a === b) return true + if (a == undefined || b == undefined) return false + return isSamePtr(a.ptr, b.ptr) +} diff --git a/koala-wrapper/koalaui/interop/src/interop/arrays.ts b/koala-wrapper/koalaui/interop/src/interop/arrays.ts new file mode 100644 index 000000000..2699de10b --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/arrays.ts @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common" + +export enum Access { + READ = 1, // 1 << 0, + WRITE = 2, // 1 << 1, + READWRITE = 3, // READ | WRITE +} +export function isRead(access: Access) { + return access & Access.READ +} +export function isWrite(access: Access) { + return access & Access.WRITE +} + +export type Exec = (pointer: P) => R +export type ExecWithLength = (pointer: P, length: int32) => R + +export type TypedArray = + Uint8Array + | Int8Array + | Uint16Array + | Int16Array + | Uint32Array + | Int32Array + | Float32Array + | Float64Array + +export type PtrArray = Uint32Array | BigUint64Array \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/interop/buffer.ts b/koala-wrapper/koalaui/interop/src/interop/buffer.ts new file mode 100644 index 000000000..5bf60ad3e --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/buffer.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022-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. + */ + +export class KBuffer { + private readonly _buffer: Uint8Array + public get buffer(): ArrayBuffer { + return this._buffer + } + public get length(): number { + return this._buffer.length + } + + constructor(length: number) { + this._buffer = new Uint8Array(length) + } + + set(index: number, value: number): void { + this._buffer[index] = value + } + + get(index: number): number { + return this._buffer[index] + } +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/interop/index.ts b/koala-wrapper/koalaui/interop/src/interop/index.ts new file mode 100644 index 000000000..5966b160a --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/index.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + withFloat32Array, + withFloat64Array, + withInt16Array, + withInt32Array, + withInt8Array, + withUint16Array, + withUint32Array, + withUint8Array, + wasmHeap as wasmHeapArrayBuffer +} from "#common/wrappers/arrays" + +export { registerCallback, setCallbackRegistry } from "#common/wrappers/Callback" + +export { Access, Exec } from "./arrays" +export { Finalizable, NativeThunk } from "./Finalizable" +export { nullable } from "./nullable" +export { getPtr, isNullPtr, nullptr, ptrEqual, Wrapper, ptrToBits, bitsToPtr } from "./Wrapper" + +export { + decodeToString, + encodeToData, + withString, + withStringArray, + withPtrArray, + fromPtrArray, + toPtrArray +} from "#common/wrappers/arrays" + +export const withFloatArray = withFloat32Array +export const withByteArray = withUint8Array +export const withIntArray = withInt32Array + +export const wasmHeap = wasmHeapArrayBuffer + +export { + withFloat32Array, + withFloat64Array, + withInt8Array, + withInt16Array, + withInt32Array, + withUint8Array, + withUint16Array, + withUint32Array, +} + +export * from "./Platform" +export * from "./InteropTypes" + +export * from "./InteropOps" +export * from "./NativeString" +export * from "./buffer" +export * from "../arkts/ResourceManager" +export * from "./NativeBuffer" +export { InteropNativeModule, loadInteropNativeModule } from "./InteropNativeModule" +export { SerializerBase, RuntimeType, Tags, runtimeType, CallbackResource, unsafeCast, isResource, isInstanceOf } from "./SerializerBase" +export { DeserializerBase } from "./DeserializerBase" +export { loadNativeModuleLibrary, loadNativeLibrary, registerNativeModuleLibraryName } from "./loadLibraries" +export * from "./MaterializedBase" diff --git a/koala-wrapper/koalaui/interop/src/interop/java/CallbackRecord.java b/koala-wrapper/koalaui/interop/src/interop/java/CallbackRecord.java new file mode 100644 index 000000000..4c866822d --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/java/CallbackRecord.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.koalaui.interop; + +class CallbackRecord { + public CallbackType callback; + public boolean autoDisposable; + + public CallbackRecord(CallbackType callback, boolean autoDisposable) { + this.callback = callback; + this.autoDisposable = autoDisposable; + } +} diff --git a/koala-wrapper/koalaui/interop/src/interop/java/CallbackRegistry.java b/koala-wrapper/koalaui/interop/src/interop/java/CallbackRegistry.java new file mode 100644 index 000000000..59dceae85 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/java/CallbackRegistry.java @@ -0,0 +1,69 @@ +/* + * 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. + */ +package org.koalaui.interop; + +import java.util.Arrays; +import java.util.HashMap; + +class CallbackRegistry { + + private static HashMap callbacks = new HashMap(); + private static Integer id = 0; + + static { + CallbackRegistry.callbacks.put(id, new CallbackRecord( + new CallbackType() { + @Override + public int apply(byte[] args, int length) { + System.out.printf("Callback 0 called with args = %s and length = %d\n", Arrays.toString(args), length); + throw new Error("Null callback called"); + } + }, false) + ); + CallbackRegistry.id++; + } + + private CallbackRegistry() { + + } + + public static Integer wrap(CallbackType callback) { + Integer id = CallbackRegistry.id++; + CallbackRegistry.callbacks.put(id, new CallbackRecord(callback, true)); + return id; + } + + public static Integer wrap(CallbackType callback, boolean autoDisposable) { + Integer id = CallbackRegistry.id++; + CallbackRegistry.callbacks.put(id, new CallbackRecord(callback, autoDisposable)); + return id; + } + + public static int call(Integer id, byte[] args, int length) { + if (!CallbackRegistry.callbacks.containsKey(id)) { + System.out.printf("Callback %d is not known\n", id); + throw new Error(String.format("Disposed or unwrapped callback called (id = %d)", id)); + } + CallbackRecord record = CallbackRegistry.callbacks.get(id); + if (record.autoDisposable) { + CallbackRegistry.dispose(id); + } + return record.callback.apply(args, length); + } + + public static void dispose(Integer id) { + CallbackRegistry.callbacks.remove(id); + } +} diff --git a/koala-wrapper/koalaui/interop/src/interop/java/CallbackTests.java b/koala-wrapper/koalaui/interop/src/interop/java/CallbackTests.java new file mode 100644 index 000000000..04573b937 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/java/CallbackTests.java @@ -0,0 +1,181 @@ +/* + * 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. + */ +package org.koalaui.interop; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.util.function.Function; + +import org.koalaui.arkoala.NativeModule; + +public class CallbackTests { + // Todo: where tests will be located? + + public class TestUtils { + // Todo: where test utils will be located? + public static void assertEquals(String name, T expected, T actual) { + if (!expected.equals(actual)) { + System.out.printf("TEST %s FAIL:\n EXPECTED \"%s\"\n ACTUAL \"%s\"\n", name, expected.toString(), actual.toString()); + } else { + System.out.printf("TEST %s PASS\n", name); + } + } + + public static void assertThrows(String name, Function fn) { + boolean caught = false; + try { + fn.apply(null); + } catch (Throwable e) { + caught = true; + } + if (!caught) { + System.out.printf("TEST %s FAIL:\n No exception thrown\n", name); + } else { + System.out.printf("TEST %s PASS\n", name); + } + } + } + + public static void checkCallback() { + Integer id1 = CallbackRegistry.wrap(new CallbackType() { + @Override + public int apply(byte[] args, int length) { + return 2024; + } + }); + Integer id2 = CallbackRegistry.wrap(new CallbackType() { + @Override + public int apply(byte[] args, int length) { + return 2025; + } + }); + + TestUtils.assertEquals("Call callback 1", 2024, CallbackRegistry.call(id1, new byte[] {}, 0)); + TestUtils.assertEquals("Call callback 2", 2025, CallbackRegistry.call(id2, new byte[] {}, 0)); + TestUtils.assertThrows("Call disposed callback 1", new Function() { + @Override + public Integer apply(Void v) { + return CallbackRegistry.call(id1, new byte[] { }, 0); + } + }); + TestUtils.assertThrows("Call callback 0", new Function() { + @Override + public Integer apply(Void v) { + return CallbackRegistry.call(0, new byte[] { 2, 4, 6, 8 }, 4); + } + }); + } + + public static void checkNativeCallback() { + Integer id1 = CallbackRegistry.wrap(new CallbackType() { + @Override + public int apply(byte[] args, int length) { + return 123456; + } + }); + TestUtils.assertEquals("NativeCallback without args", 123456, NativeModule._TestCallIntNoArgs(id1)); + TestUtils.assertThrows("NativeCallback without args called again", new Function() { + @Override + public Integer apply(Void v) { + return CallbackRegistry.call(id1, new byte[] { }, 0); + } + }); + TestUtils.assertThrows("NativeCallback without args called again from native", new Function() { + @Override + public Integer apply(Void v) { + return NativeModule._TestCallIntNoArgs(id1); + } + }); + + Integer id2 = CallbackRegistry.wrap(new CallbackType() { + @Override + public int apply(byte[] args, int length) { + ByteBuffer buffer = ByteBuffer.wrap(args); + buffer.order(ByteOrder.LITTLE_ENDIAN); + IntBuffer intBuffer = buffer.asIntBuffer(); + int sum = 0; + for (int i = 0; i < length / 4; i++) { + sum += intBuffer.get(i); + } + return sum; + } + }); + int[] arr2 = new int[] { 100, 200, 300, -1000 }; + TestUtils.assertEquals("NativeCallback Int32Array sum", -400, NativeModule._TestCallIntIntArraySum(id2, arr2, arr2.length)); + + Integer id3 = CallbackRegistry.wrap(new CallbackType() { + @Override + public int apply(byte[] args, int length) { + ByteBuffer buffer = ByteBuffer.wrap(args); + buffer.order(ByteOrder.LITTLE_ENDIAN); + IntBuffer intBuffer = buffer.asIntBuffer(); + for (int i = 1; i < length / 4; i++) { + intBuffer.put(i, intBuffer.get(i) + intBuffer.get(i - 1)); + } + return 0; + } + }); + int[] arr3 = new int[] { 100, 200, 300, -1000 }; + NativeModule._TestCallVoidIntArrayPrefixSum(id3, arr3, arr3.length); + TestUtils.assertEquals("NativeCallback Int32Array PrefixSum [0]", 100, arr3[0]); + TestUtils.assertEquals("NativeCallback Int32Array PrefixSum [1]", 300, arr3[1]); + TestUtils.assertEquals("NativeCallback Int32Array PrefixSum [2]", 600, arr3[2]); + TestUtils.assertEquals("NativeCallback Int32Array PrefixSum [3]", -400, arr3[3]); + + long start = System.currentTimeMillis(); + Integer id4 = CallbackRegistry.wrap(new CallbackType() { + @Override + public int apply(byte[] args, int length) { + ByteBuffer buffer = ByteBuffer.wrap(args); + buffer.order(ByteOrder.LITTLE_ENDIAN); + IntBuffer intBuffer = buffer.asIntBuffer(); + intBuffer.put(1, intBuffer.get(1) + 1); + if (intBuffer.get(0) + intBuffer.get(1) < intBuffer.get(2)) { + return NativeModule._TestCallIntRecursiveCallback(id3 + 1, args, args.length); + } + return 1; + } + }, false); + TestUtils.assertEquals("NativeCallback prepare recursive callback test", id4, id3 + 1); + int depth = 500; + int count = 100; + for (int i = 0; i < count; i++) { + int length = 12; + byte[] args = new byte[length]; + IntBuffer args32 = ByteBuffer.wrap(args).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); + args32.put(2, depth); + NativeModule._TestCallIntRecursiveCallback(id4, args, args.length); + if (i == 0) { + TestUtils.assertEquals("NativeCallback Recursive [0]", (depth + 1) / 2, args32.get(0)); + TestUtils.assertEquals("NativeCallback Recursive [1]", depth / 2, args32.get(1)); + } + } + long passed = System.currentTimeMillis() - start; + System.out.println("recursive native callback: " + String.valueOf(passed) + "ms for " + depth * count + " callbacks, " + Math.round((double)passed / (depth * count) * 1000000) + "ms per 1M callbacks"); + + Integer id5 = CallbackRegistry.wrap(new CallbackType() { + @Override + public int apply(byte[] args, int length) { + int sum = 0; + for (int i = 0; i < length; i++) { + sum += args[i]; + } + return sum; + } + }, false); + NativeModule._TestCallIntMemory(id5, 1000); + } +} diff --git a/koala-wrapper/koalaui/interop/src/interop/java/CallbackType.java b/koala-wrapper/koalaui/interop/src/interop/java/CallbackType.java new file mode 100644 index 000000000..188faacd2 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/java/CallbackType.java @@ -0,0 +1,19 @@ +/* + * 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. + */ +package org.koalaui.interop; + +public interface CallbackType { + public int apply(byte[] args, int length); +} diff --git a/koala-wrapper/koalaui/interop/src/interop/loadLibraries.ts b/koala-wrapper/koalaui/interop/src/interop/loadLibraries.ts new file mode 100644 index 000000000..79c8bdd9c --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/loadLibraries.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022-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. + */ + +const nativeModuleLibraries: Map = new Map() + +export function loadNativeLibrary(name: string): Record { + if ((globalThis as any).requireNapi) + return (globalThis as any).requireNapi(name, true) + else { + const suffixedName = name.endsWith(".node") ? name : `${name}.node` + return require(suffixedName) + } +} + +export function registerNativeModuleLibraryName(nativeModule: string, libraryName: string) { + nativeModuleLibraries.set(nativeModule, libraryName) +} + +export function loadNativeModuleLibrary(moduleName: string, module?: object) { + if (!module) + throw new Error(" argument is required and optional only for compatibility with ArkTS") + const library = loadNativeLibrary(nativeModuleLibraries.get(moduleName) ?? moduleName) + if (!library || !library[moduleName]) { + console.error(`Failed to load library for module ${moduleName}`) + return + } + Object.assign(module, library[moduleName]) +} diff --git a/koala-wrapper/koalaui/interop/src/interop/nullable.ts b/koala-wrapper/koalaui/interop/src/interop/nullable.ts new file mode 100644 index 000000000..546eb9cab --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/interop/nullable.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isNullPtr } from "./Wrapper" +import { KPointer } from "./InteropTypes" + +export function nullable(value: KPointer, body: (arg: KPointer) => T | undefined): T | undefined { + if (isNullPtr(value)) { + return undefined + } else { + return body(value) + } +} diff --git a/koala-wrapper/koalaui/interop/src/napi/wrappers/Callback.ts b/koala-wrapper/koalaui/interop/src/napi/wrappers/Callback.ts new file mode 100644 index 000000000..4d9193a13 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/napi/wrappers/Callback.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KPointer } from "../../interop/InteropTypes" +import { CallbackRegistry } from "../../interop/Platform" + +export function registerCallback(callback: any, obj: any = null): KPointer { + return theRegistry!.registerCallback(callback, obj) +} + +let theRegistry: CallbackRegistry|undefined = undefined + +export function setCallbackRegistry(registry: CallbackRegistry) { + theRegistry = registry +} diff --git a/koala-wrapper/koalaui/interop/src/napi/wrappers/Wrapper.ts b/koala-wrapper/koalaui/interop/src/napi/wrappers/Wrapper.ts new file mode 100644 index 000000000..0f688601b --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/napi/wrappers/Wrapper.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common" +import { KPointer } from "../../interop/InteropTypes" + +export const nullptr = BigInt(0) + +export function isNullPtr(value: KPointer): boolean { + return value === nullptr +} + +export function ptrToString(ptr: KPointer) { + return `0x${ptr!.toString(16).padStart(8, "0")}` +} + +export function isSamePtr(a: KPointer, b: KPointer) { + return (a === b) +} + +// TODO rethink me +export function ptrToBits(ptr: KPointer): Uint32Array | null { + let result = new Uint32Array(2) + let ptrBigInt = ptr as bigint + result[0] = Number(ptrBigInt & BigInt(0xFFFFFFFF)) + result[1] = Number((ptrBigInt >> BigInt(32)) & BigInt(0xFFFFFFFF)) + return result +} + +export function bitsToPtr(array: Int32Array, offset: int32): KPointer { + let ptrBigInt: bigint = BigInt(array[offset + 1]) & BigInt(0xFFFFFFFF) + ptrBigInt = (ptrBigInt << BigInt(32)) | (BigInt(array[offset]) & BigInt(0xFFFFFFFF)) + return ptrBigInt +} diff --git a/koala-wrapper/koalaui/interop/src/napi/wrappers/arrays.ts b/koala-wrapper/koalaui/interop/src/napi/wrappers/arrays.ts new file mode 100644 index 000000000..36cefa696 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/napi/wrappers/arrays.ts @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CustomTextDecoder, CustomTextEncoder } from "@koalaui/common" +import { Access, Exec, ExecWithLength, PtrArray, TypedArray } from "../../interop/arrays" +import { nullptr } from "./Wrapper" +import { Wrapper } from "../../interop/Wrapper" +import { KPointer, KStringArrayPtr } from "../../interop" + +const encoder = new CustomTextEncoder() +const decoder = new CustomTextDecoder() + +export function decodeToString(array: Uint8Array): string { + return decoder.decode(array) +} + +export function encodeToData(string: string): Uint8Array { + return encoder.encode(string, false) +} + +export function withString(data: string | undefined, exec: Exec): R { + return exec(data === undefined ? null : data) +} + +export function withStringArray(strings: Array | undefined, exec: Exec): R { + if (strings === undefined || strings.length === 0) { + return exec(null) + } + + let array = encoder.encodeArray(strings) + return exec(array) +} + +function withArray( + data: C | undefined, + exec: ExecWithLength +): R { + return exec(data ?? null, data?.length ?? 0) +} + +export function withPtrArray(data: BigUint64Array, access: Access, exec: ExecWithLength) { + return exec(data ?? null, data?.length ?? 0) // TODO rethink +} + +export function toPtrArray(data: Array | undefined): BigUint64Array { + if (data == undefined || data.length === 0) { + return new BigUint64Array(0) + } + const array = new BigUint64Array(data.length) + for (let i = 0; i < data.length; i++) { + let item = data[i] + array[i] = item != undefined ? item.ptr as bigint : nullptr + } + return array +} + +export function fromPtrArray(array: PtrArray, factory: (ptr: KPointer) => T) : Array { + if (array.length === 0) { + return new Array(0) + } + const result = new Array(array.length) + for (let i = 0; i < array.length; i++) { + let ptr = array[i] + if (ptr == nullptr) { + result[i] = undefined + } else { + result[i] = factory(ptr) + } + } + return result +} + +export function withUint8Array(data: Uint8Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, exec) +} +export function withInt8Array(data: Int8Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, exec) +} +export function withUint16Array(data: Uint16Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, exec) +} +export function withInt16Array(data: Int16Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, exec) +} +export function withUint32Array(data: Uint32Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, exec) +} +export function withInt32Array(data: Int32Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, exec) +} +export function withFloat32Array(data: Float32Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, exec) +} +export function withFloat64Array(data: Float64Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, exec) +} +export function wasmHeap(): ArrayBuffer { + throw new Error("Unused") +} \ No newline at end of file diff --git a/koala-wrapper/koalaui/interop/src/wasm/wrappers/Callback.ts b/koala-wrapper/koalaui/interop/src/wasm/wrappers/Callback.ts new file mode 100644 index 000000000..5f4de87e8 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/wasm/wrappers/Callback.ts @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KPointer } from "../../interop/InteropTypes" +import { CallbackRegistry } from "../../interop/Platform" + +class CallbackInfo { + cb: any + recv: any + constructor(callback: any, obj: any = null) { + this.cb = callback + this.recv = obj + } +} + +const GLOBAL_SCOPE = new class CallbackScope { + static readonly CB_NULL = new CallbackInfo( + () => { throw new Error("attempted to call a callback at NULL") }, + null + ) + static readonly CB_UNDEFINED = new CallbackInfo( + () => { throw new Error("attempted to call an uninitialized callback") }, + null + ) + static readonly CB_NULL_ID = 0 + nextId: number + callbackMap: Map | null + + constructor() { + this.nextId = 1 + this.callbackMap = new Map() + this.callbackMap.set(CallbackScope.CB_NULL_ID, CallbackScope.CB_NULL) + } + + addCallback(cb: any, obj: any): number { + let id = this.nextId++ + this.callbackMap?.set(id, new CallbackInfo(cb, obj)) + return id + } + + getCallback(id: number): CallbackInfo { + return this.callbackMap?.get(id) || CallbackScope.CB_UNDEFINED + } + + deleteCallback(id: number): void { + if (id > CallbackScope.CB_NULL_ID) { + this.callbackMap?.delete(id) + } + } + + release(): void { + this.callbackMap = null + } +} + +function callCallback(callbackId: number): any { + let CallbackInfo = GLOBAL_SCOPE.getCallback(callbackId) + try { + let cb = CallbackInfo.cb + if (CallbackInfo.recv !== null) { + cb = cb.bind(CallbackInfo.recv) + } + return cb() + } catch (e) { + console.error(e) + } +} + +export function registerCallback(callback: any, obj: any = null): KPointer { + return GLOBAL_SCOPE.addCallback(callback, obj) +} + +function releaseCallback(callbackId: number): void { + return GLOBAL_SCOPE.deleteCallback(callbackId) +} + +declare namespace globalThis { + function callCallback(callbackId: number): any + function releaseCallback(callbackId: number): any +} + +globalThis.callCallback = callCallback +globalThis.releaseCallback = releaseCallback + +export function setCallbackRegistry(_ignoredRegistry: CallbackRegistry) { + // On WASM we don't need registry in current implementation. +} diff --git a/koala-wrapper/koalaui/interop/src/wasm/wrappers/Wrapper.ts b/koala-wrapper/koalaui/interop/src/wasm/wrappers/Wrapper.ts new file mode 100644 index 000000000..52c2a1a58 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/wasm/wrappers/Wrapper.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common" +import { KPointer } from "../../interop/InteropTypes" + +export const nullptr: number = 0 + +export function isNullPtr(value: KPointer): boolean { + return (value == nullptr) +} + +export function ptrToString(ptr: KPointer) { + if (ptr === 0) return "0x0" + + const hex = (ptr as number).toString(16).padStart(8, "0") + return `0x${hex}` +} + +export function isSamePtr(a: KPointer, b: KPointer) { + return a === b +} + +export function ptrToBits(ptr: KPointer): Uint32Array { + let result = new Uint32Array(2) + result[0] = ptr as int32 + return result +} + +export function bitsToPtr(array: Int32Array, offset: int32): KPointer { + return array[offset] +} diff --git a/koala-wrapper/koalaui/interop/src/wasm/wrappers/arrays.ts b/koala-wrapper/koalaui/interop/src/wasm/wrappers/arrays.ts new file mode 100644 index 000000000..9aa189d07 --- /dev/null +++ b/koala-wrapper/koalaui/interop/src/wasm/wrappers/arrays.ts @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CustomTextEncoder, CustomTextDecoder, int32 } from "@koalaui/common" + +import { KPointer } from "../../interop/InteropTypes" +import { Wrapper } from "../../interop/Wrapper" +import { Access, isRead, isWrite, Exec, TypedArray, ExecWithLength } from "../../interop/arrays" + +const encoder = new CustomTextEncoder() +const decoder = new CustomTextDecoder() + +export function decodeToString(array: Uint8Array): string { + return decoder.decode(array) +} + +export function encodeToData(string: string): Uint8Array { + return encoder.encode(string, false) +} + +type Heap = { readonly buffer: ArrayBuffer } + +// TODO actually memory allocation primitives are defined for a specific intance instance, +// refactor me +declare const _heaps: { + HEAP8(): Heap; + HEAP16(): Heap; + HEAP32(): Heap; + HEAPU8(): Heap; + HEAPU16(): Heap; + HEAPU32(): Heap; + HEAPF32(): Heap; + HEAPF64(): Heap; +} +declare function _malloc(size: number): number; +declare function _free(ptr: number): void; + +const nullptr: number = 0 + +// with string as array of utf8 data headed by length +export function withString(data: string | undefined, exec: Exec): R { + if (data === undefined) return exec(nullptr) + + let array = encoder.encode(data, true) + return withUint8Array(array, Access.READ, exec) +} + +export function withStringArray(strings: Array | undefined, exec: Exec): R { + if (strings === undefined || strings.length === 0) { + return exec(nullptr) + } + + let array = encoder.encodeArray(strings) + return withUint8Array(array, Access.READ, exec) +} + +function withArray( + data: C | undefined, + access: Access, + exec: ExecWithLength, + bytesPerElement: int32, + ctor: (ptr: number, length: number) => C +): R { + if (data === undefined || data.length === 0) { + return exec(nullptr, 0) + } + + let ptr = _malloc(data.length * bytesPerElement) + let wasmArray = ctor(ptr, data.length) + + if (isRead(access)) { + wasmArray.set(data) + } + + let result = exec(ptr, data.length) + + if (isWrite(access)) { + data.set(wasmArray) + } + + _free(ptr) + + return result +} + +export function withPtrArray(data: Uint32Array, access: Access, exec: ExecWithLength) { + return withArray(data as Uint32Array, access, exec, Uint32Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Uint32Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} + +export function toPtrArray(data: Array | undefined): Uint32Array { + if (data === undefined || data.length === 0) { + return new Uint32Array(0) + } + const array = new Uint32Array(data.length) + for (let i = 0; i < data.length; i++) { + array[i] = data[i]?.ptr as number + } + return array +} + +export function fromPtrArray(array: Uint32Array, factory: (ptr: KPointer) => T) : Array { + const result = new Array(array.length) + for (let i = 0; i < array.length; i++) { + let v = array[i] + if (v == 0) { + result[i] = undefined + } else { + result[i] = factory(v) + } + } + return result +} + +export function withUint8Array(data: Uint8Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, access, exec, Uint8Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Uint8Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} +export function withInt8Array(data: Int8Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, access, exec, Int8Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Int8Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} +export function withUint16Array(data: Uint16Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, access, exec, Uint16Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Uint16Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} +export function withInt16Array(data: Int16Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, access, exec, Int16Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Int16Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} +export function withUint32Array(data: Uint32Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, access, exec, Uint32Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Uint32Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} +export function withInt32Array(data: Int32Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, access, exec, Int32Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Int32Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} +export function withFloat32Array(data: Float32Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, access, exec, Float32Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Float32Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} +export function withFloat64Array(data: Float64Array | undefined, access: Access, exec: ExecWithLength) { + return withArray(data, access, exec, Float64Array.BYTES_PER_ELEMENT, (ptr: number, length: number) => { + return new Float64Array(_heaps.HEAPU8().buffer, ptr, length) + }) +} + +export function wasmHeap(): ArrayBuffer { + return _heaps.HEAP32().buffer +} diff --git a/koala-wrapper/native/BUILD.gn b/koala-wrapper/native/BUILD.gn new file mode 100644 index 000000000..65e8bb331 --- /dev/null +++ b/koala-wrapper/native/BUILD.gn @@ -0,0 +1,141 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("build_es2panda_lib") { + external_deps = [ "ets_frontend:ets2panda" ] +} + +shared_library("es2panda") { + deps = [ ":build_es2panda_lib" ] + sources = [ + "../koalaui/interop/src/cpp/common-interop.cc", + "../koalaui/interop/src/cpp/interop-logging.cc", + "../koalaui/interop/src/cpp/napi/convertors-napi.cc", + "./src/bridges.cc", + "./src/common.cc", + "./src/generated/bridges.cc", + ] + + include_dirs = [ + "../koalaui/interop/src/cpp", + "../koalaui/interop/src/cpp/types", + "../koalaui/interop/src/cpp/napi", + "../node_modules/node-api-headers/include", + "../node_modules/node-addon-api", + "./include", + "//arkcompiler/ets_frontend/ets2panda/public/", + "//third_party/node/src", + rebase_path("$root_gen_dir/arkcompiler/ets_frontend/ets2panda/"), + ] + + defines = [ + "KOALA_INTEROP_MODULE=NativeModule", + "INTEROP_LIBRARY_NAME=es2panda", + "KOALA_USE_NODE_VM", + "KOALA_NAPI", + "NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS", + ] + + configs -= [ "//build/config/compiler:compiler" ] + + if (current_os == "linux") { + cflags_cc = [ + "-std=c++17", + "-Wall", + "-Werror", + "-Wno-unused-variable", + "-fPIC", + ] + + ldflags = [ + "-Wl,--allow-shlib-undefined", + "-Wl,--fatal-warnings", + "-Wl,--build-id=md5", + "-fPIC", + "-Wl,-z,noexecstack", + "-Wl,-z,now", + "-Wl,-z,relro", + + # "-Wl,-z,defs", # must no use this option + "-Wl,--as-needed", + "-fuse-ld=lld", + "-Wl,--icf=all", + "-Wl,--color-diagnostics", + "-m64", + ] + defines += [ "KOALA_LINUX" ] + output_extension = "node" + } else if (current_os == "mingw") { + output_extension = "dll" + cflags_cc = [ + "-std=c++17", + "-Wall", + "-Werror", + "-Wno-unused-variable", + "-fPIC", + "-Wno-error=deprecated-copy", + "-enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang", + "-ftrivial-auto-var-init=zero", + "-fcolor-diagnostics", + "-fmerge-all-constants", + "-Xclang", + "-mllvm", + "-Xclang", + "-instcombine-lower-dbg-declare=0", + "-no-canonical-prefixes", + "-static", + "-rtlib=compiler-rt", + "-stdlib=libc++", + "-lunwind", + "-lpthread", + "-Qunused-arguments", + "-fuse-ld=lld", + "-fno-stack-protector", + "-fno-strict-aliasing", + "-Wno-builtin-macro-redefined", + "-fms-extensions", + "-static", + "-rtlib=compiler-rt", + "-stdlib=libc++", + "-std=c++17", + "-lunwind", + "-lpthread", + "-Qunused-arguments", + "-target", + "x86_64-pc-windows-gnu", + "-D__CUSTOM_SECURITY_LIBRARY", + ] + + ldflags = [ + "-Wl,--fatal-warnings", + "-fPIC", + "-Wl,--as-needed", + "-fuse-ld=lld", + "-Wl,--icf=all", + "-m64", + "-static", + "-rtlib=compiler-rt", + "-stdlib=libc++", + "-std=c++17", + "-lunwind", + "-lpthread", + "-Qunused-arguments", + "-target", + "x86_64-pc-windows-gnu", + ] + defines += [ "KOALA_WINDOWS" ] + sources += [ "../koalaui/interop/src/cpp/napi/win-dynamic-node.cc" ] + } +} diff --git a/koala-wrapper/native/include/common.h b/koala-wrapper/native/include/common.h new file mode 100644 index 000000000..77ed29cf8 --- /dev/null +++ b/koala-wrapper/native/include/common.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022-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 COMMON_H +#define COMMON_H + +#include "dynamic-loader.h" +#include "es2panda_lib.h" +#include "common-interop.h" +#include "stdexcept" +#include +#include +#include + +using std::string, std::cout, std::endl, std::vector; + +es2panda_Impl *GetImpl(); + +string getString(KStringPtr ptr); + +char* getStringCopy(KStringPtr& ptr); + +inline KUInt unpackUInt(const KByte* bytes); + +es2panda_ContextState intToState(KInt state); + +#endif // COMMON_H \ No newline at end of file diff --git a/koala-wrapper/native/meson.build b/koala-wrapper/native/meson.build new file mode 100644 index 000000000..5286b471b --- /dev/null +++ b/koala-wrapper/native/meson.build @@ -0,0 +1,63 @@ +project( + 'es2panda_interop', + 'cpp', + version: '1.0', + default_options: [ + 'cpp_std=c++17', + 'buildtype=debug', + ], +) + +sources = [ + './src/common.cc', + './src/bridges.cc', + './src/generated/bridges.cc', + get_option('interop_src_dir') / 'common-interop.cc', + get_option('interop_src_dir') / 'callback-resource.cc', + get_option('interop_src_dir') / 'interop-logging.cc', + get_option('interop_src_dir') / 'napi/convertors-napi.cc', +] + +cflags = [ + '-DKOALA_INTEROP_MODULE=NativeModule', + '-DINTEROP_LIBRARY_NAME=' + get_option('lib_name'), + '-DKOALA_USE_NODE_VM', + '-DKOALA_NAPI', +] + +if (target_machine.system() == 'windows') + cflags += ['-DKOALA_WINDOWS'] + if (meson.get_compiler('cpp').get_id() == 'msvc') + # apply node.exe symbol loading hook + sources += [ + get_option('interop_src_dir') / 'napi/win-dynamic-node.cc' + ] + endif +else + cflags += ['-DKOALA_LINUX'] +endif + +shared_library( + get_option('lib_name'), + sources, + override_options: [ + 'b_lundef=false', + ], + install: true, + name_prefix: '', + name_suffix: 'node', + include_directories: [ + './src/', + './include/', + get_option('panda_sdk_dir') / 'ohos_arm64/include/tools/es2panda/public', + get_option('panda_sdk_dir') / 'ohos_arm64/include/tools/es2panda', + get_option('interop_src_dir'), + get_option('interop_src_dir') / 'types', + get_option('interop_src_dir') / 'napi', + get_option('node_modules_dir') / 'node-api-headers/include', + get_option('node_modules_dir') / 'node-addon-api', + ], + cpp_args: cflags, + link_args: [], + dependencies: [] +) diff --git a/koala-wrapper/native/meson_options.txt b/koala-wrapper/native/meson_options.txt new file mode 100644 index 000000000..cc5b1cd09 --- /dev/null +++ b/koala-wrapper/native/meson_options.txt @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2022-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. + */ + +option('node_modules_dir', type : 'string', value : '../node_modules/', + description : 'path to node_modules') +option('panda_sdk_dir', type : 'string', value : '../node_modules/@panda/sdk/', + description : 'path to panda sdk') +option('interop_src_dir', type : 'string', value : '../node_modules/@koalaui/interop/src/cpp/', + description : 'path to interop') +option('lib_name', type : 'string', value : 'es2panda', + description : 'name of shared library') diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc new file mode 100644 index 000000000..1823e99e4 --- /dev/null +++ b/koala-wrapper/native/src/bridges.cc @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2022-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 "common.h" + +KBoolean impl_ClassDefinitionIsFromStructConst(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(instancePtr); + return GetImpl()->ClassDefinitionIsFromStructConst(context, node); +} +KOALA_INTEROP_2(ClassDefinitionIsFromStructConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetFromStructModifier(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(instancePtr); + return GetImpl()->ClassDefinitionSetFromStructModifier(context, node); +} +KOALA_INTEROP_V2(ClassDefinitionSetFromStructModifier, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeRecheck(KNativePointer contextPtr, KNativePointer nodePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + GetImpl()->AstNodeRecheck(context, node); + return nullptr; +} +KOALA_INTEROP_2(AstNodeRecheck, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_AstNodeRebind(KNativePointer contextPtr, KNativePointer nodePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + GetImpl()->AstNodeRebind(context, node); + return nullptr; +} +KOALA_INTEROP_2(AstNodeRebind, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_AnnotationAllowedAnnotations(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer returnLen) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + std::size_t params_len = 0; + auto annotations = GetImpl()->AnnotationAllowedAnnotations(context, node, ¶ms_len); + return new std::vector(annotations, annotations + params_len); +} +KOALA_INTEROP_3(AnnotationAllowedAnnotations, KNativePointer, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_AnnotationAllowedAnnotationsConst(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer returnLen) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + std::size_t params_len = 0; + auto annotations = GetImpl()->AnnotationAllowedAnnotationsConst(context, node, ¶ms_len); + return new std::vector(annotations, annotations + params_len); +} +KOALA_INTEROP_3(AnnotationAllowedAnnotationsConst, KNativePointer, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_AstNodeVariableConst(KNativePointer contextPtr, KNativePointer nodePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->AstNodeVariableConst(context, node); +} +KOALA_INTEROP_2(AstNodeVariableConst, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_VariableDeclaration(KNativePointer contextPtr, KNativePointer variablePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto variable = reinterpret_cast(variablePtr); + + return GetImpl()->VariableDeclaration(context, variable); +} +KOALA_INTEROP_2(VariableDeclaration, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_DeclNode(KNativePointer contextPtr, KNativePointer declPtr) +{ + auto context = reinterpret_cast(contextPtr); + auto decl = reinterpret_cast(declPtr); + + return GetImpl()->DeclNode(context, decl); +} +KOALA_INTEROP_2(DeclNode, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_AstNodeScopeConst(KNativePointer contextPtr, KNativePointer nodePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + return GetImpl()->AstNodeScopeConst(context, node); +} +KOALA_INTEROP_2(AstNodeScopeConst, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_ScopeSetParent(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer parentPtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + auto parent = reinterpret_cast(parentPtr); + GetImpl()->ScopeSetParent(context, node, parent); + return node; +} +KOALA_INTEROP_3(ScopeSetParent, KNativePointer, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_CreateNumberLiteral(KNativePointer contextPtr, KDouble value) +{ + auto context = reinterpret_cast(contextPtr); + + return GetImpl()->CreateNumberLiteral(context, value); +} +KOALA_INTEROP_2(CreateNumberLiteral, KNativePointer, KNativePointer, KDouble) + +KNativePointer impl_ETSParserCreateExpression(KNativePointer contextPtr, KStringPtr& sourceCodePtr, KInt flagsT) +{ + auto context = reinterpret_cast(contextPtr); + auto flags = static_cast(flagsT); + + return GetImpl()->ETSParserCreateExpression(context, getStringCopy(sourceCodePtr), flags); +} +KOALA_INTEROP_3(ETSParserCreateExpression, KNativePointer, KNativePointer, KStringPtr, KInt) + +KBoolean impl_IsProgram(KNativePointer contextPtr, KNativePointer nodePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + return GetImpl()->AstNodeIsProgramConst(context, node); +} +KOALA_INTEROP_2(IsProgram, KBoolean, KNativePointer, KNativePointer) + +KBoolean impl_IsBlockStatement(KNativePointer nodePtr) +{ + auto node = reinterpret_cast(nodePtr); + return GetImpl()->IsBlockStatement(node); +} +KOALA_INTEROP_1(IsBlockStatement, KBoolean, KNativePointer) + +KNativePointer impl_ProceedToState(KNativePointer contextPtr, KInt state) +{ + auto context = reinterpret_cast(contextPtr); + return GetImpl()->ProceedToState(context, intToState(state)); +} +KOALA_INTEROP_2(ProceedToState, KNativePointer, KNativePointer, KInt) + +KNativePointer impl_ContextProgram(KNativePointer contextPtr) +{ + auto context = reinterpret_cast(contextPtr); + return GetImpl()->ContextProgram(context); +} +KOALA_INTEROP_1(ContextProgram, KNativePointer, KNativePointer) + +KNativePointer impl_ProgramAst(KNativePointer contextPtr, KNativePointer programPtr) +{ + auto context = reinterpret_cast(programPtr); + auto program = reinterpret_cast(programPtr); + return GetImpl()->ProgramAst(context, program); +} +KOALA_INTEROP_2(ProgramAst, KNativePointer, KNativePointer, KNativePointer) + +KBoolean impl_IsIdentifier(KNativePointer nodePtr) +{ + auto node = reinterpret_cast(nodePtr); + return GetImpl()->IsIdentifier(node); +} +KOALA_INTEROP_1(IsIdentifier, KBoolean, KNativePointer) + +KNativePointer impl_CreateContextFromString(KNativePointer configPtr, KStringPtr& sourcePtr, KStringPtr& filenamePtr) +{ + auto config = reinterpret_cast(configPtr); + return GetImpl()->CreateContextFromString(config, sourcePtr.data(), filenamePtr.data()); +} +KOALA_INTEROP_3(CreateContextFromString, KNativePointer, KNativePointer, KStringPtr, KStringPtr) + +KNativePointer impl_CreateContextFromFile(KNativePointer configPtr, KStringPtr& filenamePtr) +{ + auto config = reinterpret_cast(configPtr); + return GetImpl()->CreateContextFromFile(config, getStringCopy(filenamePtr)); +} +KOALA_INTEROP_2(CreateContextFromFile, KNativePointer, KNativePointer, KStringPtr) + +KInt impl_ContextState(KNativePointer contextPtr) +{ + auto context = reinterpret_cast(contextPtr); + + return static_cast(GetImpl()->ContextState(context)); +} +KOALA_INTEROP_1(ContextState, KInt, KNativePointer) + +KNativePointer impl_ContextErrorMessage(KNativePointer contextPtr) +{ + auto context = reinterpret_cast(contextPtr); + + return new string(GetImpl()->ContextErrorMessage(context)); +} +KOALA_INTEROP_1(ContextErrorMessage, KNativePointer, KNativePointer) + +KNativePointer impl_CallExpressionSignature(KNativePointer context, KNativePointer classInstance) +{ + const auto _context = reinterpret_cast(context); + const auto _classInstance = reinterpret_cast(classInstance); + const auto result = GetImpl()->CallExpressionSignature(_context, _classInstance); + return result; +} +KOALA_INTEROP_2(CallExpressionSignature, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_SignatureFunction(KNativePointer context, KNativePointer classInstance) +{ + const auto _context = reinterpret_cast(context); + const auto _classInstance = reinterpret_cast(classInstance); + const auto result = GetImpl()->SignatureFunction(_context, _classInstance); + return result; +} +KOALA_INTEROP_2(SignatureFunction, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_DeclarationFromIdentifier(KNativePointer context, KNativePointer identifier) +{ + const auto _context = reinterpret_cast(context); + const auto _identifier = reinterpret_cast(identifier); + const auto result = GetImpl()->DeclarationFromIdentifier(_context, _identifier); + return result; +} +KOALA_INTEROP_2(DeclarationFromIdentifier, KNativePointer, KNativePointer, KNativePointer) + +static KNativePointer impl_ProgramExternalSources(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto&& instance = reinterpret_cast(instancePtr); + std::size_t source_len = 0; + auto external_sources = GetImpl()->ProgramExternalSources(context, instance, &source_len); + return new std::vector(external_sources, external_sources + source_len); +} +KOALA_INTEROP_2(ProgramExternalSources, KNativePointer, KNativePointer, KNativePointer); + +static KNativePointer impl_ExternalSourceName(KNativePointer instance) +{ + auto&& _instance_ = reinterpret_cast(instance); + auto&& _result_ = GetImpl()->ExternalSourceName(_instance_); + return new std::string(_result_); +} +KOALA_INTEROP_1(ExternalSourceName, KNativePointer, KNativePointer); + +static KNativePointer impl_ExternalSourcePrograms(KNativePointer instance) +{ + auto&& _instance_ = reinterpret_cast(instance); + std::size_t program_len = 0; + auto programs = GetImpl()->ExternalSourcePrograms(_instance_, &program_len); + return new std::vector(programs, programs + program_len); +} +KOALA_INTEROP_1(ExternalSourcePrograms, KNativePointer, KNativePointer); + +KBoolean impl_IsClassProperty(KNativePointer nodePtr) +{ + auto node = reinterpret_cast(nodePtr); + return GetImpl()->IsClassProperty(node); +} +KOALA_INTEROP_1(IsClassProperty, KBoolean, KNativePointer) + +KBoolean impl_IsETSUnionType(KNativePointer nodePtr) +{ + auto node = reinterpret_cast(nodePtr); + return GetImpl()->IsETSUnionType(node); +} +KOALA_INTEROP_1(IsETSUnionType, KBoolean, KNativePointer) + +KBoolean impl_IsETSFunctionType(KNativePointer nodePtr) +{ + auto node = reinterpret_cast(nodePtr); + return GetImpl()->IsETSFunctionType(node); +} +KOALA_INTEROP_1(IsETSFunctionType, KBoolean, KNativePointer) + +KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPtr &outputDeclEts, KStringPtr &outputEts, + KBoolean exportAll) +{ + auto context = reinterpret_cast(contextPtr); + return GetImpl()->GenerateTsDeclarationsFromContext(context, outputDeclEts.data(), outputEts.data(), exportAll); +} +KOALA_INTEROP_4(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean) + +void impl_InsertETSImportDeclarationAndParse(KNativePointer context, KNativePointer importDeclaration) +{ + const auto _context = reinterpret_cast(context); + const auto _ast = reinterpret_cast(importDeclaration); + GetImpl()->InsertETSImportDeclarationAndParse(_context, _ast); + return ; +} +KOALA_INTEROP_V2(InsertETSImportDeclarationAndParse, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParserGetImportPathManager(KNativePointer contextPtr) +{ + auto context = reinterpret_cast(contextPtr); + return GetImpl()->ETSParserGetImportPathManager(context); +} +KOALA_INTEROP_1(ETSParserGetImportPathManager, KNativePointer, KNativePointer); + +KNativePointer impl_CreateSourcePosition(KNativePointer context, KInt index, KInt line) +{ + auto&& _context_ = reinterpret_cast(context); + return GetImpl()->CreateSourcePosition(_context_, index, line); +} +KOALA_INTEROP_3(CreateSourcePosition, KNativePointer, KNativePointer, KInt, KInt); + +KInt impl_SourcePositionIndex(KNativePointer context, KNativePointer instance) +{ + auto&& _context_ = reinterpret_cast(context); + auto&& _instance_ = reinterpret_cast(instance); + return GetImpl()->SourcePositionIndex(_context_, _instance_); +} +KOALA_INTEROP_2(SourcePositionIndex, KInt, KNativePointer, KNativePointer); + +KInt impl_SourcePositionLine(KNativePointer context, KNativePointer instance) +{ + auto&& _context_ = reinterpret_cast(context); + auto&& _instance_ = reinterpret_cast(instance); + return GetImpl()->SourcePositionLine(_context_, _instance_); +} +KOALA_INTEROP_2(SourcePositionLine, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_CreateSourceRange(KNativePointer context, KNativePointer start, KNativePointer end) +{ + auto&& _context_ = reinterpret_cast(context); + auto&& _start_ = reinterpret_cast(start); + auto&& _end_ = reinterpret_cast(end); + return GetImpl()->CreateSourceRange(_context_, _start_, _end_); +} +KOALA_INTEROP_3(CreateSourceRange, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSStringLiteralType(KNativePointer contextPtr, KStringPtr& str) +{ + auto context = reinterpret_cast(contextPtr); + const auto _str = getStringCopy(str); + return GetImpl()->CreateETSStringLiteralType(context, _str); +} +KOALA_INTEROP_2(CreateETSStringLiteralType, KNativePointer, KNativePointer, KStringPtr) \ No newline at end of file diff --git a/koala-wrapper/native/src/common.cc b/koala-wrapper/native/src/common.cc new file mode 100644 index 000000000..7ddc761cc --- /dev/null +++ b/koala-wrapper/native/src/common.cc @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2022-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 + +using std::string, std::cout, std::endl, std::vector; + +static es2panda_Impl *impl = nullptr; + +#ifdef KOALA_WINDOWS + #include + #define PLUGIN_DIR "windows_host_tools" + #define LIB_PREFIX "lib" + #define LIB_SUFFIX ".dll" +#endif + +#ifdef KOALA_LINUX + #include + + #ifdef __x86_64__ + #define PLUGIN_DIR "linux_host_tools" + #else + #define PLUGIN_DIR "linux_arm64_host_tools" + #endif + + #define LIB_PREFIX "lib" + #define LIB_SUFFIX ".so" +#endif + +const char* LIB_ES2PANDA_PUBLIC = LIB_PREFIX "es2panda_public" LIB_SUFFIX; + +void* FindLibrary() { + std::string libraryName; + char* envValue = getenv("PANDA_SDK_PATH"); + if (envValue) { + libraryName = std::string(envValue) + ("/" PLUGIN_DIR "/lib/") + LIB_ES2PANDA_PUBLIC; + } else { + libraryName = LIB_ES2PANDA_PUBLIC; + } + return loadLibrary(libraryName); +} + +es2panda_Impl *GetImpl() { + if (impl) { + return impl; + } + auto library = FindLibrary(); + if (!library) { + std::cout << "Cannot find " << LIB_ES2PANDA_PUBLIC << endl; + } + auto symbol = findSymbol(library, "es2panda_GetImpl"); + if (!symbol) { + std::cout << "Cannot find Impl Entry point" << endl; + } + impl = reinterpret_cast(symbol)(ES2PANDA_LIB_VERSION); + return impl; +} + +es2panda_ContextState intToState(KInt state) +{ + return es2panda_ContextState(state); +} + +string getString(KStringPtr ptr) { + return ptr.data(); +} + +char* getStringCopy(KStringPtr& ptr) { + return strdup(ptr.c_str()); +} + +inline KUInt unpackUInt(const KByte* bytes) { + const KUInt BYTE_0 = 0; + const KUInt BYTE_1 = 1; + const KUInt BYTE_2 = 2; + const KUInt BYTE_3 = 3; + + const KUInt BYTE_1_SHIFT = 8; + const KUInt BYTE_2_SHIFT = 16; + const KUInt BYTE_3_SHIFT = 24; + return ( + bytes[BYTE_0] + | (bytes[BYTE_1] << BYTE_1_SHIFT) + | (bytes[BYTE_2] << BYTE_2_SHIFT) + | (bytes[BYTE_3] << BYTE_3_SHIFT) + ); +} + +KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr) { + 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; + } + return GetImpl()->CreateConfig(argc, argv); +} +KOALA_INTEROP_2(CreateConfig, KNativePointer, KInt, KStringArray) + +KNativePointer impl_DestroyConfig(KNativePointer configPtr) { + auto config = reinterpret_cast(configPtr); + GetImpl()->DestroyConfig(config); + return nullptr; +} +KOALA_INTEROP_1(DestroyConfig, KNativePointer, KNativePointer) + +KNativePointer impl_DestroyContext(KNativePointer contextPtr) { + auto context = reinterpret_cast(contextPtr); + GetImpl()->DestroyContext(context); + return nullptr; +} +KOALA_INTEROP_1(DestroyContext, KNativePointer, KNativePointer) + +KNativePointer impl_UpdateCallExpression( + KNativePointer contextPtr, + KNativePointer nodePtr, + KNativePointer calleePtr, + KNativePointerArray argumentsPtr, + KInt argumentsLen, + KNativePointer typeParamsPtr, + KBoolean optionalT, + KBoolean trailingCommaT +) { + auto node = reinterpret_cast(nodePtr); + auto context = reinterpret_cast(contextPtr); + auto callee = reinterpret_cast(calleePtr); + auto arguments = reinterpret_cast(argumentsPtr); + auto typeParams = reinterpret_cast(typeParamsPtr); + auto optional = static_cast(optionalT); + auto trailingComma = static_cast(trailingCommaT); + + auto nn = GetImpl()->CreateCallExpression( + context, callee, arguments, argumentsLen, typeParams, optional, trailingComma + ); + GetImpl()->AstNodeSetOriginalNode(context, nn, node); + return nn; +} +KOALA_INTEROP_8(UpdateCallExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KNativePointer, KBoolean, KBoolean) + +KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer nodePtr) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return + (GetImpl()->IdentifierIsOptionalConst(context, node) ? (1 << 0) : 0) | + (GetImpl()->IdentifierIsReferenceConst(context, node) ? (1 << 1) : 0) | + (GetImpl()->IdentifierIsTdzConst(context, node) ? (1 << 2) : 0); +} +KOALA_INTEROP_2(IdentifierIdentifierFlags, KInt, KNativePointer, KNativePointer) + +/* +TODO: NOT FROM API (shouldn't be there) +----------------------------------------------------------------------------------------------------------------------------- +*/ + +es2panda_AstNode * cachedParentNode; +es2panda_Context * cachedContext; + +static void changeParent(es2panda_AstNode *child) +{ + GetImpl()->AstNodeSetParent(cachedContext, child, cachedParentNode); +} + +static void SetRightParent(es2panda_AstNode *node, void *arg) +{ + es2panda_Context *ctx = static_cast(arg); + cachedContext = ctx; + cachedParentNode = node; + + GetImpl()->AstNodeIterateConst(ctx, node, changeParent); +} + +KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer programPtr) { + auto context = reinterpret_cast(contextPtr); + auto program = reinterpret_cast(programPtr); + + GetImpl()->AstNodeForEach(program, SetRightParent, context); + return program; +} +KOALA_INTEROP_2(AstNodeUpdateAll, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_AstNodeUpdateChildren(KNativePointer contextPtr, KNativePointer nodePtr) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + cachedParentNode = node; + + GetImpl()->AstNodeIterateConst(context, node, changeParent); + return node; +} +KOALA_INTEROP_2(AstNodeUpdateChildren, KNativePointer, KNativePointer, KNativePointer) + +std::vector cachedChildren; + +static void visitChild(es2panda_AstNode *node) { + cachedChildren.emplace_back(node); +} + +KNativePointer impl_AstNodeChildren( + KNativePointer contextPtr, + KNativePointer nodePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + cachedContext = context; + cachedChildren.clear(); + + GetImpl()->AstNodeIterateConst(context, node, visitChild); + return new std::vector(cachedChildren); +} +KOALA_INTEROP_2(AstNodeChildren, KNativePointer, KNativePointer, KNativePointer) + +/* +----------------------------------------------------------------------------------------------------------------------------- +*/ diff --git a/koala-wrapper/native/src/generated/bridges.cc b/koala-wrapper/native/src/generated/bridges.cc new file mode 100644 index 000000000..f1ca609eb --- /dev/null +++ b/koala-wrapper/native/src/generated/bridges.cc @@ -0,0 +1,11764 @@ +/* + * Copyright (c) 2022-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 + +KNativePointer impl_CreateLabelledStatement(KNativePointer context, KNativePointer ident, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _ident = reinterpret_cast(ident); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->CreateLabelledStatement(_context, _ident, _body); + return result; +} +KOALA_INTEROP_3(CreateLabelledStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateLabelledStatement(KNativePointer context, KNativePointer original, KNativePointer ident, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _ident = reinterpret_cast(ident); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->UpdateLabelledStatement(_context, _original, _ident, _body); + return result; +} +KOALA_INTEROP_4(UpdateLabelledStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_LabelledStatementBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->LabelledStatementBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(LabelledStatementBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_LabelledStatementIdentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->LabelledStatementIdentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(LabelledStatementIdentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_LabelledStatementIdent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->LabelledStatementIdent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(LabelledStatementIdent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_LabelledStatementGetReferencedStatementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->LabelledStatementGetReferencedStatementConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(LabelledStatementGetReferencedStatementConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateThrowStatement(KNativePointer context, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->CreateThrowStatement(_context, _argument); + return result; +} +KOALA_INTEROP_2(CreateThrowStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateThrowStatement(KNativePointer context, KNativePointer original, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->UpdateThrowStatement(_context, _original, _argument); + return result; +} +KOALA_INTEROP_3(UpdateThrowStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ThrowStatementArgumentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ThrowStatementArgumentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ThrowStatementArgumentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateClassProperty(KNativePointer context, KNativePointer key, KNativePointer value, KNativePointer typeAnnotation, KInt modifiers, KBoolean isComputed) +{ + const auto _context = reinterpret_cast(context); + const auto _key = reinterpret_cast(key); + const auto _value = reinterpret_cast(value); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _modifiers = static_cast(modifiers); + const auto _isComputed = static_cast(isComputed); + auto result = GetImpl()->CreateClassProperty(_context, _key, _value, _typeAnnotation, _modifiers, _isComputed); + return result; +} +KOALA_INTEROP_6(CreateClassProperty, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KBoolean); + +KNativePointer impl_UpdateClassProperty(KNativePointer context, KNativePointer original, KNativePointer key, KNativePointer value, KNativePointer typeAnnotation, KInt modifiers, KBoolean isComputed) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _key = reinterpret_cast(key); + const auto _value = reinterpret_cast(value); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _modifiers = static_cast(modifiers); + const auto _isComputed = static_cast(isComputed); + auto result = GetImpl()->UpdateClassProperty(_context, _original, _key, _value, _typeAnnotation, _modifiers, _isComputed); + return result; +} +KOALA_INTEROP_7(UpdateClassProperty, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KBoolean); + +KNativePointer impl_ClassPropertyTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassPropertyTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassPropertyTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassPropertySetTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->ClassPropertySetTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(ClassPropertySetTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassPropertyAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassPropertyAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassPropertyAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassPropertyAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassPropertyAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassPropertyAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassPropertySetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->ClassPropertySetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(ClassPropertySetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateTSVoidKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSVoidKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSVoidKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSVoidKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSVoidKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSVoidKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSFunctionTypeIr(KNativePointer context, KNativePointer signature, KInt funcFlags) +{ + const auto _context = reinterpret_cast(context); + const auto _signature = reinterpret_cast(signature); + const auto _funcFlags = static_cast(funcFlags); + auto result = GetImpl()->CreateETSFunctionTypeIr(_context, _signature, _funcFlags); + return result; +} +KOALA_INTEROP_3(CreateETSFunctionTypeIr, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateETSFunctionTypeIr(KNativePointer context, KNativePointer original, KNativePointer signature, KInt funcFlags) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _signature = reinterpret_cast(signature); + const auto _funcFlags = static_cast(funcFlags); + auto result = GetImpl()->UpdateETSFunctionTypeIr(_context, _original, _signature, _funcFlags); + return result; +} +KOALA_INTEROP_4(UpdateETSFunctionTypeIr, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_ETSFunctionTypeIrTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSFunctionTypeIrTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSFunctionTypeIrParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSFunctionTypeIrParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSFunctionTypeIrParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSFunctionTypeIrReturnTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrReturnTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrReturnTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSFunctionTypeIrReturnType(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrReturnType(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrReturnType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSFunctionTypeIrFunctionalInterface(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrFunctionalInterface(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrFunctionalInterface, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSFunctionTypeIrFunctionalInterfaceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrFunctionalInterfaceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrFunctionalInterfaceConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSFunctionTypeIrSetFunctionalInterface(KNativePointer context, KNativePointer receiver, KNativePointer functionalInterface) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _functionalInterface = reinterpret_cast(functionalInterface); + GetImpl()->ETSFunctionTypeIrSetFunctionalInterface(_context, _receiver, _functionalInterface); + return ; +} +KOALA_INTEROP_V3(ETSFunctionTypeIrSetFunctionalInterface, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_ETSFunctionTypeIrFlags(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrFlags(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrFlags, KInt, KNativePointer, KNativePointer); + +KBoolean impl_ETSFunctionTypeIrIsThrowingConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrIsThrowingConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrIsThrowingConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ETSFunctionTypeIrIsRethrowingConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrIsRethrowingConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrIsRethrowingConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ETSFunctionTypeIrIsExtensionFunctionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSFunctionTypeIrIsExtensionFunctionConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSFunctionTypeIrIsExtensionFunctionConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeOperator(KNativePointer context, KNativePointer type, KInt operatorType) +{ + const auto _context = reinterpret_cast(context); + const auto _type = reinterpret_cast(type); + const auto _operatorType = static_cast(operatorType); + auto result = GetImpl()->CreateTSTypeOperator(_context, _type, _operatorType); + return result; +} +KOALA_INTEROP_3(CreateTSTypeOperator, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateTSTypeOperator(KNativePointer context, KNativePointer original, KNativePointer type, KInt operatorType) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _type = reinterpret_cast(type); + const auto _operatorType = static_cast(operatorType); + auto result = GetImpl()->UpdateTSTypeOperator(_context, _original, _type, _operatorType); + return result; +} +KOALA_INTEROP_4(UpdateTSTypeOperator, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_TSTypeOperatorTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeOperatorTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeOperatorTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSTypeOperatorIsReadonlyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeOperatorIsReadonlyConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSTypeOperatorIsReadonlyConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSTypeOperatorIsKeyofConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeOperatorIsKeyofConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSTypeOperatorIsKeyofConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSTypeOperatorIsUniqueConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeOperatorIsUniqueConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSTypeOperatorIsUniqueConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateIfStatement(KNativePointer context, KNativePointer test, KNativePointer consequent, KNativePointer alternate) +{ + const auto _context = reinterpret_cast(context); + const auto _test = reinterpret_cast(test); + const auto _consequent = reinterpret_cast(consequent); + const auto _alternate = reinterpret_cast(alternate); + auto result = GetImpl()->CreateIfStatement(_context, _test, _consequent, _alternate); + return result; +} +KOALA_INTEROP_4(CreateIfStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateIfStatement(KNativePointer context, KNativePointer original, KNativePointer test, KNativePointer consequent, KNativePointer alternate) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _test = reinterpret_cast(test); + const auto _consequent = reinterpret_cast(consequent); + const auto _alternate = reinterpret_cast(alternate); + auto result = GetImpl()->UpdateIfStatement(_context, _original, _test, _consequent, _alternate); + return result; +} +KOALA_INTEROP_5(UpdateIfStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IfStatementTestConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IfStatementTestConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(IfStatementTestConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IfStatementTest(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IfStatementTest(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IfStatementTest, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IfStatementConsequentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IfStatementConsequentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(IfStatementConsequentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IfStatementConsequent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IfStatementConsequent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IfStatementConsequent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IfStatementAlternate(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IfStatementAlternate(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IfStatementAlternate, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IfStatementAlternateConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IfStatementAlternateConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(IfStatementAlternateConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSConstructorType(KNativePointer context, KNativePointer signature, KBoolean abstract) +{ + const auto _context = reinterpret_cast(context); + const auto _signature = reinterpret_cast(signature); + const auto _abstract = static_cast(abstract); + auto result = GetImpl()->CreateTSConstructorType(_context, _signature, _abstract); + return result; +} +KOALA_INTEROP_3(CreateTSConstructorType, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateTSConstructorType(KNativePointer context, KNativePointer original, KNativePointer signature, KBoolean abstract) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _signature = reinterpret_cast(signature); + const auto _abstract = static_cast(abstract); + auto result = GetImpl()->UpdateTSConstructorType(_context, _original, _signature, _abstract); + return result; +} +KOALA_INTEROP_4(UpdateTSConstructorType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSConstructorTypeTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConstructorTypeTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSConstructorTypeTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSConstructorTypeTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConstructorTypeTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSConstructorTypeTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSConstructorTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSConstructorTypeParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSConstructorTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSConstructorTypeReturnTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConstructorTypeReturnTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSConstructorTypeReturnTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSConstructorTypeReturnType(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConstructorTypeReturnType(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSConstructorTypeReturnType, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSConstructorTypeAbstractConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConstructorTypeAbstractConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSConstructorTypeAbstractConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateDecorator(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateDecorator(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateDecorator, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateDecorator(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateDecorator(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateDecorator, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_DecoratorExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->DecoratorExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(DecoratorExprConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSEnumDeclaration(KNativePointer context, KNativePointer key, KNativePointerArray members, KUInt membersSequenceLength, KBoolean isConst, KBoolean isStatic, KBoolean isDeclare) +{ + const auto _context = reinterpret_cast(context); + const auto _key = reinterpret_cast(key); + const auto _members = reinterpret_cast(members); + const auto _membersSequenceLength = static_cast(membersSequenceLength); + const auto _isConst = static_cast(isConst); + const auto _isStatic = static_cast(isStatic); + const auto _isDeclare = static_cast(isDeclare); + auto result = GetImpl()->CreateTSEnumDeclaration(_context, _key, _members, _membersSequenceLength, _isConst, _isStatic, _isDeclare); + return result; +} +KOALA_INTEROP_7(CreateTSEnumDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KBoolean, KBoolean, KBoolean); + +KNativePointer impl_UpdateTSEnumDeclaration(KNativePointer context, KNativePointer original, KNativePointer key, KNativePointerArray members, KUInt membersSequenceLength, KBoolean isConst, KBoolean isStatic, KBoolean isDeclare) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _key = reinterpret_cast(key); + const auto _members = reinterpret_cast(members); + const auto _membersSequenceLength = static_cast(membersSequenceLength); + const auto _isConst = static_cast(isConst); + const auto _isStatic = static_cast(isStatic); + const auto _isDeclare = static_cast(isDeclare); + auto result = GetImpl()->UpdateTSEnumDeclaration(_context, _original, _key, _members, _membersSequenceLength, _isConst, _isStatic, _isDeclare); + return result; +} +KOALA_INTEROP_8(UpdateTSEnumDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KBoolean, KBoolean, KBoolean); + +KNativePointer impl_TSEnumDeclarationKeyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumDeclarationKeyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSEnumDeclarationKeyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSEnumDeclarationKey(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumDeclarationKey(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSEnumDeclarationKey, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSEnumDeclarationMembersConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSEnumDeclarationMembersConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSEnumDeclarationMembersConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSEnumDeclarationInternalNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumDeclarationInternalNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(TSEnumDeclarationInternalNameConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSEnumDeclarationSetInternalName(KNativePointer context, KNativePointer receiver, KStringPtr& internalName) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _internalName = getStringCopy(internalName); + GetImpl()->TSEnumDeclarationSetInternalName(_context, _receiver, _internalName); + return ; +} +KOALA_INTEROP_V3(TSEnumDeclarationSetInternalName, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_TSEnumDeclarationBoxedClassConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumDeclarationBoxedClassConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSEnumDeclarationBoxedClassConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSEnumDeclarationSetBoxedClass(KNativePointer context, KNativePointer receiver, KNativePointer wrapperClass) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _wrapperClass = reinterpret_cast(wrapperClass); + GetImpl()->TSEnumDeclarationSetBoxedClass(_context, _receiver, _wrapperClass); + return ; +} +KOALA_INTEROP_V3(TSEnumDeclarationSetBoxedClass, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSEnumDeclarationIsConstConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumDeclarationIsConstConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSEnumDeclarationIsConstConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_TSEnumDeclarationDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSEnumDeclarationDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSEnumDeclarationDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSNeverKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSNeverKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSNeverKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSNeverKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSNeverKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSNeverKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateImportDefaultSpecifier(KNativePointer context, KNativePointer local) +{ + const auto _context = reinterpret_cast(context); + const auto _local = reinterpret_cast(local); + auto result = GetImpl()->CreateImportDefaultSpecifier(_context, _local); + return result; +} +KOALA_INTEROP_2(CreateImportDefaultSpecifier, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateImportDefaultSpecifier(KNativePointer context, KNativePointer original, KNativePointer local) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _local = reinterpret_cast(local); + auto result = GetImpl()->UpdateImportDefaultSpecifier(_context, _original, _local); + return result; +} +KOALA_INTEROP_3(UpdateImportDefaultSpecifier, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportDefaultSpecifierLocalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportDefaultSpecifierLocalConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ImportDefaultSpecifierLocalConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportDefaultSpecifierLocal(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportDefaultSpecifierLocal(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ImportDefaultSpecifierLocal, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateObjectExpression(KNativePointer context, KInt nodeType, KNativePointerArray properties, KUInt propertiesSequenceLength, KBoolean trailingComma) +{ + const auto _context = reinterpret_cast(context); + const auto _nodeType = static_cast(nodeType); + const auto _properties = reinterpret_cast(properties); + const auto _propertiesSequenceLength = static_cast(propertiesSequenceLength); + const auto _trailingComma = static_cast(trailingComma); + auto result = GetImpl()->CreateObjectExpression(_context, _nodeType, _properties, _propertiesSequenceLength, _trailingComma); + return result; +} +KOALA_INTEROP_5(CreateObjectExpression, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt, KBoolean); + +KNativePointer impl_UpdateObjectExpression(KNativePointer context, KNativePointer original, KInt nodeType, KNativePointerArray properties, KUInt propertiesSequenceLength, KBoolean trailingComma) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _nodeType = static_cast(nodeType); + const auto _properties = reinterpret_cast(properties); + const auto _propertiesSequenceLength = static_cast(propertiesSequenceLength); + const auto _trailingComma = static_cast(trailingComma); + auto result = GetImpl()->UpdateObjectExpression(_context, _original, _nodeType, _properties, _propertiesSequenceLength, _trailingComma); + return result; +} +KOALA_INTEROP_6(UpdateObjectExpression, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt, KBoolean); + +KNativePointer impl_ObjectExpressionPropertiesConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ObjectExpressionPropertiesConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ObjectExpressionPropertiesConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ObjectExpressionIsDeclarationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ObjectExpressionIsDeclarationConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ObjectExpressionIsDeclarationConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ObjectExpressionIsOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ObjectExpressionIsOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ObjectExpressionIsOptionalConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_ObjectExpressionDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ObjectExpressionDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ObjectExpressionDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ObjectExpressionValidateExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ObjectExpressionValidateExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ObjectExpressionValidateExpression, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ObjectExpressionConvertibleToObjectPattern(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ObjectExpressionConvertibleToObjectPattern(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ObjectExpressionConvertibleToObjectPattern, KBoolean, KNativePointer, KNativePointer); + +void impl_ObjectExpressionSetDeclaration(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ObjectExpressionSetDeclaration(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ObjectExpressionSetDeclaration, KNativePointer, KNativePointer); + +void impl_ObjectExpressionSetOptional(KNativePointer context, KNativePointer receiver, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _optional_arg = static_cast(optional_arg); + GetImpl()->ObjectExpressionSetOptional(_context, _receiver, _optional_arg); + return ; +} +KOALA_INTEROP_V3(ObjectExpressionSetOptional, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_ObjectExpressionTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ObjectExpressionTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ObjectExpressionTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ObjectExpressionSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->ObjectExpressionSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(ObjectExpressionSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateImportSpecifier(KNativePointer context, KNativePointer imported, KNativePointer local) +{ + const auto _context = reinterpret_cast(context); + const auto _imported = reinterpret_cast(imported); + const auto _local = reinterpret_cast(local); + auto result = GetImpl()->CreateImportSpecifier(_context, _imported, _local); + return result; +} +KOALA_INTEROP_3(CreateImportSpecifier, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateImportSpecifier(KNativePointer context, KNativePointer original, KNativePointer imported, KNativePointer local) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _imported = reinterpret_cast(imported); + const auto _local = reinterpret_cast(local); + auto result = GetImpl()->UpdateImportSpecifier(_context, _original, _imported, _local); + return result; +} +KOALA_INTEROP_4(UpdateImportSpecifier, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportSpecifierImported(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportSpecifierImported(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ImportSpecifierImported, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportSpecifierImportedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportSpecifierImportedConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ImportSpecifierImportedConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportSpecifierLocal(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportSpecifierLocal(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ImportSpecifierLocal, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportSpecifierLocalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportSpecifierLocalConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ImportSpecifierLocalConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateConditionalExpression(KNativePointer context, KNativePointer test, KNativePointer consequent, KNativePointer alternate) +{ + const auto _context = reinterpret_cast(context); + const auto _test = reinterpret_cast(test); + const auto _consequent = reinterpret_cast(consequent); + const auto _alternate = reinterpret_cast(alternate); + auto result = GetImpl()->CreateConditionalExpression(_context, _test, _consequent, _alternate); + return result; +} +KOALA_INTEROP_4(CreateConditionalExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateConditionalExpression(KNativePointer context, KNativePointer original, KNativePointer test, KNativePointer consequent, KNativePointer alternate) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _test = reinterpret_cast(test); + const auto _consequent = reinterpret_cast(consequent); + const auto _alternate = reinterpret_cast(alternate); + auto result = GetImpl()->UpdateConditionalExpression(_context, _original, _test, _consequent, _alternate); + return result; +} +KOALA_INTEROP_5(UpdateConditionalExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ConditionalExpressionTestConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ConditionalExpressionTestConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ConditionalExpressionTestConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ConditionalExpressionTest(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ConditionalExpressionTest(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ConditionalExpressionTest, KNativePointer, KNativePointer, KNativePointer); + +void impl_ConditionalExpressionSetTest(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->ConditionalExpressionSetTest(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(ConditionalExpressionSetTest, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ConditionalExpressionConsequentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ConditionalExpressionConsequentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ConditionalExpressionConsequentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ConditionalExpressionConsequent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ConditionalExpressionConsequent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ConditionalExpressionConsequent, KNativePointer, KNativePointer, KNativePointer); + +void impl_ConditionalExpressionSetConsequent(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->ConditionalExpressionSetConsequent(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(ConditionalExpressionSetConsequent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ConditionalExpressionAlternateConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ConditionalExpressionAlternateConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ConditionalExpressionAlternateConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ConditionalExpressionAlternate(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ConditionalExpressionAlternate(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ConditionalExpressionAlternate, KNativePointer, KNativePointer, KNativePointer); + +void impl_ConditionalExpressionSetAlternate(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->ConditionalExpressionSetAlternate(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(ConditionalExpressionSetAlternate, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateCallExpression(KNativePointer context, KNativePointer callee, KNativePointerArray _arguments, KUInt _argumentsSequenceLength, KNativePointer typeParams, KBoolean optional_arg, KBoolean trailingComma) +{ + const auto _context = reinterpret_cast(context); + const auto _callee = reinterpret_cast(callee); + const auto __arguments = reinterpret_cast(_arguments); + const auto __argumentsSequenceLength = static_cast(_argumentsSequenceLength); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _optional_arg = static_cast(optional_arg); + const auto _trailingComma = static_cast(trailingComma); + auto result = GetImpl()->CreateCallExpression(_context, _callee, __arguments, __argumentsSequenceLength, _typeParams, _optional_arg, _trailingComma); + return result; +} +KOALA_INTEROP_7(CreateCallExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_CreateCallExpression1(KNativePointer context, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->CreateCallExpression1(_context, _other); + return result; +} +KOALA_INTEROP_2(CreateCallExpression1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateCallExpression1(KNativePointer context, KNativePointer original, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->UpdateCallExpression1(_context, _original, _other); + return result; +} +KOALA_INTEROP_3(UpdateCallExpression1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CallExpressionCalleeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionCalleeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(CallExpressionCalleeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CallExpressionCallee(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionCallee(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CallExpressionCallee, KNativePointer, KNativePointer, KNativePointer); + +void impl_CallExpressionSetCallee(KNativePointer context, KNativePointer receiver, KNativePointer callee) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _callee = reinterpret_cast(callee); + GetImpl()->CallExpressionSetCallee(_context, _receiver, _callee); + return ; +} +KOALA_INTEROP_V3(CallExpressionSetCallee, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CallExpressionTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(CallExpressionTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CallExpressionTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CallExpressionTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CallExpressionArgumentsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->CallExpressionArgumentsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(CallExpressionArgumentsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CallExpressionArguments(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->CallExpressionArguments(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(CallExpressionArguments, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_CallExpressionHasTrailingCommaConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionHasTrailingCommaConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CallExpressionHasTrailingCommaConst, KBoolean, KNativePointer, KNativePointer); + +void impl_CallExpressionSetTypeParams(KNativePointer context, KNativePointer receiver, KNativePointer typeParams) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeParams = reinterpret_cast(typeParams); + GetImpl()->CallExpressionSetTypeParams(_context, _receiver, _typeParams); + return ; +} +KOALA_INTEROP_V3(CallExpressionSetTypeParams, KNativePointer, KNativePointer, KNativePointer); + +void impl_CallExpressionSetTrailingBlock(KNativePointer context, KNativePointer receiver, KNativePointer block) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _block = reinterpret_cast(block); + GetImpl()->CallExpressionSetTrailingBlock(_context, _receiver, _block); + return ; +} +KOALA_INTEROP_V3(CallExpressionSetTrailingBlock, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_CallExpressionIsExtensionAccessorCall(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionIsExtensionAccessorCall(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CallExpressionIsExtensionAccessorCall, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CallExpressionTrailingBlockConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionTrailingBlockConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(CallExpressionTrailingBlockConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_CallExpressionSetIsTrailingBlockInNewLine(KNativePointer context, KNativePointer receiver, KBoolean isNewLine) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _isNewLine = static_cast(isNewLine); + GetImpl()->CallExpressionSetIsTrailingBlockInNewLine(_context, _receiver, _isNewLine); + return ; +} +KOALA_INTEROP_V3(CallExpressionSetIsTrailingBlockInNewLine, KNativePointer, KNativePointer, KBoolean); + +KBoolean impl_CallExpressionIsTrailingBlockInNewLineConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionIsTrailingBlockInNewLineConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CallExpressionIsTrailingBlockInNewLineConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_CallExpressionIsETSConstructorCallConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CallExpressionIsETSConstructorCallConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CallExpressionIsETSConstructorCallConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateBigIntLiteral(KNativePointer context, KStringPtr& src) +{ + const auto _context = reinterpret_cast(context); + const auto _src = getStringCopy(src); + auto result = GetImpl()->CreateBigIntLiteral(_context, _src); + return result; +} +KOALA_INTEROP_2(CreateBigIntLiteral, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_UpdateBigIntLiteral(KNativePointer context, KNativePointer original, KStringPtr& src) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _src = getStringCopy(src); + auto result = GetImpl()->UpdateBigIntLiteral(_context, _original, _src); + return result; +} +KOALA_INTEROP_3(UpdateBigIntLiteral, KNativePointer, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_BigIntLiteralStrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BigIntLiteralStrConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(BigIntLiteralStrConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassElementId(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassElementId(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassElementId, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassElementIdConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassElementIdConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassElementIdConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassElementKey(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassElementKey(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassElementKey, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassElementKeyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassElementKeyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassElementKeyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassElementValue(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassElementValue(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassElementValue, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassElementSetValue(KNativePointer context, KNativePointer receiver, KNativePointer value) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _value = reinterpret_cast(value); + GetImpl()->ClassElementSetValue(_context, _receiver, _value); + return ; +} +KOALA_INTEROP_V3(ClassElementSetValue, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassElementValueConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassElementValueConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassElementValueConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ClassElementIsPrivateElementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassElementIsPrivateElementConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassElementIsPrivateElementConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_ClassElementDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassElementDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassElementDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ClassElementIsComputedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassElementIsComputedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassElementIsComputedConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ClassElementAddDecorator(KNativePointer context, KNativePointer receiver, KNativePointer decorator) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _decorator = reinterpret_cast(decorator); + GetImpl()->ClassElementAddDecorator(_context, _receiver, _decorator); + return ; +} +KOALA_INTEROP_V3(ClassElementAddDecorator, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_ClassElementToPrivateFieldKindConst(KNativePointer context, KNativePointer receiver, KBoolean isStatic) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _isStatic = static_cast(isStatic); + auto result = GetImpl()->ClassElementToPrivateFieldKindConst(_context, _receiver, _isStatic); + return result; +} +KOALA_INTEROP_3(ClassElementToPrivateFieldKindConst, KInt, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_CreateTSImportType(KNativePointer context, KNativePointer param, KNativePointer typeParams, KNativePointer qualifier, KBoolean isTypeof) +{ + const auto _context = reinterpret_cast(context); + const auto _param = reinterpret_cast(param); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _qualifier = reinterpret_cast(qualifier); + const auto _isTypeof = static_cast(isTypeof); + auto result = GetImpl()->CreateTSImportType(_context, _param, _typeParams, _qualifier, _isTypeof); + return result; +} +KOALA_INTEROP_5(CreateTSImportType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateTSImportType(KNativePointer context, KNativePointer original, KNativePointer param, KNativePointer typeParams, KNativePointer qualifier, KBoolean isTypeof) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _param = reinterpret_cast(param); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _qualifier = reinterpret_cast(qualifier); + const auto _isTypeof = static_cast(isTypeof); + auto result = GetImpl()->UpdateTSImportType(_context, _original, _param, _typeParams, _qualifier, _isTypeof); + return result; +} +KOALA_INTEROP_6(UpdateTSImportType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSImportTypeParamConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSImportTypeParamConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSImportTypeParamConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSImportTypeTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSImportTypeTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSImportTypeTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSImportTypeQualifierConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSImportTypeQualifierConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSImportTypeQualifierConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSImportTypeIsTypeofConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSImportTypeIsTypeofConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSImportTypeIsTypeofConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTaggedTemplateExpression(KNativePointer context, KNativePointer tag, KNativePointer quasi, KNativePointer typeParams) +{ + const auto _context = reinterpret_cast(context); + const auto _tag = reinterpret_cast(tag); + const auto _quasi = reinterpret_cast(quasi); + const auto _typeParams = reinterpret_cast(typeParams); + auto result = GetImpl()->CreateTaggedTemplateExpression(_context, _tag, _quasi, _typeParams); + return result; +} +KOALA_INTEROP_4(CreateTaggedTemplateExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTaggedTemplateExpression(KNativePointer context, KNativePointer original, KNativePointer tag, KNativePointer quasi, KNativePointer typeParams) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _tag = reinterpret_cast(tag); + const auto _quasi = reinterpret_cast(quasi); + const auto _typeParams = reinterpret_cast(typeParams); + auto result = GetImpl()->UpdateTaggedTemplateExpression(_context, _original, _tag, _quasi, _typeParams); + return result; +} +KOALA_INTEROP_5(UpdateTaggedTemplateExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TaggedTemplateExpressionTagConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TaggedTemplateExpressionTagConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TaggedTemplateExpressionTagConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TaggedTemplateExpressionQuasiConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TaggedTemplateExpressionQuasiConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TaggedTemplateExpressionQuasiConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TaggedTemplateExpressionTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TaggedTemplateExpressionTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TaggedTemplateExpressionTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateFunctionDeclaration(KNativePointer context, KNativePointer func, KNativePointerArray annotations, KUInt annotationsSequenceLength, KBoolean isAnonymous) +{ + const auto _context = reinterpret_cast(context); + const auto _func = reinterpret_cast(func); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + const auto _isAnonymous = static_cast(isAnonymous); + auto result = GetImpl()->CreateFunctionDeclaration(_context, _func, _annotations, _annotationsSequenceLength, _isAnonymous); + return result; +} +KOALA_INTEROP_5(CreateFunctionDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KBoolean); + +KNativePointer impl_UpdateFunctionDeclaration(KNativePointer context, KNativePointer original, KNativePointer func, KNativePointerArray annotations, KUInt annotationsSequenceLength, KBoolean isAnonymous) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _func = reinterpret_cast(func); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + const auto _isAnonymous = static_cast(isAnonymous); + auto result = GetImpl()->UpdateFunctionDeclaration(_context, _original, _func, _annotations, _annotationsSequenceLength, _isAnonymous); + return result; +} +KOALA_INTEROP_6(UpdateFunctionDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KBoolean); + +KNativePointer impl_CreateFunctionDeclaration1(KNativePointer context, KNativePointer func, KBoolean isAnonymous) +{ + const auto _context = reinterpret_cast(context); + const auto _func = reinterpret_cast(func); + const auto _isAnonymous = static_cast(isAnonymous); + auto result = GetImpl()->CreateFunctionDeclaration1(_context, _func, _isAnonymous); + return result; +} +KOALA_INTEROP_3(CreateFunctionDeclaration1, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateFunctionDeclaration1(KNativePointer context, KNativePointer original, KNativePointer func, KBoolean isAnonymous) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _func = reinterpret_cast(func); + const auto _isAnonymous = static_cast(isAnonymous); + auto result = GetImpl()->UpdateFunctionDeclaration1(_context, _original, _func, _isAnonymous); + return result; +} +KOALA_INTEROP_4(UpdateFunctionDeclaration1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_FunctionDeclarationFunction(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionDeclarationFunction(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionDeclarationFunction, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_FunctionDeclarationIsAnonymousConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionDeclarationIsAnonymousConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionDeclarationIsAnonymousConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionDeclarationFunctionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionDeclarationFunctionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(FunctionDeclarationFunctionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionDeclarationAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->FunctionDeclarationAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(FunctionDeclarationAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionDeclarationAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->FunctionDeclarationAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(FunctionDeclarationAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_FunctionDeclarationSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->FunctionDeclarationSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(FunctionDeclarationSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateETSTypeReference(KNativePointer context, KNativePointer part) +{ + const auto _context = reinterpret_cast(context); + const auto _part = reinterpret_cast(part); + auto result = GetImpl()->CreateETSTypeReference(_context, _part); + return result; +} +KOALA_INTEROP_2(CreateETSTypeReference, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSTypeReference(KNativePointer context, KNativePointer original, KNativePointer part) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _part = reinterpret_cast(part); + auto result = GetImpl()->UpdateETSTypeReference(_context, _original, _part); + return result; +} +KOALA_INTEROP_3(UpdateETSTypeReference, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTypeReferencePart(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTypeReferencePart(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSTypeReferencePart, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTypeReferencePartConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTypeReferencePartConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSTypeReferencePartConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTypeReferenceBaseNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTypeReferenceBaseNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSTypeReferenceBaseNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeReference(KNativePointer context, KNativePointer typeName, KNativePointer typeParams) +{ + const auto _context = reinterpret_cast(context); + const auto _typeName = reinterpret_cast(typeName); + const auto _typeParams = reinterpret_cast(typeParams); + auto result = GetImpl()->CreateTSTypeReference(_context, _typeName, _typeParams); + return result; +} +KOALA_INTEROP_3(CreateTSTypeReference, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSTypeReference(KNativePointer context, KNativePointer original, KNativePointer typeName, KNativePointer typeParams) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeName = reinterpret_cast(typeName); + const auto _typeParams = reinterpret_cast(typeParams); + auto result = GetImpl()->UpdateTSTypeReference(_context, _original, _typeName, _typeParams); + return result; +} +KOALA_INTEROP_4(UpdateTSTypeReference, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeReferenceTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeReferenceTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeReferenceTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeReferenceTypeNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeReferenceTypeNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeReferenceTypeNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeReferenceBaseNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeReferenceBaseNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeReferenceBaseNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateNamedType(KNativePointer context, KNativePointer name) +{ + const auto _context = reinterpret_cast(context); + const auto _name = reinterpret_cast(name); + auto result = GetImpl()->CreateNamedType(_context, _name); + return result; +} +KOALA_INTEROP_2(CreateNamedType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateNamedType(KNativePointer context, KNativePointer original, KNativePointer name) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = reinterpret_cast(name); + auto result = GetImpl()->UpdateNamedType(_context, _original, _name); + return result; +} +KOALA_INTEROP_3(UpdateNamedType, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_NamedTypeNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->NamedTypeNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(NamedTypeNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_NamedTypeTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->NamedTypeTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(NamedTypeTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_NamedTypeIsNullableConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->NamedTypeIsNullableConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(NamedTypeIsNullableConst, KBoolean, KNativePointer, KNativePointer); + +void impl_NamedTypeSetNullable(KNativePointer context, KNativePointer receiver, KBoolean nullable) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _nullable = static_cast(nullable); + GetImpl()->NamedTypeSetNullable(_context, _receiver, _nullable); + return ; +} +KOALA_INTEROP_V3(NamedTypeSetNullable, KNativePointer, KNativePointer, KBoolean); + +void impl_NamedTypeSetNext(KNativePointer context, KNativePointer receiver, KNativePointer next) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _next = reinterpret_cast(next); + GetImpl()->NamedTypeSetNext(_context, _receiver, _next); + return ; +} +KOALA_INTEROP_V3(NamedTypeSetNext, KNativePointer, KNativePointer, KNativePointer); + +void impl_NamedTypeSetTypeParams(KNativePointer context, KNativePointer receiver, KNativePointer typeParams) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeParams = reinterpret_cast(typeParams); + GetImpl()->NamedTypeSetTypeParams(_context, _receiver, _typeParams); + return ; +} +KOALA_INTEROP_V3(NamedTypeSetTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_NumberLiteralStrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->NumberLiteralStrConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(NumberLiteralStrConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSFunctionType(KNativePointer context, KNativePointer signature) +{ + const auto _context = reinterpret_cast(context); + const auto _signature = reinterpret_cast(signature); + auto result = GetImpl()->CreateTSFunctionType(_context, _signature); + return result; +} +KOALA_INTEROP_2(CreateTSFunctionType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSFunctionType(KNativePointer context, KNativePointer original, KNativePointer signature) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _signature = reinterpret_cast(signature); + auto result = GetImpl()->UpdateTSFunctionType(_context, _original, _signature); + return result; +} +KOALA_INTEROP_3(UpdateTSFunctionType, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSFunctionTypeTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSFunctionTypeTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSFunctionTypeTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSFunctionTypeTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSFunctionTypeTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSFunctionTypeTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSFunctionTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSFunctionTypeParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSFunctionTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSFunctionTypeReturnTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSFunctionTypeReturnTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSFunctionTypeReturnTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSFunctionTypeReturnType(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSFunctionTypeReturnType(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSFunctionTypeReturnType, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSFunctionTypeSetNullable(KNativePointer context, KNativePointer receiver, KBoolean nullable) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _nullable = static_cast(nullable); + GetImpl()->TSFunctionTypeSetNullable(_context, _receiver, _nullable); + return ; +} +KOALA_INTEROP_V3(TSFunctionTypeSetNullable, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_CreateTemplateElement(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTemplateElement(_context); + return result; +} +KOALA_INTEROP_1(CreateTemplateElement, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTemplateElement(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTemplateElement(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTemplateElement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTemplateElement1(KNativePointer context, KStringPtr& raw, KStringPtr& cooked) +{ + const auto _context = reinterpret_cast(context); + const auto _raw = getStringCopy(raw); + const auto _cooked = getStringCopy(cooked); + auto result = GetImpl()->CreateTemplateElement1(_context, _raw, _cooked); + return result; +} +KOALA_INTEROP_3(CreateTemplateElement1, KNativePointer, KNativePointer, KStringPtr, KStringPtr); + +KNativePointer impl_UpdateTemplateElement1(KNativePointer context, KNativePointer original, KStringPtr& raw, KStringPtr& cooked) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _raw = getStringCopy(raw); + const auto _cooked = getStringCopy(cooked); + auto result = GetImpl()->UpdateTemplateElement1(_context, _original, _raw, _cooked); + return result; +} +KOALA_INTEROP_4(UpdateTemplateElement1, KNativePointer, KNativePointer, KNativePointer, KStringPtr, KStringPtr); + +KNativePointer impl_TemplateElementRawConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TemplateElementRawConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(TemplateElementRawConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TemplateElementCookedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TemplateElementCookedConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(TemplateElementCookedConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSInterfaceDeclaration(KNativePointer context, KNativePointerArray _extends, KUInt _extendsSequenceLength, KNativePointer id, KNativePointer typeParams, KNativePointer body, KBoolean isStatic, KBoolean isExternal) +{ + const auto _context = reinterpret_cast(context); + const auto __extends = reinterpret_cast(_extends); + const auto __extendsSequenceLength = static_cast(_extendsSequenceLength); + const auto _id = reinterpret_cast(id); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _body = reinterpret_cast(body); + const auto _isStatic = static_cast(isStatic); + const auto _isExternal = static_cast(isExternal); + auto result = GetImpl()->CreateTSInterfaceDeclaration(_context, __extends, __extendsSequenceLength, _id, _typeParams, _body, _isStatic, _isExternal); + return result; +} +KOALA_INTEROP_8(CreateTSInterfaceDeclaration, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_UpdateTSInterfaceDeclaration(KNativePointer context, KNativePointer original, KNativePointerArray _extends, KUInt _extendsSequenceLength, KNativePointer id, KNativePointer typeParams, KNativePointer body, KBoolean isStatic, KBoolean isExternal) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto __extends = reinterpret_cast(_extends); + const auto __extendsSequenceLength = static_cast(_extendsSequenceLength); + const auto _id = reinterpret_cast(id); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _body = reinterpret_cast(body); + const auto _isStatic = static_cast(isStatic); + const auto _isExternal = static_cast(isExternal); + auto result = GetImpl()->UpdateTSInterfaceDeclaration(_context, _original, __extends, __extendsSequenceLength, _id, _typeParams, _body, _isStatic, _isExternal); + return result; +} +KOALA_INTEROP_9(UpdateTSInterfaceDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_TSInterfaceDeclarationBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationBody(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationId(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationId(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationId, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationIdConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationIdConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationIdConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationInternalNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationInternalNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(TSInterfaceDeclarationInternalNameConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSInterfaceDeclarationSetInternalName(KNativePointer context, KNativePointer receiver, KStringPtr& internalName) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _internalName = getStringCopy(internalName); + GetImpl()->TSInterfaceDeclarationSetInternalName(_context, _receiver, _internalName); + return ; +} +KOALA_INTEROP_V3(TSInterfaceDeclarationSetInternalName, KNativePointer, KNativePointer, KStringPtr); + +KBoolean impl_TSInterfaceDeclarationIsStaticConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationIsStaticConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationIsStaticConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSInterfaceDeclarationIsFromExternalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationIsFromExternalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationIsFromExternalConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationExtends(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSInterfaceDeclarationExtends(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSInterfaceDeclarationExtends, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationExtendsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSInterfaceDeclarationExtendsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSInterfaceDeclarationExtendsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSInterfaceDeclarationDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSInterfaceDeclarationDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationGetAnonClass(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationGetAnonClass(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationGetAnonClass, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationGetAnonClassConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceDeclarationGetAnonClassConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSInterfaceDeclarationGetAnonClassConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSInterfaceDeclarationSetAnonClass(KNativePointer context, KNativePointer receiver, KNativePointer anonClass) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _anonClass = reinterpret_cast(anonClass); + GetImpl()->TSInterfaceDeclarationSetAnonClass(_context, _receiver, _anonClass); + return ; +} +KOALA_INTEROP_V3(TSInterfaceDeclarationSetAnonClass, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSInterfaceDeclarationAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSInterfaceDeclarationAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceDeclarationAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSInterfaceDeclarationAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSInterfaceDeclarationAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSInterfaceDeclarationSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->TSInterfaceDeclarationSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(TSInterfaceDeclarationSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateVariableDeclaration(KNativePointer context, KInt kind, KNativePointerArray declarators, KUInt declaratorsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _kind = static_cast(kind); + const auto _declarators = reinterpret_cast(declarators); + const auto _declaratorsSequenceLength = static_cast(declaratorsSequenceLength); + auto result = GetImpl()->CreateVariableDeclaration(_context, _kind, _declarators, _declaratorsSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateVariableDeclaration, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateVariableDeclaration(KNativePointer context, KNativePointer original, KInt kind, KNativePointerArray declarators, KUInt declaratorsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _kind = static_cast(kind); + const auto _declarators = reinterpret_cast(declarators); + const auto _declaratorsSequenceLength = static_cast(declaratorsSequenceLength); + auto result = GetImpl()->UpdateVariableDeclaration(_context, _original, _kind, _declarators, _declaratorsSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateVariableDeclaration, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt); + +KNativePointer impl_VariableDeclarationDeclaratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->VariableDeclarationDeclaratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(VariableDeclarationDeclaratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_VariableDeclarationKindConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->VariableDeclarationKindConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(VariableDeclarationKindConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_VariableDeclarationDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->VariableDeclarationDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(VariableDeclarationDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_VariableDeclarationGetDeclaratorByNameConst(KNativePointer context, KNativePointer receiver, KStringPtr& name) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _name = getStringCopy(name); + auto result = GetImpl()->VariableDeclarationGetDeclaratorByNameConst(_context, _receiver, _name); + return (void*)result; +} +KOALA_INTEROP_3(VariableDeclarationGetDeclaratorByNameConst, KNativePointer, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_VariableDeclarationAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->VariableDeclarationAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(VariableDeclarationAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_VariableDeclarationAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->VariableDeclarationAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(VariableDeclarationAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_VariableDeclarationSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->VariableDeclarationSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(VariableDeclarationSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateUndefinedLiteral(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateUndefinedLiteral(_context); + return result; +} +KOALA_INTEROP_1(CreateUndefinedLiteral, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateUndefinedLiteral(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateUndefinedLiteral(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateUndefinedLiteral, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateMemberExpression(KNativePointer context, KNativePointer object_arg, KNativePointer property, KInt kind, KBoolean computed, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _object_arg = reinterpret_cast(object_arg); + const auto _property = reinterpret_cast(property); + const auto _kind = static_cast(kind); + const auto _computed = static_cast(computed); + const auto _optional_arg = static_cast(optional_arg); + auto result = GetImpl()->CreateMemberExpression(_context, _object_arg, _property, _kind, _computed, _optional_arg); + return result; +} +KOALA_INTEROP_6(CreateMemberExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KBoolean, KBoolean); + +KNativePointer impl_UpdateMemberExpression(KNativePointer context, KNativePointer original, KNativePointer object_arg, KNativePointer property, KInt kind, KBoolean computed, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _object_arg = reinterpret_cast(object_arg); + const auto _property = reinterpret_cast(property); + const auto _kind = static_cast(kind); + const auto _computed = static_cast(computed); + const auto _optional_arg = static_cast(optional_arg); + auto result = GetImpl()->UpdateMemberExpression(_context, _original, _object_arg, _property, _kind, _computed, _optional_arg); + return result; +} +KOALA_INTEROP_7(UpdateMemberExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KBoolean, KBoolean); + +KNativePointer impl_MemberExpressionObject(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MemberExpressionObject(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MemberExpressionObject, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MemberExpressionObjectConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MemberExpressionObjectConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(MemberExpressionObjectConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_MemberExpressionSetObject(KNativePointer context, KNativePointer receiver, KNativePointer object_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _object_arg = reinterpret_cast(object_arg); + GetImpl()->MemberExpressionSetObject(_context, _receiver, _object_arg); + return ; +} +KOALA_INTEROP_V3(MemberExpressionSetObject, KNativePointer, KNativePointer, KNativePointer); + +void impl_MemberExpressionSetProperty(KNativePointer context, KNativePointer receiver, KNativePointer prop) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _prop = reinterpret_cast(prop); + GetImpl()->MemberExpressionSetProperty(_context, _receiver, _prop); + return ; +} +KOALA_INTEROP_V3(MemberExpressionSetProperty, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MemberExpressionProperty(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MemberExpressionProperty(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MemberExpressionProperty, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MemberExpressionPropertyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MemberExpressionPropertyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(MemberExpressionPropertyConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_MemberExpressionIsComputedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MemberExpressionIsComputedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MemberExpressionIsComputedConst, KBoolean, KNativePointer, KNativePointer); + +KInt impl_MemberExpressionKindConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MemberExpressionKindConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MemberExpressionKindConst, KInt, KNativePointer, KNativePointer); + +void impl_MemberExpressionAddMemberKind(KNativePointer context, KNativePointer receiver, KInt kind) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _kind = static_cast(kind); + GetImpl()->MemberExpressionAddMemberKind(_context, _receiver, _kind); + return ; +} +KOALA_INTEROP_V3(MemberExpressionAddMemberKind, KNativePointer, KNativePointer, KInt); + +KBoolean impl_MemberExpressionHasMemberKindConst(KNativePointer context, KNativePointer receiver, KInt kind) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _kind = static_cast(kind); + auto result = GetImpl()->MemberExpressionHasMemberKindConst(_context, _receiver, _kind); + return result; +} +KOALA_INTEROP_3(MemberExpressionHasMemberKindConst, KBoolean, KNativePointer, KNativePointer, KInt); + +void impl_MemberExpressionRemoveMemberKind(KNativePointer context, KNativePointer receiver, KInt kind) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _kind = static_cast(kind); + GetImpl()->MemberExpressionRemoveMemberKind(_context, _receiver, _kind); + return ; +} +KOALA_INTEROP_V3(MemberExpressionRemoveMemberKind, KNativePointer, KNativePointer, KInt); + +KBoolean impl_MemberExpressionIsIgnoreBoxConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MemberExpressionIsIgnoreBoxConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MemberExpressionIsIgnoreBoxConst, KBoolean, KNativePointer, KNativePointer); + +void impl_MemberExpressionSetIgnoreBox(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->MemberExpressionSetIgnoreBox(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(MemberExpressionSetIgnoreBox, KNativePointer, KNativePointer); + +KBoolean impl_MemberExpressionIsPrivateReferenceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MemberExpressionIsPrivateReferenceConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MemberExpressionIsPrivateReferenceConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSClassImplements(KNativePointer context, KNativePointer expression, KNativePointer typeParameters) +{ + const auto _context = reinterpret_cast(context); + const auto _expression = reinterpret_cast(expression); + const auto _typeParameters = reinterpret_cast(typeParameters); + auto result = GetImpl()->CreateTSClassImplements(_context, _expression, _typeParameters); + return result; +} +KOALA_INTEROP_3(CreateTSClassImplements, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSClassImplements(KNativePointer context, KNativePointer original, KNativePointer expression, KNativePointer typeParameters) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expression = reinterpret_cast(expression); + const auto _typeParameters = reinterpret_cast(typeParameters); + auto result = GetImpl()->UpdateTSClassImplements(_context, _original, _expression, _typeParameters); + return result; +} +KOALA_INTEROP_4(UpdateTSClassImplements, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSClassImplements1(KNativePointer context, KNativePointer expression) +{ + const auto _context = reinterpret_cast(context); + const auto _expression = reinterpret_cast(expression); + auto result = GetImpl()->CreateTSClassImplements1(_context, _expression); + return result; +} +KOALA_INTEROP_2(CreateTSClassImplements1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSClassImplements1(KNativePointer context, KNativePointer original, KNativePointer expression) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expression = reinterpret_cast(expression); + auto result = GetImpl()->UpdateTSClassImplements1(_context, _original, _expression); + return result; +} +KOALA_INTEROP_3(UpdateTSClassImplements1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSClassImplementsExpr(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSClassImplementsExpr(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSClassImplementsExpr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSClassImplementsExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSClassImplementsExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSClassImplementsExprConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSClassImplementsTypeParametersConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSClassImplementsTypeParametersConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSClassImplementsTypeParametersConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSObjectKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSObjectKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSObjectKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSObjectKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSObjectKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSObjectKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSUnionTypeIr(KNativePointer context, KNativePointerArray types, KUInt typesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _types = reinterpret_cast(types); + const auto _typesSequenceLength = static_cast(typesSequenceLength); + auto result = GetImpl()->CreateETSUnionTypeIr(_context, _types, _typesSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateETSUnionTypeIr, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateETSUnionTypeIr(KNativePointer context, KNativePointer original, KNativePointerArray types, KUInt typesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _types = reinterpret_cast(types); + const auto _typesSequenceLength = static_cast(typesSequenceLength); + auto result = GetImpl()->UpdateETSUnionTypeIr(_context, _original, _types, _typesSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateETSUnionTypeIr, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_ETSUnionTypeIrTypesConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSUnionTypeIrTypesConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSUnionTypeIrTypesConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSPropertySignature(KNativePointer context, KNativePointer key, KNativePointer typeAnnotation, KBoolean computed, KBoolean optional_arg, KBoolean readonly_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _key = reinterpret_cast(key); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _computed = static_cast(computed); + const auto _optional_arg = static_cast(optional_arg); + const auto _readonly_arg = static_cast(readonly_arg); + auto result = GetImpl()->CreateTSPropertySignature(_context, _key, _typeAnnotation, _computed, _optional_arg, _readonly_arg); + return result; +} +KOALA_INTEROP_6(CreateTSPropertySignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean, KBoolean, KBoolean); + +KNativePointer impl_UpdateTSPropertySignature(KNativePointer context, KNativePointer original, KNativePointer key, KNativePointer typeAnnotation, KBoolean computed, KBoolean optional_arg, KBoolean readonly_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _key = reinterpret_cast(key); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _computed = static_cast(computed); + const auto _optional_arg = static_cast(optional_arg); + const auto _readonly_arg = static_cast(readonly_arg); + auto result = GetImpl()->UpdateTSPropertySignature(_context, _original, _key, _typeAnnotation, _computed, _optional_arg, _readonly_arg); + return result; +} +KOALA_INTEROP_7(UpdateTSPropertySignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean, KBoolean, KBoolean); + +KNativePointer impl_TSPropertySignatureKeyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSPropertySignatureKeyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSPropertySignatureKeyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSPropertySignatureKey(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSPropertySignatureKey(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSPropertySignatureKey, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSPropertySignatureComputedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSPropertySignatureComputedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSPropertySignatureComputedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSPropertySignatureOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSPropertySignatureOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSPropertySignatureOptionalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSPropertySignatureReadonlyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSPropertySignatureReadonlyConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSPropertySignatureReadonlyConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_TSPropertySignatureTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSPropertySignatureTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSPropertySignatureTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSPropertySignatureSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->TSPropertySignatureSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(TSPropertySignatureSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSConditionalType(KNativePointer context, KNativePointer checkType, KNativePointer extendsType, KNativePointer trueType, KNativePointer falseType) +{ + const auto _context = reinterpret_cast(context); + const auto _checkType = reinterpret_cast(checkType); + const auto _extendsType = reinterpret_cast(extendsType); + const auto _trueType = reinterpret_cast(trueType); + const auto _falseType = reinterpret_cast(falseType); + auto result = GetImpl()->CreateTSConditionalType(_context, _checkType, _extendsType, _trueType, _falseType); + return result; +} +KOALA_INTEROP_5(CreateTSConditionalType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSConditionalType(KNativePointer context, KNativePointer original, KNativePointer checkType, KNativePointer extendsType, KNativePointer trueType, KNativePointer falseType) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _checkType = reinterpret_cast(checkType); + const auto _extendsType = reinterpret_cast(extendsType); + const auto _trueType = reinterpret_cast(trueType); + const auto _falseType = reinterpret_cast(falseType); + auto result = GetImpl()->UpdateTSConditionalType(_context, _original, _checkType, _extendsType, _trueType, _falseType); + return result; +} +KOALA_INTEROP_6(UpdateTSConditionalType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSConditionalTypeCheckTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConditionalTypeCheckTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSConditionalTypeCheckTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSConditionalTypeExtendsTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConditionalTypeExtendsTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSConditionalTypeExtendsTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSConditionalTypeTrueTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConditionalTypeTrueTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSConditionalTypeTrueTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSConditionalTypeFalseTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSConditionalTypeFalseTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSConditionalTypeFalseTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSLiteralType(KNativePointer context, KNativePointer literal) +{ + const auto _context = reinterpret_cast(context); + const auto _literal = reinterpret_cast(literal); + auto result = GetImpl()->CreateTSLiteralType(_context, _literal); + return result; +} +KOALA_INTEROP_2(CreateTSLiteralType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSLiteralType(KNativePointer context, KNativePointer original, KNativePointer literal) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _literal = reinterpret_cast(literal); + auto result = GetImpl()->UpdateTSLiteralType(_context, _original, _literal); + return result; +} +KOALA_INTEROP_3(UpdateTSLiteralType, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSLiteralTypeLiteralConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSLiteralTypeLiteralConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSLiteralTypeLiteralConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeAliasDeclaration(KNativePointer context, KNativePointer id, KNativePointer typeParams, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _id = reinterpret_cast(id); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + auto result = GetImpl()->CreateTSTypeAliasDeclaration(_context, _id, _typeParams, _typeAnnotation); + return result; +} +KOALA_INTEROP_4(CreateTSTypeAliasDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSTypeAliasDeclaration(KNativePointer context, KNativePointer original, KNativePointer id, KNativePointer typeParams, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _id = reinterpret_cast(id); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + auto result = GetImpl()->UpdateTSTypeAliasDeclaration(_context, _original, _id, _typeParams, _typeAnnotation); + return result; +} +KOALA_INTEROP_5(UpdateTSTypeAliasDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeAliasDeclaration1(KNativePointer context, KNativePointer id) +{ + const auto _context = reinterpret_cast(context); + const auto _id = reinterpret_cast(id); + auto result = GetImpl()->CreateTSTypeAliasDeclaration1(_context, _id); + return result; +} +KOALA_INTEROP_2(CreateTSTypeAliasDeclaration1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSTypeAliasDeclaration1(KNativePointer context, KNativePointer original, KNativePointer id) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _id = reinterpret_cast(id); + auto result = GetImpl()->UpdateTSTypeAliasDeclaration1(_context, _original, _id); + return result; +} +KOALA_INTEROP_3(UpdateTSTypeAliasDeclaration1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeAliasDeclarationId(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeAliasDeclarationId(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSTypeAliasDeclarationId, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeAliasDeclarationIdConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeAliasDeclarationIdConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeAliasDeclarationIdConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeAliasDeclarationTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeAliasDeclarationTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeAliasDeclarationTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeAliasDeclarationDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTypeAliasDeclarationDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTypeAliasDeclarationDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSTypeAliasDeclarationSetTypeParameters(KNativePointer context, KNativePointer receiver, KNativePointer typeParams) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeParams = reinterpret_cast(typeParams); + GetImpl()->TSTypeAliasDeclarationSetTypeParameters(_context, _receiver, _typeParams); + return ; +} +KOALA_INTEROP_V3(TSTypeAliasDeclarationSetTypeParameters, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeAliasDeclarationAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTypeAliasDeclarationAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTypeAliasDeclarationAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeAliasDeclarationAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTypeAliasDeclarationAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTypeAliasDeclarationAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSTypeAliasDeclarationSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->TSTypeAliasDeclarationSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(TSTypeAliasDeclarationSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TSTypeAliasDeclarationTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeAliasDeclarationTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeAliasDeclarationTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSTypeAliasDeclarationSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->TSTypeAliasDeclarationSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(TSTypeAliasDeclarationSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateDebuggerStatement(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateDebuggerStatement(_context); + return result; +} +KOALA_INTEROP_1(CreateDebuggerStatement, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateDebuggerStatement(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateDebuggerStatement(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateDebuggerStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateReturnStatement(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateReturnStatement(_context); + return result; +} +KOALA_INTEROP_1(CreateReturnStatement, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateReturnStatement(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateReturnStatement(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateReturnStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateReturnStatement1(KNativePointer context, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->CreateReturnStatement1(_context, _argument); + return result; +} +KOALA_INTEROP_2(CreateReturnStatement1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateReturnStatement1(KNativePointer context, KNativePointer original, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->UpdateReturnStatement1(_context, _original, _argument); + return result; +} +KOALA_INTEROP_3(UpdateReturnStatement1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ReturnStatementArgument(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ReturnStatementArgument(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ReturnStatementArgument, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ReturnStatementArgumentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ReturnStatementArgumentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ReturnStatementArgumentConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ReturnStatementSetArgument(KNativePointer context, KNativePointer receiver, KNativePointer arg) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _arg = reinterpret_cast(arg); + GetImpl()->ReturnStatementSetArgument(_context, _receiver, _arg); + return ; +} +KOALA_INTEROP_V3(ReturnStatementSetArgument, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateExportDefaultDeclaration(KNativePointer context, KNativePointer decl, KBoolean exportEquals) +{ + const auto _context = reinterpret_cast(context); + const auto _decl = reinterpret_cast(decl); + const auto _exportEquals = static_cast(exportEquals); + auto result = GetImpl()->CreateExportDefaultDeclaration(_context, _decl, _exportEquals); + return result; +} +KOALA_INTEROP_3(CreateExportDefaultDeclaration, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateExportDefaultDeclaration(KNativePointer context, KNativePointer original, KNativePointer decl, KBoolean exportEquals) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _decl = reinterpret_cast(decl); + const auto _exportEquals = static_cast(exportEquals); + auto result = GetImpl()->UpdateExportDefaultDeclaration(_context, _original, _decl, _exportEquals); + return result; +} +KOALA_INTEROP_4(UpdateExportDefaultDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_ExportDefaultDeclarationDecl(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportDefaultDeclarationDecl(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExportDefaultDeclarationDecl, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExportDefaultDeclarationDeclConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportDefaultDeclarationDeclConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExportDefaultDeclarationDeclConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ExportDefaultDeclarationIsExportEqualsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportDefaultDeclarationIsExportEqualsConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExportDefaultDeclarationIsExportEqualsConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateScriptFunction(KNativePointer context, KNativePointer databody, KNativePointer datasignature, KInt datafuncFlags, KInt dataflags) +{ + const auto _context = reinterpret_cast(context); + const auto _databody = reinterpret_cast(databody); + const auto _datasignature = reinterpret_cast(datasignature); + const auto _datafuncFlags = static_cast(datafuncFlags); + const auto _dataflags = static_cast(dataflags); + auto result = GetImpl()->CreateScriptFunction(_context, _databody, _datasignature, _datafuncFlags, _dataflags); + return result; +} +KOALA_INTEROP_5(CreateScriptFunction, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KInt); + +KNativePointer impl_UpdateScriptFunction(KNativePointer context, KNativePointer original, KNativePointer databody, KNativePointer datasignature, KInt datafuncFlags, KInt dataflags) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _databody = reinterpret_cast(databody); + const auto _datasignature = reinterpret_cast(datasignature); + const auto _datafuncFlags = static_cast(datafuncFlags); + const auto _dataflags = static_cast(dataflags); + auto result = GetImpl()->UpdateScriptFunction(_context, _original, _databody, _datasignature, _datafuncFlags, _dataflags); + return result; +} +KOALA_INTEROP_6(UpdateScriptFunction, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KInt); + +KNativePointer impl_ScriptFunctionIdConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIdConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ScriptFunctionIdConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionId(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionId(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionId, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ScriptFunctionParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ScriptFunctionParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ScriptFunctionParams(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ScriptFunctionParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionReturnStatementsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ScriptFunctionReturnStatementsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ScriptFunctionReturnStatementsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionReturnStatements(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ScriptFunctionReturnStatements(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ScriptFunctionReturnStatements, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ScriptFunctionTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ScriptFunctionBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionBody(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionBody, KNativePointer, KNativePointer, KNativePointer); + +void impl_ScriptFunctionAddReturnStatement(KNativePointer context, KNativePointer receiver, KNativePointer returnStatement) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _returnStatement = reinterpret_cast(returnStatement); + GetImpl()->ScriptFunctionAddReturnStatement(_context, _receiver, _returnStatement); + return ; +} +KOALA_INTEROP_V3(ScriptFunctionAddReturnStatement, KNativePointer, KNativePointer, KNativePointer); + +void impl_ScriptFunctionSetBody(KNativePointer context, KNativePointer receiver, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _body = reinterpret_cast(body); + GetImpl()->ScriptFunctionSetBody(_context, _receiver, _body); + return ; +} +KOALA_INTEROP_V3(ScriptFunctionSetBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionReturnTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionReturnTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ScriptFunctionReturnTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionReturnTypeAnnotation(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionReturnTypeAnnotation(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionReturnTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +void impl_ScriptFunctionSetReturnTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer node) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _node = reinterpret_cast(node); + GetImpl()->ScriptFunctionSetReturnTypeAnnotation(_context, _receiver, _node); + return ; +} +KOALA_INTEROP_V3(ScriptFunctionSetReturnTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsEntryPointConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsEntryPointConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsEntryPointConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsGeneratorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsGeneratorConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsGeneratorConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsAsyncFuncConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsAsyncFuncConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsAsyncFuncConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsAsyncImplFuncConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsAsyncImplFuncConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsAsyncImplFuncConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsArrowConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsArrowConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsArrowConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsOverloadConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsOverloadConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsOverloadConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsExternalOverloadConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsExternalOverloadConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsExternalOverloadConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsConstructorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsConstructorConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsConstructorConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsGetterConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsGetterConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsGetterConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsSetterConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsSetterConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsSetterConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsExtensionAccessorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsExtensionAccessorConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsExtensionAccessorConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsMethodConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsMethodConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsMethodConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsProxyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsProxyConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsProxyConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsStaticBlockConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsStaticBlockConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsStaticBlockConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsEnumConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsEnumConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsEnumConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsHiddenConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsHiddenConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsHiddenConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsExternalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsExternalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsExternalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsImplicitSuperCallNeededConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsImplicitSuperCallNeededConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsImplicitSuperCallNeededConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionHasBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionHasBodyConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionHasBodyConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionHasRestParameterConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionHasRestParameterConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionHasRestParameterConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionHasReturnStatementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionHasReturnStatementConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionHasReturnStatementConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionHasThrowStatementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionHasThrowStatementConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionHasThrowStatementConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsThrowingConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsThrowingConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsThrowingConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsRethrowingConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsRethrowingConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsRethrowingConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsDynamicConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsDynamicConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsDynamicConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionIsExtensionMethodConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionIsExtensionMethodConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionIsExtensionMethodConst, KBoolean, KNativePointer, KNativePointer); + +KInt impl_ScriptFunctionFlagsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionFlagsConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionFlagsConst, KInt, KNativePointer, KNativePointer); + +KBoolean impl_ScriptFunctionHasReceiverConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionHasReceiverConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionHasReceiverConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ScriptFunctionSetIdent(KNativePointer context, KNativePointer receiver, KNativePointer id) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _id = reinterpret_cast(id); + GetImpl()->ScriptFunctionSetIdent(_context, _receiver, _id); + return ; +} +KOALA_INTEROP_V3(ScriptFunctionSetIdent, KNativePointer, KNativePointer, KNativePointer); + +void impl_ScriptFunctionAddFlag(KNativePointer context, KNativePointer receiver, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _flags = static_cast(flags); + GetImpl()->ScriptFunctionAddFlag(_context, _receiver, _flags); + return ; +} +KOALA_INTEROP_V3(ScriptFunctionAddFlag, KNativePointer, KNativePointer, KInt); + +void impl_ScriptFunctionAddModifier(KNativePointer context, KNativePointer receiver, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _flags = static_cast(flags); + GetImpl()->ScriptFunctionAddModifier(_context, _receiver, _flags); + return ; +} +KOALA_INTEROP_V3(ScriptFunctionAddModifier, KNativePointer, KNativePointer, KInt); + +KUInt impl_ScriptFunctionFormalParamsLengthConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ScriptFunctionFormalParamsLengthConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ScriptFunctionFormalParamsLengthConst, KUInt, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ScriptFunctionAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ScriptFunctionAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ScriptFunctionAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ScriptFunctionAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ScriptFunctionAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ScriptFunctionSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->ScriptFunctionSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(ScriptFunctionSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateClassDefinition(KNativePointer context, KNativePointer ident, KNativePointer typeParams, KNativePointer superTypeParams, KNativePointerArray _implements, KUInt _implementsSequenceLength, KNativePointer ctor, KNativePointer superClass, KNativePointerArray body, KUInt bodySequenceLength, KInt modifiers, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _ident = reinterpret_cast(ident); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _superTypeParams = reinterpret_cast(superTypeParams); + const auto __implements = reinterpret_cast(_implements); + const auto __implementsSequenceLength = static_cast(_implementsSequenceLength); + const auto _ctor = reinterpret_cast(ctor); + const auto _superClass = reinterpret_cast(superClass); + const auto _body = reinterpret_cast(body); + const auto _bodySequenceLength = static_cast(bodySequenceLength); + const auto _modifiers = static_cast(modifiers); + const auto _flags = static_cast(flags); + auto result = GetImpl()->CreateClassDefinition(_context, _ident, _typeParams, _superTypeParams, __implements, __implementsSequenceLength, _ctor, _superClass, _body, _bodySequenceLength, _modifiers, _flags); + return result; +} +KOALA_INTEROP_12(CreateClassDefinition, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt, KInt); + +KNativePointer impl_UpdateClassDefinition(KNativePointer context, KNativePointer original, KNativePointer ident, KNativePointer typeParams, KNativePointer superTypeParams, KNativePointerArray _implements, KUInt _implementsSequenceLength, KNativePointer ctor, KNativePointer superClass, KNativePointerArray body, KUInt bodySequenceLength, KInt modifiers, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _ident = reinterpret_cast(ident); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _superTypeParams = reinterpret_cast(superTypeParams); + const auto __implements = reinterpret_cast(_implements); + const auto __implementsSequenceLength = static_cast(_implementsSequenceLength); + const auto _ctor = reinterpret_cast(ctor); + const auto _superClass = reinterpret_cast(superClass); + const auto _body = reinterpret_cast(body); + const auto _bodySequenceLength = static_cast(bodySequenceLength); + const auto _modifiers = static_cast(modifiers); + const auto _flags = static_cast(flags); + auto result = GetImpl()->UpdateClassDefinition(_context, _original, _ident, _typeParams, _superTypeParams, __implements, __implementsSequenceLength, _ctor, _superClass, _body, _bodySequenceLength, _modifiers, _flags); + return result; +} +KOALA_INTEROP_13(UpdateClassDefinition, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt, KInt); + +KNativePointer impl_CreateClassDefinition1(KNativePointer context, KNativePointer ident, KNativePointerArray body, KUInt bodySequenceLength, KInt modifiers, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _ident = reinterpret_cast(ident); + const auto _body = reinterpret_cast(body); + const auto _bodySequenceLength = static_cast(bodySequenceLength); + const auto _modifiers = static_cast(modifiers); + const auto _flags = static_cast(flags); + auto result = GetImpl()->CreateClassDefinition1(_context, _ident, _body, _bodySequenceLength, _modifiers, _flags); + return result; +} +KOALA_INTEROP_6(CreateClassDefinition1, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt, KInt); + +KNativePointer impl_UpdateClassDefinition1(KNativePointer context, KNativePointer original, KNativePointer ident, KNativePointerArray body, KUInt bodySequenceLength, KInt modifiers, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _ident = reinterpret_cast(ident); + const auto _body = reinterpret_cast(body); + const auto _bodySequenceLength = static_cast(bodySequenceLength); + const auto _modifiers = static_cast(modifiers); + const auto _flags = static_cast(flags); + auto result = GetImpl()->UpdateClassDefinition1(_context, _original, _ident, _body, _bodySequenceLength, _modifiers, _flags); + return result; +} +KOALA_INTEROP_7(UpdateClassDefinition1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt, KInt); + +KNativePointer impl_CreateClassDefinition2(KNativePointer context, KNativePointer ident, KInt modifiers, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _ident = reinterpret_cast(ident); + const auto _modifiers = static_cast(modifiers); + const auto _flags = static_cast(flags); + auto result = GetImpl()->CreateClassDefinition2(_context, _ident, _modifiers, _flags); + return result; +} +KOALA_INTEROP_4(CreateClassDefinition2, KNativePointer, KNativePointer, KNativePointer, KInt, KInt); + +KNativePointer impl_UpdateClassDefinition2(KNativePointer context, KNativePointer original, KNativePointer ident, KInt modifiers, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _ident = reinterpret_cast(ident); + const auto _modifiers = static_cast(modifiers); + const auto _flags = static_cast(flags); + auto result = GetImpl()->UpdateClassDefinition2(_context, _original, _ident, _modifiers, _flags); + return result; +} +KOALA_INTEROP_5(UpdateClassDefinition2, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KInt); + +KNativePointer impl_ClassDefinitionIdentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIdentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassDefinitionIdentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionIdent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIdent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIdent, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetIdent(KNativePointer context, KNativePointer receiver, KNativePointer ident) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _ident = reinterpret_cast(ident); + GetImpl()->ClassDefinitionSetIdent(_context, _receiver, _ident); + return ; +} +KOALA_INTEROP_V3(ClassDefinitionSetIdent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionInternalNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionInternalNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ClassDefinitionInternalNameConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetInternalName(KNativePointer context, KNativePointer receiver, KStringPtr& internalName) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _internalName = getStringCopy(internalName); + GetImpl()->ClassDefinitionSetInternalName(_context, _receiver, _internalName); + return ; +} +KOALA_INTEROP_V3(ClassDefinitionSetInternalName, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_ClassDefinitionSuper(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionSuper(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionSuper, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionSuperConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionSuperConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassDefinitionSuperConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetSuper(KNativePointer context, KNativePointer receiver, KNativePointer superClass) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _superClass = reinterpret_cast(superClass); + GetImpl()->ClassDefinitionSetSuper(_context, _receiver, _superClass); + return ; +} +KOALA_INTEROP_V3(ClassDefinitionSetSuper, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsGlobalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsGlobalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsGlobalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsLocalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsLocalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsLocalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsExternConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsExternConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsExternConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsFromExternalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsFromExternalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsFromExternalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsInnerConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsInnerConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsInnerConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsGlobalInitializedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsGlobalInitializedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsGlobalInitializedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsClassDefinitionCheckedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsClassDefinitionCheckedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsClassDefinitionCheckedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsAnonymousConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsAnonymousConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsAnonymousConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsNamespaceTransformedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsNamespaceTransformedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsNamespaceTransformedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionIsModuleConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionIsModuleConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionIsModuleConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetGlobalInitialized(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ClassDefinitionSetGlobalInitialized(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ClassDefinitionSetGlobalInitialized, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetInnerModifier(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ClassDefinitionSetInnerModifier(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ClassDefinitionSetInnerModifier, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetClassDefinitionChecked(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ClassDefinitionSetClassDefinitionChecked(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ClassDefinitionSetClassDefinitionChecked, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetAnonymousModifier(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ClassDefinitionSetAnonymousModifier(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ClassDefinitionSetAnonymousModifier, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetNamespaceTransformed(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ClassDefinitionSetNamespaceTransformed(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ClassDefinitionSetNamespaceTransformed, KNativePointer, KNativePointer); + +KInt impl_ClassDefinitionModifiersConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionModifiersConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionModifiersConst, KInt, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetModifiers(KNativePointer context, KNativePointer receiver, KInt modifiers) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _modifiers = static_cast(modifiers); + GetImpl()->ClassDefinitionSetModifiers(_context, _receiver, _modifiers); + return ; +} +KOALA_INTEROP_V3(ClassDefinitionSetModifiers, KNativePointer, KNativePointer, KInt); + +void impl_ClassDefinitionAddProperties(KNativePointer context, KNativePointer receiver, KNativePointerArray body, KUInt bodySequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _body = reinterpret_cast(body); + const auto _bodySequenceLength = static_cast(bodySequenceLength); + GetImpl()->ClassDefinitionAddProperties(_context, _receiver, _body, _bodySequenceLength); + return ; +} +KOALA_INTEROP_V4(ClassDefinitionAddProperties, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_ClassDefinitionBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassDefinitionBody(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassDefinitionBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassDefinitionBodyConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassDefinitionBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionCtor(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionCtor(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionCtor, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetCtor(KNativePointer context, KNativePointer receiver, KNativePointer ctor) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _ctor = reinterpret_cast(ctor); + GetImpl()->ClassDefinitionSetCtor(_context, _receiver, _ctor); + return ; +} +KOALA_INTEROP_V3(ClassDefinitionSetCtor, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionImplements(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassDefinitionImplements(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassDefinitionImplements, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionImplementsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassDefinitionImplementsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassDefinitionImplementsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassDefinitionTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionTypeParams, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetTypeParams(KNativePointer context, KNativePointer receiver, KNativePointer typeParams) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeParams = reinterpret_cast(typeParams); + GetImpl()->ClassDefinitionSetTypeParams(_context, _receiver, _typeParams); + return ; +} +KOALA_INTEROP_V3(ClassDefinitionSetTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionSuperTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionSuperTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassDefinitionSuperTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionSuperTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionSuperTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionSuperTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_ClassDefinitionLocalTypeCounter(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionLocalTypeCounter(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionLocalTypeCounter, KInt, KNativePointer, KNativePointer); + +KInt impl_ClassDefinitionLocalIndexConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionLocalIndexConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionLocalIndexConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionLocalPrefixConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionLocalPrefixConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ClassDefinitionLocalPrefixConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetOrigEnumDecl(KNativePointer context, KNativePointer receiver, KNativePointer enumDecl) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _enumDecl = reinterpret_cast(enumDecl); + GetImpl()->ClassDefinitionSetOrigEnumDecl(_context, _receiver, _enumDecl); + return ; +} +KOALA_INTEROP_V3(ClassDefinitionSetOrigEnumDecl, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionOrigEnumDeclConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionOrigEnumDeclConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassDefinitionOrigEnumDeclConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionGetAnonClass(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionGetAnonClass(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionGetAnonClass, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetAnonClass(KNativePointer context, KNativePointer receiver, KNativePointer anonClass) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _anonClass = reinterpret_cast(anonClass); + GetImpl()->ClassDefinitionSetAnonClass(_context, _receiver, _anonClass); + return ; +} +KOALA_INTEROP_V3(ClassDefinitionSetAnonClass, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionCtorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionCtorConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassDefinitionCtorConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionHasPrivateMethodConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionHasPrivateMethodConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionHasPrivateMethodConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionHasComputedInstanceFieldConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDefinitionHasComputedInstanceFieldConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDefinitionHasComputedInstanceFieldConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ClassDefinitionHasMatchingPrivateKeyConst(KNativePointer context, KNativePointer receiver, KStringPtr& name) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _name = getStringCopy(name); + auto result = GetImpl()->ClassDefinitionHasMatchingPrivateKeyConst(_context, _receiver, _name); + return result; +} +KOALA_INTEROP_3(ClassDefinitionHasMatchingPrivateKeyConst, KBoolean, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_ClassDefinitionAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassDefinitionAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassDefinitionAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDefinitionAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassDefinitionAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassDefinitionAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ClassDefinitionSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->ClassDefinitionSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(ClassDefinitionSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateArrayExpression(KNativePointer context, KNativePointerArray elements, KUInt elementsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _elements = reinterpret_cast(elements); + const auto _elementsSequenceLength = static_cast(elementsSequenceLength); + auto result = GetImpl()->CreateArrayExpression(_context, _elements, _elementsSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateArrayExpression, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateArrayExpression(KNativePointer context, KNativePointer original, KNativePointerArray elements, KUInt elementsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _elements = reinterpret_cast(elements); + const auto _elementsSequenceLength = static_cast(elementsSequenceLength); + auto result = GetImpl()->UpdateArrayExpression(_context, _original, _elements, _elementsSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateArrayExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateArrayExpression1(KNativePointer context, KInt nodeType, KNativePointerArray elements, KUInt elementsSequenceLength, KBoolean trailingComma) +{ + const auto _context = reinterpret_cast(context); + const auto _nodeType = static_cast(nodeType); + const auto _elements = reinterpret_cast(elements); + const auto _elementsSequenceLength = static_cast(elementsSequenceLength); + const auto _trailingComma = static_cast(trailingComma); + auto result = GetImpl()->CreateArrayExpression1(_context, _nodeType, _elements, _elementsSequenceLength, _trailingComma); + return result; +} +KOALA_INTEROP_5(CreateArrayExpression1, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt, KBoolean); + +KNativePointer impl_UpdateArrayExpression1(KNativePointer context, KNativePointer original, KInt nodeType, KNativePointerArray elements, KUInt elementsSequenceLength, KBoolean trailingComma) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _nodeType = static_cast(nodeType); + const auto _elements = reinterpret_cast(elements); + const auto _elementsSequenceLength = static_cast(elementsSequenceLength); + const auto _trailingComma = static_cast(trailingComma); + auto result = GetImpl()->UpdateArrayExpression1(_context, _original, _nodeType, _elements, _elementsSequenceLength, _trailingComma); + return result; +} +KOALA_INTEROP_6(UpdateArrayExpression1, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointerArray, KUInt, KBoolean); + +KNativePointer impl_ArrayExpressionElementsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ArrayExpressionElementsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ArrayExpressionElementsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ArrayExpressionElements(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ArrayExpressionElements(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ArrayExpressionElements, KNativePointer, KNativePointer, KNativePointer); + +void impl_ArrayExpressionSetElements(KNativePointer context, KNativePointer receiver, KNativePointerArray elements, KUInt elementsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _elements = reinterpret_cast(elements); + const auto _elementsSequenceLength = static_cast(elementsSequenceLength); + GetImpl()->ArrayExpressionSetElements(_context, _receiver, _elements, _elementsSequenceLength); + return ; +} +KOALA_INTEROP_V4(ArrayExpressionSetElements, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KBoolean impl_ArrayExpressionIsDeclarationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ArrayExpressionIsDeclarationConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ArrayExpressionIsDeclarationConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ArrayExpressionIsOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ArrayExpressionIsOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ArrayExpressionIsOptionalConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ArrayExpressionSetDeclaration(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ArrayExpressionSetDeclaration(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ArrayExpressionSetDeclaration, KNativePointer, KNativePointer); + +void impl_ArrayExpressionSetOptional(KNativePointer context, KNativePointer receiver, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _optional_arg = static_cast(optional_arg); + GetImpl()->ArrayExpressionSetOptional(_context, _receiver, _optional_arg); + return ; +} +KOALA_INTEROP_V3(ArrayExpressionSetOptional, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_ArrayExpressionDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ArrayExpressionDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ArrayExpressionDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ArrayExpressionConvertibleToArrayPattern(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ArrayExpressionConvertibleToArrayPattern(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ArrayExpressionConvertibleToArrayPattern, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_ArrayExpressionValidateExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ArrayExpressionValidateExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ArrayExpressionValidateExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ArrayExpressionTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ArrayExpressionTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ArrayExpressionTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ArrayExpressionSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->ArrayExpressionSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(ArrayExpressionSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSInterfaceBody(KNativePointer context, KNativePointerArray body, KUInt bodySequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _body = reinterpret_cast(body); + const auto _bodySequenceLength = static_cast(bodySequenceLength); + auto result = GetImpl()->CreateTSInterfaceBody(_context, _body, _bodySequenceLength); + return result; +} +KOALA_INTEROP_3(CreateTSInterfaceBody, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateTSInterfaceBody(KNativePointer context, KNativePointer original, KNativePointerArray body, KUInt bodySequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _body = reinterpret_cast(body); + const auto _bodySequenceLength = static_cast(bodySequenceLength); + auto result = GetImpl()->UpdateTSInterfaceBody(_context, _original, _body, _bodySequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateTSInterfaceBody, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TSInterfaceBodyBodyPtr(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSInterfaceBodyBodyPtr(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSInterfaceBodyBodyPtr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceBodyBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSInterfaceBodyBody(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSInterfaceBodyBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceBodyBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSInterfaceBodyBodyConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSInterfaceBodyBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeQuery(KNativePointer context, KNativePointer exprName) +{ + const auto _context = reinterpret_cast(context); + const auto _exprName = reinterpret_cast(exprName); + auto result = GetImpl()->CreateTSTypeQuery(_context, _exprName); + return result; +} +KOALA_INTEROP_2(CreateTSTypeQuery, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSTypeQuery(KNativePointer context, KNativePointer original, KNativePointer exprName) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _exprName = reinterpret_cast(exprName); + auto result = GetImpl()->UpdateTSTypeQuery(_context, _original, _exprName); + return result; +} +KOALA_INTEROP_3(UpdateTSTypeQuery, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeQueryExprNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeQueryExprNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeQueryExprNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSBigintKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSBigintKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSBigintKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSBigintKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSBigintKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSBigintKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateProperty(KNativePointer context, KNativePointer key, KNativePointer value) +{ + const auto _context = reinterpret_cast(context); + const auto _key = reinterpret_cast(key); + const auto _value = reinterpret_cast(value); + auto result = GetImpl()->CreateProperty(_context, _key, _value); + return result; +} +KOALA_INTEROP_3(CreateProperty, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateProperty(KNativePointer context, KNativePointer original, KNativePointer key, KNativePointer value) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _key = reinterpret_cast(key); + const auto _value = reinterpret_cast(value); + auto result = GetImpl()->UpdateProperty(_context, _original, _key, _value); + return result; +} +KOALA_INTEROP_4(UpdateProperty, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateProperty1(KNativePointer context, KInt kind, KNativePointer key, KNativePointer value, KBoolean isMethod, KBoolean isComputed) +{ + const auto _context = reinterpret_cast(context); + const auto _kind = static_cast(kind); + const auto _key = reinterpret_cast(key); + const auto _value = reinterpret_cast(value); + const auto _isMethod = static_cast(isMethod); + const auto _isComputed = static_cast(isComputed); + auto result = GetImpl()->CreateProperty1(_context, _kind, _key, _value, _isMethod, _isComputed); + return result; +} +KOALA_INTEROP_6(CreateProperty1, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_UpdateProperty1(KNativePointer context, KNativePointer original, KInt kind, KNativePointer key, KNativePointer value, KBoolean isMethod, KBoolean isComputed) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _kind = static_cast(kind); + const auto _key = reinterpret_cast(key); + const auto _value = reinterpret_cast(value); + const auto _isMethod = static_cast(isMethod); + const auto _isComputed = static_cast(isComputed); + auto result = GetImpl()->UpdateProperty1(_context, _original, _kind, _key, _value, _isMethod, _isComputed); + return result; +} +KOALA_INTEROP_7(UpdateProperty1, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_PropertyKey(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyKey(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyKey, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_PropertyKeyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyKeyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(PropertyKeyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_PropertyValueConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyValueConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(PropertyValueConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_PropertyValue(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyValue(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyValue, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_PropertyKindConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyKindConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyKindConst, KInt, KNativePointer, KNativePointer); + +KBoolean impl_PropertyIsMethodConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyIsMethodConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyIsMethodConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_PropertyIsShorthandConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyIsShorthandConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyIsShorthandConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_PropertyIsComputedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyIsComputedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyIsComputedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_PropertyIsAccessorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyIsAccessorConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyIsAccessorConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_PropertyIsAccessorKind(KNativePointer context, KNativePointer receiver, KInt kind) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _kind = static_cast(kind); + auto result = GetImpl()->PropertyIsAccessorKind(_context, _receiver, _kind); + return result; +} +KOALA_INTEROP_3(PropertyIsAccessorKind, KBoolean, KNativePointer, KNativePointer, KInt); + +KBoolean impl_PropertyConvertibleToPatternProperty(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyConvertibleToPatternProperty(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyConvertibleToPatternProperty, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_PropertyValidateExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PropertyValidateExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(PropertyValidateExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateVariableDeclarator(KNativePointer context, KInt flag, KNativePointer ident) +{ + const auto _context = reinterpret_cast(context); + const auto _flag = static_cast(flag); + const auto _ident = reinterpret_cast(ident); + auto result = GetImpl()->CreateVariableDeclarator(_context, _flag, _ident); + return result; +} +KOALA_INTEROP_3(CreateVariableDeclarator, KNativePointer, KNativePointer, KInt, KNativePointer); + +KNativePointer impl_UpdateVariableDeclarator(KNativePointer context, KNativePointer original, KInt flag, KNativePointer ident) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _flag = static_cast(flag); + const auto _ident = reinterpret_cast(ident); + auto result = GetImpl()->UpdateVariableDeclarator(_context, _original, _flag, _ident); + return result; +} +KOALA_INTEROP_4(UpdateVariableDeclarator, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointer); + +KNativePointer impl_CreateVariableDeclarator1(KNativePointer context, KInt flag, KNativePointer ident, KNativePointer init) +{ + const auto _context = reinterpret_cast(context); + const auto _flag = static_cast(flag); + const auto _ident = reinterpret_cast(ident); + const auto _init = reinterpret_cast(init); + auto result = GetImpl()->CreateVariableDeclarator1(_context, _flag, _ident, _init); + return result; +} +KOALA_INTEROP_4(CreateVariableDeclarator1, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateVariableDeclarator1(KNativePointer context, KNativePointer original, KInt flag, KNativePointer ident, KNativePointer init) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _flag = static_cast(flag); + const auto _ident = reinterpret_cast(ident); + const auto _init = reinterpret_cast(init); + auto result = GetImpl()->UpdateVariableDeclarator1(_context, _original, _flag, _ident, _init); + return result; +} +KOALA_INTEROP_5(UpdateVariableDeclarator1, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_VariableDeclaratorInit(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->VariableDeclaratorInit(_context, _receiver); + return result; +} +KOALA_INTEROP_2(VariableDeclaratorInit, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_VariableDeclaratorInitConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->VariableDeclaratorInitConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(VariableDeclaratorInitConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_VariableDeclaratorSetInit(KNativePointer context, KNativePointer receiver, KNativePointer init) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _init = reinterpret_cast(init); + GetImpl()->VariableDeclaratorSetInit(_context, _receiver, _init); + return ; +} +KOALA_INTEROP_V3(VariableDeclaratorSetInit, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_VariableDeclaratorId(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->VariableDeclaratorId(_context, _receiver); + return result; +} +KOALA_INTEROP_2(VariableDeclaratorId, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_VariableDeclaratorIdConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->VariableDeclaratorIdConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(VariableDeclaratorIdConst, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_VariableDeclaratorFlag(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->VariableDeclaratorFlag(_context, _receiver); + return result; +} +KOALA_INTEROP_2(VariableDeclaratorFlag, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_CreateStringLiteral(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateStringLiteral(_context); + return result; +} +KOALA_INTEROP_1(CreateStringLiteral, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateStringLiteral(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateStringLiteral(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateStringLiteral, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateStringLiteral1(KNativePointer context, KStringPtr& str) +{ + const auto _context = reinterpret_cast(context); + const auto _str = getStringCopy(str); + auto result = GetImpl()->CreateStringLiteral1(_context, _str); + return result; +} +KOALA_INTEROP_2(CreateStringLiteral1, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_UpdateStringLiteral1(KNativePointer context, KNativePointer original, KStringPtr& str) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _str = getStringCopy(str); + auto result = GetImpl()->UpdateStringLiteral1(_context, _original, _str); + return result; +} +KOALA_INTEROP_3(UpdateStringLiteral1, KNativePointer, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_StringLiteralStrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->StringLiteralStrConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(StringLiteralStrConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeAssertion(KNativePointer context, KNativePointer typeAnnotation, KNativePointer expression) +{ + const auto _context = reinterpret_cast(context); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _expression = reinterpret_cast(expression); + auto result = GetImpl()->CreateTSTypeAssertion(_context, _typeAnnotation, _expression); + return result; +} +KOALA_INTEROP_3(CreateTSTypeAssertion, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSTypeAssertion(KNativePointer context, KNativePointer original, KNativePointer typeAnnotation, KNativePointer expression) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _expression = reinterpret_cast(expression); + auto result = GetImpl()->UpdateTSTypeAssertion(_context, _original, _typeAnnotation, _expression); + return result; +} +KOALA_INTEROP_4(UpdateTSTypeAssertion, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeAssertionGetExpressionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeAssertionGetExpressionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeAssertionGetExpressionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeAssertionTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeAssertionTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeAssertionTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSTypeAssertionSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->TSTypeAssertionSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(TSTypeAssertionSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSExternalModuleReference(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateTSExternalModuleReference(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateTSExternalModuleReference, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSExternalModuleReference(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateTSExternalModuleReference(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateTSExternalModuleReference, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSExternalModuleReferenceExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSExternalModuleReferenceExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSExternalModuleReferenceExprConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSUndefinedKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSUndefinedKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSUndefinedKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSUndefinedKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSUndefinedKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSUndefinedKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSTuple(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateETSTuple(_context); + return result; +} +KOALA_INTEROP_1(CreateETSTuple, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSTuple(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateETSTuple(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateETSTuple, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSTuple1(KNativePointer context, KUInt size) +{ + const auto _context = reinterpret_cast(context); + const auto _size = static_cast(size); + auto result = GetImpl()->CreateETSTuple1(_context, _size); + return result; +} +KOALA_INTEROP_2(CreateETSTuple1, KNativePointer, KNativePointer, KUInt); + +KNativePointer impl_UpdateETSTuple1(KNativePointer context, KNativePointer original, KUInt size) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _size = static_cast(size); + auto result = GetImpl()->UpdateETSTuple1(_context, _original, _size); + return result; +} +KOALA_INTEROP_3(UpdateETSTuple1, KNativePointer, KNativePointer, KNativePointer, KUInt); + +KNativePointer impl_CreateETSTuple2(KNativePointer context, KNativePointerArray typeList, KUInt typeListSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _typeList = reinterpret_cast(typeList); + const auto _typeListSequenceLength = static_cast(typeListSequenceLength); + auto result = GetImpl()->CreateETSTuple2(_context, _typeList, _typeListSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateETSTuple2, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateETSTuple2(KNativePointer context, KNativePointer original, KNativePointerArray typeList, KUInt typeListSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeList = reinterpret_cast(typeList); + const auto _typeListSequenceLength = static_cast(typeListSequenceLength); + auto result = GetImpl()->UpdateETSTuple2(_context, _original, _typeList, _typeListSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateETSTuple2, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KUInt impl_ETSTupleGetTupleSizeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTupleGetTupleSizeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSTupleGetTupleSizeConst, KUInt, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTupleGetTupleTypeAnnotationsListConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSTupleGetTupleTypeAnnotationsListConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSTupleGetTupleTypeAnnotationsListConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSTupleSetTypeAnnotationsList(KNativePointer context, KNativePointer receiver, KNativePointerArray typeNodeList, KUInt typeNodeListSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeNodeList = reinterpret_cast(typeNodeList); + const auto _typeNodeListSequenceLength = static_cast(typeNodeListSequenceLength); + GetImpl()->ETSTupleSetTypeAnnotationsList(_context, _receiver, _typeNodeList, _typeNodeListSequenceLength); + return ; +} +KOALA_INTEROP_V4(ETSTupleSetTypeAnnotationsList, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TryStatementFinallyBlockConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TryStatementFinallyBlockConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TryStatementFinallyBlockConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TryStatementBlockConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TryStatementBlockConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TryStatementBlockConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TryStatementHasFinalizerConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TryStatementHasFinalizerConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TryStatementHasFinalizerConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TryStatementHasDefaultCatchClauseConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TryStatementHasDefaultCatchClauseConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TryStatementHasDefaultCatchClauseConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_TryStatementCatchClausesConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TryStatementCatchClausesConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TryStatementCatchClausesConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TryStatementFinallyCanCompleteNormallyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TryStatementFinallyCanCompleteNormallyConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TryStatementFinallyCanCompleteNormallyConst, KBoolean, KNativePointer, KNativePointer); + +void impl_TryStatementSetFinallyCanCompleteNormally(KNativePointer context, KNativePointer receiver, KBoolean finallyCanCompleteNormally) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _finallyCanCompleteNormally = static_cast(finallyCanCompleteNormally); + GetImpl()->TryStatementSetFinallyCanCompleteNormally(_context, _receiver, _finallyCanCompleteNormally); + return ; +} +KOALA_INTEROP_V3(TryStatementSetFinallyCanCompleteNormally, KNativePointer, KNativePointer, KBoolean); + +KBoolean impl_AstNodeIsProgramConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsProgramConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsProgramConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsStatementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsStatementConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsStatementConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsExpressionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsExpressionConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsExpressionConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsTypedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsTypedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsTypedConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeAsTyped(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeAsTyped(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeAsTyped, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeAsTypedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeAsTypedConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AstNodeAsTypedConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsBrokenStatementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsBrokenStatementConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsBrokenStatementConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeAsExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeAsExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeAsExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeAsExpressionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeAsExpressionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AstNodeAsExpressionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeAsStatement(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeAsStatement(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeAsStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeAsStatementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeAsStatementConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AstNodeAsStatementConst, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_AstNodeTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeTypeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeTypeConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeParent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeParent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeParent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeParentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeParentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AstNodeParentConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AstNodeSetParent(KNativePointer context, KNativePointer receiver, KNativePointer parent) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _parent = reinterpret_cast(parent); + GetImpl()->AstNodeSetParent(_context, _receiver, _parent); + return ; +} +KOALA_INTEROP_V3(AstNodeSetParent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeDecoratorsPtrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AstNodeDecoratorsPtrConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(AstNodeDecoratorsPtrConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AstNodeAddDecorators(KNativePointer context, KNativePointer receiver, KNativePointerArray decorators, KUInt decoratorsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _decorators = reinterpret_cast(decorators); + const auto _decoratorsSequenceLength = static_cast(decoratorsSequenceLength); + GetImpl()->AstNodeAddDecorators(_context, _receiver, _decorators, _decoratorsSequenceLength); + return ; +} +KOALA_INTEROP_V4(AstNodeAddDecorators, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KBoolean impl_AstNodeCanHaveDecoratorConst(KNativePointer context, KNativePointer receiver, KBoolean inTs) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _inTs = static_cast(inTs); + auto result = GetImpl()->AstNodeCanHaveDecoratorConst(_context, _receiver, _inTs); + return result; +} +KOALA_INTEROP_3(AstNodeCanHaveDecoratorConst, KBoolean, KNativePointer, KNativePointer, KBoolean); + +KBoolean impl_AstNodeIsReadonlyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsReadonlyConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsReadonlyConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsReadonlyTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsReadonlyTypeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsReadonlyTypeConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsOptionalDeclarationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsOptionalDeclarationConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsOptionalDeclarationConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsDefiniteConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsDefiniteConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsDefiniteConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsConstructorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsConstructorConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsConstructorConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsOverrideConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsOverrideConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsOverrideConst, KBoolean, KNativePointer, KNativePointer); + +void impl_AstNodeSetOverride(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->AstNodeSetOverride(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(AstNodeSetOverride, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsAsyncConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsAsyncConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsAsyncConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsSynchronizedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsSynchronizedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsSynchronizedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsNativeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsNativeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsNativeConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsConstConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsConstConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsConstConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsStaticConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsStaticConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsStaticConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsFinalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsFinalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsFinalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsAbstractConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsAbstractConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsAbstractConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsPublicConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsPublicConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsPublicConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsProtectedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsProtectedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsProtectedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsPrivateConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsPrivateConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsPrivateConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsInternalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsInternalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsInternalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsExportedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsExportedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsExportedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsDefaultExportedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsDefaultExportedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsDefaultExportedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsExportedTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsExportedTypeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsExportedTypeConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsDeclareConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsDeclareConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsDeclareConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsInConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsInConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsInConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsOutConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsOutConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsOutConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsSetterConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsSetterConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsSetterConst, KBoolean, KNativePointer, KNativePointer); + +void impl_AstNodeAddModifier(KNativePointer context, KNativePointer receiver, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _flags = static_cast(flags); + GetImpl()->AstNodeAddModifier(_context, _receiver, _flags); + return ; +} +KOALA_INTEROP_V3(AstNodeAddModifier, KNativePointer, KNativePointer, KInt); + +void impl_AstNodeClearModifier(KNativePointer context, KNativePointer receiver, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _flags = static_cast(flags); + GetImpl()->AstNodeClearModifier(_context, _receiver, _flags); + return ; +} +KOALA_INTEROP_V3(AstNodeClearModifier, KNativePointer, KNativePointer, KInt); + +KInt impl_AstNodeModifiers(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeModifiers(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeModifiers, KInt, KNativePointer, KNativePointer); + +KInt impl_AstNodeModifiersConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeModifiersConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeModifiersConst, KInt, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeHasExportAliasConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeHasExportAliasConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeHasExportAliasConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeAsClassElement(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeAsClassElement(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeAsClassElement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeAsClassElementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeAsClassElementConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AstNodeAsClassElementConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_AstNodeIsScopeBearerConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeIsScopeBearerConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeIsScopeBearerConst, KBoolean, KNativePointer, KNativePointer); + +void impl_AstNodeClearScope(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->AstNodeClearScope(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(AstNodeClearScope, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeGetTopStatement(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeGetTopStatement(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AstNodeGetTopStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeGetTopStatementConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeGetTopStatementConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AstNodeGetTopStatementConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeClone(KNativePointer context, KNativePointer receiver, KNativePointer parent) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _parent = reinterpret_cast(parent); + auto result = GetImpl()->AstNodeClone(_context, _receiver, _parent); + return result; +} +KOALA_INTEROP_3(AstNodeClone, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeDumpJSONConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeDumpJSONConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(AstNodeDumpJSONConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeDumpEtsSrcConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeDumpEtsSrcConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(AstNodeDumpEtsSrcConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AstNodeDumpConst(KNativePointer context, KNativePointer receiver, KNativePointer dumper) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _dumper = reinterpret_cast(dumper); + GetImpl()->AstNodeDumpConst(_context, _receiver, _dumper); + return ; +} +KOALA_INTEROP_V3(AstNodeDumpConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AstNodeDumpConst1(KNativePointer context, KNativePointer receiver, KNativePointer dumper) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _dumper = reinterpret_cast(dumper); + GetImpl()->AstNodeDumpConst1(_context, _receiver, _dumper); + return ; +} +KOALA_INTEROP_V3(AstNodeDumpConst1, KNativePointer, KNativePointer, KNativePointer); + +void impl_AstNodeSetTransformedNode(KNativePointer context, KNativePointer receiver, KStringPtr& transformationName, KNativePointer transformedNode) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _transformationName = getStringCopy(transformationName); + const auto _transformedNode = reinterpret_cast(transformedNode); + GetImpl()->AstNodeSetTransformedNode(_context, _receiver, _transformationName, _transformedNode); + return ; +} +KOALA_INTEROP_V4(AstNodeSetTransformedNode, KNativePointer, KNativePointer, KStringPtr, KNativePointer); + +void impl_AstNodeSetOriginalNode(KNativePointer context, KNativePointer receiver, KNativePointer originalNode) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _originalNode = reinterpret_cast(originalNode); + GetImpl()->AstNodeSetOriginalNode(_context, _receiver, _originalNode); + return ; +} +KOALA_INTEROP_V3(AstNodeSetOriginalNode, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeOriginalNodeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstNodeOriginalNodeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AstNodeOriginalNodeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateUnaryExpression(KNativePointer context, KNativePointer argument, KInt unaryOperator) +{ + const auto _context = reinterpret_cast(context); + const auto _argument = reinterpret_cast(argument); + const auto _unaryOperator = static_cast(unaryOperator); + auto result = GetImpl()->CreateUnaryExpression(_context, _argument, _unaryOperator); + return result; +} +KOALA_INTEROP_3(CreateUnaryExpression, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateUnaryExpression(KNativePointer context, KNativePointer original, KNativePointer argument, KInt unaryOperator) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _argument = reinterpret_cast(argument); + const auto _unaryOperator = static_cast(unaryOperator); + auto result = GetImpl()->UpdateUnaryExpression(_context, _original, _argument, _unaryOperator); + return result; +} +KOALA_INTEROP_4(UpdateUnaryExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KInt impl_UnaryExpressionOperatorTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->UnaryExpressionOperatorTypeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(UnaryExpressionOperatorTypeConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_UnaryExpressionArgument(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->UnaryExpressionArgument(_context, _receiver); + return result; +} +KOALA_INTEROP_2(UnaryExpressionArgument, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UnaryExpressionArgumentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->UnaryExpressionArgumentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(UnaryExpressionArgumentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateForInStatement(KNativePointer context, KNativePointer left, KNativePointer right, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->CreateForInStatement(_context, _left, _right, _body); + return result; +} +KOALA_INTEROP_4(CreateForInStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateForInStatement(KNativePointer context, KNativePointer original, KNativePointer left, KNativePointer right, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->UpdateForInStatement(_context, _original, _left, _right, _body); + return result; +} +KOALA_INTEROP_5(UpdateForInStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForInStatementLeft(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForInStatementLeft(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForInStatementLeft, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForInStatementLeftConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForInStatementLeftConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForInStatementLeftConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForInStatementRight(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForInStatementRight(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForInStatementRight, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForInStatementRightConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForInStatementRightConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForInStatementRightConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForInStatementBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForInStatementBody(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForInStatementBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForInStatementBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForInStatementBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForInStatementBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateThisExpression(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateThisExpression(_context); + return result; +} +KOALA_INTEROP_1(CreateThisExpression, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateThisExpression(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateThisExpression(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateThisExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSMethodSignature(KNativePointer context, KNativePointer key, KNativePointer signature, KBoolean computed, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _key = reinterpret_cast(key); + const auto _signature = reinterpret_cast(signature); + const auto _computed = static_cast(computed); + const auto _optional_arg = static_cast(optional_arg); + auto result = GetImpl()->CreateTSMethodSignature(_context, _key, _signature, _computed, _optional_arg); + return result; +} +KOALA_INTEROP_5(CreateTSMethodSignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_UpdateTSMethodSignature(KNativePointer context, KNativePointer original, KNativePointer key, KNativePointer signature, KBoolean computed, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _key = reinterpret_cast(key); + const auto _signature = reinterpret_cast(signature); + const auto _computed = static_cast(computed); + const auto _optional_arg = static_cast(optional_arg); + auto result = GetImpl()->UpdateTSMethodSignature(_context, _original, _key, _signature, _computed, _optional_arg); + return result; +} +KOALA_INTEROP_6(UpdateTSMethodSignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_TSMethodSignatureKeyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMethodSignatureKeyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSMethodSignatureKeyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSMethodSignatureKey(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMethodSignatureKey(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMethodSignatureKey, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSMethodSignatureTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMethodSignatureTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSMethodSignatureTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSMethodSignatureTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMethodSignatureTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMethodSignatureTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSMethodSignatureParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSMethodSignatureParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSMethodSignatureParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSMethodSignatureReturnTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMethodSignatureReturnTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSMethodSignatureReturnTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSMethodSignatureReturnTypeAnnotation(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMethodSignatureReturnTypeAnnotation(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMethodSignatureReturnTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSMethodSignatureComputedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMethodSignatureComputedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMethodSignatureComputedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSMethodSignatureOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMethodSignatureOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMethodSignatureOptionalConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateBinaryExpression(KNativePointer context, KNativePointer left, KNativePointer right, KInt operatorType) +{ + const auto _context = reinterpret_cast(context); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _operatorType = static_cast(operatorType); + auto result = GetImpl()->CreateBinaryExpression(_context, _left, _right, _operatorType); + return result; +} +KOALA_INTEROP_4(CreateBinaryExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateBinaryExpression(KNativePointer context, KNativePointer original, KNativePointer left, KNativePointer right, KInt operatorType) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _operatorType = static_cast(operatorType); + auto result = GetImpl()->UpdateBinaryExpression(_context, _original, _left, _right, _operatorType); + return result; +} +KOALA_INTEROP_5(UpdateBinaryExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_BinaryExpressionLeftConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionLeftConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(BinaryExpressionLeftConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BinaryExpressionLeft(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionLeft(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BinaryExpressionLeft, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BinaryExpressionRightConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionRightConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(BinaryExpressionRightConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BinaryExpressionRight(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionRight(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BinaryExpressionRight, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BinaryExpressionResultConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionResultConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(BinaryExpressionResultConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BinaryExpressionResult(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionResult(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BinaryExpressionResult, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_BinaryExpressionOperatorTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionOperatorTypeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BinaryExpressionOperatorTypeConst, KInt, KNativePointer, KNativePointer); + +KBoolean impl_BinaryExpressionIsLogicalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionIsLogicalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BinaryExpressionIsLogicalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_BinaryExpressionIsLogicalExtendedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionIsLogicalExtendedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BinaryExpressionIsLogicalExtendedConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_BinaryExpressionIsBitwiseConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionIsBitwiseConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BinaryExpressionIsBitwiseConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_BinaryExpressionIsArithmeticConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BinaryExpressionIsArithmeticConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BinaryExpressionIsArithmeticConst, KBoolean, KNativePointer, KNativePointer); + +void impl_BinaryExpressionSetLeft(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->BinaryExpressionSetLeft(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(BinaryExpressionSetLeft, KNativePointer, KNativePointer, KNativePointer); + +void impl_BinaryExpressionSetRight(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->BinaryExpressionSetRight(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(BinaryExpressionSetRight, KNativePointer, KNativePointer, KNativePointer); + +void impl_BinaryExpressionSetResult(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->BinaryExpressionSetResult(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(BinaryExpressionSetResult, KNativePointer, KNativePointer, KNativePointer); + +void impl_BinaryExpressionSetOperator(KNativePointer context, KNativePointer receiver, KInt operatorType) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _operatorType = static_cast(operatorType); + GetImpl()->BinaryExpressionSetOperator(_context, _receiver, _operatorType); + return ; +} +KOALA_INTEROP_V3(BinaryExpressionSetOperator, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_CreateSuperExpression(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateSuperExpression(_context); + return result; +} +KOALA_INTEROP_1(CreateSuperExpression, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateSuperExpression(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateSuperExpression(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateSuperExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateAssertStatement(KNativePointer context, KNativePointer test, KNativePointer second) +{ + const auto _context = reinterpret_cast(context); + const auto _test = reinterpret_cast(test); + const auto _second = reinterpret_cast(second); + auto result = GetImpl()->CreateAssertStatement(_context, _test, _second); + return result; +} +KOALA_INTEROP_3(CreateAssertStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateAssertStatement(KNativePointer context, KNativePointer original, KNativePointer test, KNativePointer second) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _test = reinterpret_cast(test); + const auto _second = reinterpret_cast(second); + auto result = GetImpl()->UpdateAssertStatement(_context, _original, _test, _second); + return result; +} +KOALA_INTEROP_4(UpdateAssertStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AssertStatementTestConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssertStatementTestConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AssertStatementTestConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AssertStatementTest(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssertStatementTest(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AssertStatementTest, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AssertStatementSecondConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssertStatementSecondConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AssertStatementSecondConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSStringKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSStringKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSStringKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSStringKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSStringKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSStringKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateAssignmentExpression(KNativePointer context, KNativePointer left, KNativePointer right, KInt assignmentOperator) +{ + const auto _context = reinterpret_cast(context); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _assignmentOperator = static_cast(assignmentOperator); + auto result = GetImpl()->CreateAssignmentExpression(_context, _left, _right, _assignmentOperator); + return result; +} +KOALA_INTEROP_4(CreateAssignmentExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateAssignmentExpression(KNativePointer context, KNativePointer original, KNativePointer left, KNativePointer right, KInt assignmentOperator) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _assignmentOperator = static_cast(assignmentOperator); + auto result = GetImpl()->UpdateAssignmentExpression(_context, _original, _left, _right, _assignmentOperator); + return result; +} +KOALA_INTEROP_5(UpdateAssignmentExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_CreateAssignmentExpression1(KNativePointer context, KInt type, KNativePointer left, KNativePointer right, KInt assignmentOperator) +{ + const auto _context = reinterpret_cast(context); + const auto _type = static_cast(type); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _assignmentOperator = static_cast(assignmentOperator); + auto result = GetImpl()->CreateAssignmentExpression1(_context, _type, _left, _right, _assignmentOperator); + return result; +} +KOALA_INTEROP_5(CreateAssignmentExpression1, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateAssignmentExpression1(KNativePointer context, KNativePointer original, KInt type, KNativePointer left, KNativePointer right, KInt assignmentOperator) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _type = static_cast(type); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _assignmentOperator = static_cast(assignmentOperator); + auto result = GetImpl()->UpdateAssignmentExpression1(_context, _original, _type, _left, _right, _assignmentOperator); + return result; +} +KOALA_INTEROP_6(UpdateAssignmentExpression1, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_AssignmentExpressionLeftConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionLeftConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AssignmentExpressionLeftConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AssignmentExpressionLeft(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionLeft(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AssignmentExpressionLeft, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AssignmentExpressionRight(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionRight(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AssignmentExpressionRight, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AssignmentExpressionRightConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionRightConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AssignmentExpressionRightConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AssignmentExpressionSetRight(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->AssignmentExpressionSetRight(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(AssignmentExpressionSetRight, KNativePointer, KNativePointer, KNativePointer); + +void impl_AssignmentExpressionSetLeft(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->AssignmentExpressionSetLeft(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(AssignmentExpressionSetLeft, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AssignmentExpressionResultConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionResultConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AssignmentExpressionResultConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AssignmentExpressionResult(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionResult(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AssignmentExpressionResult, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_AssignmentExpressionOperatorTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionOperatorTypeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AssignmentExpressionOperatorTypeConst, KInt, KNativePointer, KNativePointer); + +KInt impl_AssignmentExpressionSetOperatorType(KNativePointer context, KNativePointer receiver, KInt tokenType) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _tokenType = static_cast(tokenType); + auto result = GetImpl()->AssignmentExpressionSetOperatorType(_context, _receiver, _tokenType); + return result; +} +KOALA_INTEROP_3(AssignmentExpressionSetOperatorType, KInt, KNativePointer, KNativePointer, KInt); + +void impl_AssignmentExpressionSetResult(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->AssignmentExpressionSetResult(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(AssignmentExpressionSetResult, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_AssignmentExpressionIsLogicalExtendedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionIsLogicalExtendedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AssignmentExpressionIsLogicalExtendedConst, KBoolean, KNativePointer, KNativePointer); + +void impl_AssignmentExpressionSetIgnoreConstAssign(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->AssignmentExpressionSetIgnoreConstAssign(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(AssignmentExpressionSetIgnoreConstAssign, KNativePointer, KNativePointer); + +KBoolean impl_AssignmentExpressionIsIgnoreConstAssignConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionIsIgnoreConstAssignConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AssignmentExpressionIsIgnoreConstAssignConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AssignmentExpressionConvertibleToAssignmentPatternLeft(KNativePointer context, KNativePointer receiver, KBoolean mustBePattern) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _mustBePattern = static_cast(mustBePattern); + auto result = GetImpl()->AssignmentExpressionConvertibleToAssignmentPatternLeft(_context, _receiver, _mustBePattern); + return result; +} +KOALA_INTEROP_3(AssignmentExpressionConvertibleToAssignmentPatternLeft, KBoolean, KNativePointer, KNativePointer, KBoolean); + +KBoolean impl_AssignmentExpressionConvertibleToAssignmentPatternRight(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AssignmentExpressionConvertibleToAssignmentPatternRight(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AssignmentExpressionConvertibleToAssignmentPatternRight, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AssignmentExpressionConvertibleToAssignmentPattern(KNativePointer context, KNativePointer receiver, KBoolean mustBePattern) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _mustBePattern = static_cast(mustBePattern); + auto result = GetImpl()->AssignmentExpressionConvertibleToAssignmentPattern(_context, _receiver, _mustBePattern); + return result; +} +KOALA_INTEROP_3(AssignmentExpressionConvertibleToAssignmentPattern, KBoolean, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_CreateExpressionStatement(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateExpressionStatement(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateExpressionStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateExpressionStatement(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateExpressionStatement(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateExpressionStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionStatementGetExpressionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionStatementGetExpressionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExpressionStatementGetExpressionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionStatementGetExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionStatementGetExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionStatementGetExpression, KNativePointer, KNativePointer, KNativePointer); + +void impl_ExpressionStatementSetExpression(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->ExpressionStatementSetExpression(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(ExpressionStatementSetExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSModuleIdent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSModuleIdent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSModuleIdent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSModuleIdentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSModuleIdentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSModuleIdentConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ETSModuleIsETSScriptConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSModuleIsETSScriptConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSModuleIsETSScriptConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ETSModuleIsNamespaceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSModuleIsNamespaceConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSModuleIsNamespaceConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ETSModuleIsNamespaceChainLastNodeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSModuleIsNamespaceChainLastNodeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSModuleIsNamespaceChainLastNodeConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ETSModuleSetNamespaceChainLastNode(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ETSModuleSetNamespaceChainLastNode(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ETSModuleSetNamespaceChainLastNode, KNativePointer, KNativePointer); + +KNativePointer impl_ETSModuleAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSModuleAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSModuleAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSModuleAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSModuleAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSModuleAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSModuleSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->ETSModuleSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(ETSModuleSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateMetaProperty(KNativePointer context, KInt kind) +{ + const auto _context = reinterpret_cast(context); + const auto _kind = static_cast(kind); + auto result = GetImpl()->CreateMetaProperty(_context, _kind); + return result; +} +KOALA_INTEROP_2(CreateMetaProperty, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateMetaProperty(KNativePointer context, KNativePointer original, KInt kind) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _kind = static_cast(kind); + auto result = GetImpl()->UpdateMetaProperty(_context, _original, _kind); + return result; +} +KOALA_INTEROP_3(UpdateMetaProperty, KNativePointer, KNativePointer, KNativePointer, KInt); + +KInt impl_MetaPropertyKindConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MetaPropertyKindConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MetaPropertyKindConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSArrayType(KNativePointer context, KNativePointer elementType) +{ + const auto _context = reinterpret_cast(context); + const auto _elementType = reinterpret_cast(elementType); + auto result = GetImpl()->CreateTSArrayType(_context, _elementType); + return result; +} +KOALA_INTEROP_2(CreateTSArrayType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSArrayType(KNativePointer context, KNativePointer original, KNativePointer elementType) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _elementType = reinterpret_cast(elementType); + auto result = GetImpl()->UpdateTSArrayType(_context, _original, _elementType); + return result; +} +KOALA_INTEROP_3(UpdateTSArrayType, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSArrayTypeElementTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSArrayTypeElementTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSArrayTypeElementTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSSignatureDeclaration(KNativePointer context, KInt kind, KNativePointer signature) +{ + const auto _context = reinterpret_cast(context); + const auto _kind = static_cast(kind); + const auto _signature = reinterpret_cast(signature); + auto result = GetImpl()->CreateTSSignatureDeclaration(_context, _kind, _signature); + return result; +} +KOALA_INTEROP_3(CreateTSSignatureDeclaration, KNativePointer, KNativePointer, KInt, KNativePointer); + +KNativePointer impl_UpdateTSSignatureDeclaration(KNativePointer context, KNativePointer original, KInt kind, KNativePointer signature) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _kind = static_cast(kind); + const auto _signature = reinterpret_cast(signature); + auto result = GetImpl()->UpdateTSSignatureDeclaration(_context, _original, _kind, _signature); + return result; +} +KOALA_INTEROP_4(UpdateTSSignatureDeclaration, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointer); + +KNativePointer impl_TSSignatureDeclarationTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSSignatureDeclarationTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSSignatureDeclarationTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSSignatureDeclarationTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSSignatureDeclarationTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSSignatureDeclarationTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSSignatureDeclarationParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSSignatureDeclarationParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSSignatureDeclarationParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSSignatureDeclarationReturnTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSSignatureDeclarationReturnTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSSignatureDeclarationReturnTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSSignatureDeclarationReturnTypeAnnotation(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSSignatureDeclarationReturnTypeAnnotation(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSSignatureDeclarationReturnTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_TSSignatureDeclarationKindConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSSignatureDeclarationKindConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSSignatureDeclarationKindConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_CreateExportAllDeclaration(KNativePointer context, KNativePointer source, KNativePointer exported) +{ + const auto _context = reinterpret_cast(context); + const auto _source = reinterpret_cast(source); + const auto _exported = reinterpret_cast(exported); + auto result = GetImpl()->CreateExportAllDeclaration(_context, _source, _exported); + return result; +} +KOALA_INTEROP_3(CreateExportAllDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateExportAllDeclaration(KNativePointer context, KNativePointer original, KNativePointer source, KNativePointer exported) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _source = reinterpret_cast(source); + const auto _exported = reinterpret_cast(exported); + auto result = GetImpl()->UpdateExportAllDeclaration(_context, _original, _source, _exported); + return result; +} +KOALA_INTEROP_4(UpdateExportAllDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExportAllDeclarationSourceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportAllDeclarationSourceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExportAllDeclarationSourceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExportAllDeclarationExportedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportAllDeclarationExportedConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExportAllDeclarationExportedConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateExportSpecifier(KNativePointer context, KNativePointer local, KNativePointer exported) +{ + const auto _context = reinterpret_cast(context); + const auto _local = reinterpret_cast(local); + const auto _exported = reinterpret_cast(exported); + auto result = GetImpl()->CreateExportSpecifier(_context, _local, _exported); + return result; +} +KOALA_INTEROP_3(CreateExportSpecifier, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateExportSpecifier(KNativePointer context, KNativePointer original, KNativePointer local, KNativePointer exported) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _local = reinterpret_cast(local); + const auto _exported = reinterpret_cast(exported); + auto result = GetImpl()->UpdateExportSpecifier(_context, _original, _local, _exported); + return result; +} +KOALA_INTEROP_4(UpdateExportSpecifier, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExportSpecifierLocalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportSpecifierLocalConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExportSpecifierLocalConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExportSpecifierExportedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportSpecifierExportedConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExportSpecifierExportedConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTupleType(KNativePointer context, KNativePointerArray elementTypes, KUInt elementTypesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _elementTypes = reinterpret_cast(elementTypes); + const auto _elementTypesSequenceLength = static_cast(elementTypesSequenceLength); + auto result = GetImpl()->CreateTSTupleType(_context, _elementTypes, _elementTypesSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateTSTupleType, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateTSTupleType(KNativePointer context, KNativePointer original, KNativePointerArray elementTypes, KUInt elementTypesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _elementTypes = reinterpret_cast(elementTypes); + const auto _elementTypesSequenceLength = static_cast(elementTypesSequenceLength); + auto result = GetImpl()->UpdateTSTupleType(_context, _original, _elementTypes, _elementTypesSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateTSTupleType, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TSTupleTypeElementTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTupleTypeElementTypeConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTupleTypeElementTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateFunctionExpression(KNativePointer context, KNativePointer func) +{ + const auto _context = reinterpret_cast(context); + const auto _func = reinterpret_cast(func); + auto result = GetImpl()->CreateFunctionExpression(_context, _func); + return result; +} +KOALA_INTEROP_2(CreateFunctionExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateFunctionExpression(KNativePointer context, KNativePointer original, KNativePointer func) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _func = reinterpret_cast(func); + auto result = GetImpl()->UpdateFunctionExpression(_context, _original, _func); + return result; +} +KOALA_INTEROP_3(UpdateFunctionExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateFunctionExpression1(KNativePointer context, KNativePointer namedExpr, KNativePointer func) +{ + const auto _context = reinterpret_cast(context); + const auto _namedExpr = reinterpret_cast(namedExpr); + const auto _func = reinterpret_cast(func); + auto result = GetImpl()->CreateFunctionExpression1(_context, _namedExpr, _func); + return result; +} +KOALA_INTEROP_3(CreateFunctionExpression1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateFunctionExpression1(KNativePointer context, KNativePointer original, KNativePointer namedExpr, KNativePointer func) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _namedExpr = reinterpret_cast(namedExpr); + const auto _func = reinterpret_cast(func); + auto result = GetImpl()->UpdateFunctionExpression1(_context, _original, _namedExpr, _func); + return result; +} +KOALA_INTEROP_4(UpdateFunctionExpression1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionExpressionFunctionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionExpressionFunctionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(FunctionExpressionFunctionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionExpressionFunction(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionExpressionFunction(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionExpressionFunction, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_FunctionExpressionIsAnonymousConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionExpressionIsAnonymousConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionExpressionIsAnonymousConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionExpressionId(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionExpressionId(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionExpressionId, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSIndexSignature(KNativePointer context, KNativePointer param, KNativePointer typeAnnotation, KBoolean readonly_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _param = reinterpret_cast(param); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _readonly_arg = static_cast(readonly_arg); + auto result = GetImpl()->CreateTSIndexSignature(_context, _param, _typeAnnotation, _readonly_arg); + return result; +} +KOALA_INTEROP_4(CreateTSIndexSignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateTSIndexSignature(KNativePointer context, KNativePointer original, KNativePointer param, KNativePointer typeAnnotation, KBoolean readonly_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _param = reinterpret_cast(param); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _readonly_arg = static_cast(readonly_arg); + auto result = GetImpl()->UpdateTSIndexSignature(_context, _original, _param, _typeAnnotation, _readonly_arg); + return result; +} +KOALA_INTEROP_5(UpdateTSIndexSignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSIndexSignatureParamConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSIndexSignatureParamConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSIndexSignatureParamConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSIndexSignatureTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSIndexSignatureTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSIndexSignatureTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSIndexSignatureReadonlyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSIndexSignatureReadonlyConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSIndexSignatureReadonlyConst, KBoolean, KNativePointer, KNativePointer); + +KInt impl_TSIndexSignatureKindConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSIndexSignatureKindConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSIndexSignatureKindConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSModuleDeclaration(KNativePointer context, KNativePointer name, KNativePointer body, KBoolean declare, KBoolean _global) +{ + const auto _context = reinterpret_cast(context); + const auto _name = reinterpret_cast(name); + const auto _body = reinterpret_cast(body); + const auto _declare = static_cast(declare); + const auto __global = static_cast(_global); + auto result = GetImpl()->CreateTSModuleDeclaration(_context, _name, _body, _declare, __global); + return result; +} +KOALA_INTEROP_5(CreateTSModuleDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_UpdateTSModuleDeclaration(KNativePointer context, KNativePointer original, KNativePointer name, KNativePointer body, KBoolean declare, KBoolean _global) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = reinterpret_cast(name); + const auto _body = reinterpret_cast(body); + const auto _declare = static_cast(declare); + const auto __global = static_cast(_global); + auto result = GetImpl()->UpdateTSModuleDeclaration(_context, _original, _name, _body, _declare, __global); + return result; +} +KOALA_INTEROP_6(UpdateTSModuleDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_TSModuleDeclarationNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSModuleDeclarationNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSModuleDeclarationNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSModuleDeclarationBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSModuleDeclarationBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSModuleDeclarationBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSModuleDeclarationGlobalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSModuleDeclarationGlobalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSModuleDeclarationGlobalConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSModuleDeclarationIsExternalOrAmbientConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSModuleDeclarationIsExternalOrAmbientConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSModuleDeclarationIsExternalOrAmbientConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateImportDeclaration(KNativePointer context, KNativePointer source, KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind) +{ + const auto _context = reinterpret_cast(context); + const auto _source = reinterpret_cast(source); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + const auto _importKind = static_cast(importKind); + auto result = GetImpl()->CreateImportDeclaration(_context, _source, _specifiers, _specifiersSequenceLength, _importKind); + return result; +} +KOALA_INTEROP_5(CreateImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt); + +KNativePointer impl_UpdateImportDeclaration(KNativePointer context, KNativePointer original, KNativePointer source, KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _source = reinterpret_cast(source); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + const auto _importKind = static_cast(importKind); + auto result = GetImpl()->UpdateImportDeclaration(_context, _original, _source, _specifiers, _specifiersSequenceLength, _importKind); + return result; +} +KOALA_INTEROP_6(UpdateImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt); + +KNativePointer impl_ImportDeclarationSourceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportDeclarationSourceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ImportDeclarationSourceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportDeclarationSource(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportDeclarationSource(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ImportDeclarationSource, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportDeclarationSpecifiersConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ImportDeclarationSpecifiersConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ImportDeclarationSpecifiersConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportDeclarationSpecifiers(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ImportDeclarationSpecifiers(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ImportDeclarationSpecifiers, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ImportDeclarationIsTypeKindConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportDeclarationIsTypeKindConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ImportDeclarationIsTypeKindConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSParenthesizedType(KNativePointer context, KNativePointer type) +{ + const auto _context = reinterpret_cast(context); + const auto _type = reinterpret_cast(type); + auto result = GetImpl()->CreateTSParenthesizedType(_context, _type); + return result; +} +KOALA_INTEROP_2(CreateTSParenthesizedType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSParenthesizedType(KNativePointer context, KNativePointer original, KNativePointer type) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _type = reinterpret_cast(type); + auto result = GetImpl()->UpdateTSParenthesizedType(_context, _original, _type); + return result; +} +KOALA_INTEROP_3(UpdateTSParenthesizedType, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSParenthesizedTypeTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSParenthesizedTypeTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSParenthesizedTypeTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateCharLiteral(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateCharLiteral(_context); + return result; +} +KOALA_INTEROP_1(CreateCharLiteral, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateCharLiteral(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateCharLiteral(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateCharLiteral, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSPackageDeclaration(KNativePointer context, KNativePointer name) +{ + const auto _context = reinterpret_cast(context); + const auto _name = reinterpret_cast(name); + auto result = GetImpl()->CreateETSPackageDeclaration(_context, _name); + return result; +} +KOALA_INTEROP_2(CreateETSPackageDeclaration, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSPackageDeclaration(KNativePointer context, KNativePointer original, KNativePointer name) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = reinterpret_cast(name); + auto result = GetImpl()->UpdateETSPackageDeclaration(_context, _original, _name); + return result; +} +KOALA_INTEROP_3(UpdateETSPackageDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSImportDeclaration(KNativePointer context, KNativePointer source , KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind) +{ + const auto _context = reinterpret_cast(context); + const auto _source = reinterpret_cast(source); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + const auto _importKind = static_cast(importKind); + auto result = GetImpl()->ETSParserBuildImportDeclaration(_context, _importKind, _specifiers, _specifiersSequenceLength, _source); + return result; +} +KOALA_INTEROP_5(CreateETSImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt); + +KNativePointer impl_UpdateETSImportDeclaration(KNativePointer context, KNativePointer original, KNativePointer source, KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _source = reinterpret_cast(source); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + const auto _importKind = static_cast(importKind); + auto result = GetImpl()->UpdateETSImportDeclaration(_context, _original, _source, _specifiers, _specifiersSequenceLength, _importKind); + return result; +} +KOALA_INTEROP_6(UpdateETSImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt); + +KNativePointer impl_ETSImportDeclarationAssemblerName(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSImportDeclarationAssemblerName(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ETSImportDeclarationAssemblerName, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSImportDeclarationAssemblerNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSImportDeclarationAssemblerNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ETSImportDeclarationAssemblerNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSImportDeclarationResolvedSourceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSImportDeclarationResolvedSourceConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ETSImportDeclarationResolvedSourceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSStructDeclaration(KNativePointer context, KNativePointer def) +{ + const auto _context = reinterpret_cast(context); + const auto _def = reinterpret_cast(def); + auto result = GetImpl()->CreateETSStructDeclaration(_context, _def); + return result; +} +KOALA_INTEROP_2(CreateETSStructDeclaration, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSStructDeclaration(KNativePointer context, KNativePointer original, KNativePointer def) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _def = reinterpret_cast(def); + auto result = GetImpl()->UpdateETSStructDeclaration(_context, _original, _def); + return result; +} +KOALA_INTEROP_3(UpdateETSStructDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSModuleBlock(KNativePointer context, KNativePointerArray statements, KUInt statementsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _statements = reinterpret_cast(statements); + const auto _statementsSequenceLength = static_cast(statementsSequenceLength); + auto result = GetImpl()->CreateTSModuleBlock(_context, _statements, _statementsSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateTSModuleBlock, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateTSModuleBlock(KNativePointer context, KNativePointer original, KNativePointerArray statements, KUInt statementsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _statements = reinterpret_cast(statements); + const auto _statementsSequenceLength = static_cast(statementsSequenceLength); + auto result = GetImpl()->UpdateTSModuleBlock(_context, _original, _statements, _statementsSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateTSModuleBlock, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TSModuleBlockStatementsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSModuleBlockStatementsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSModuleBlockStatementsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSNewArrayInstanceExpression(KNativePointer context, KNativePointer typeReference, KNativePointer dimension) +{ + const auto _context = reinterpret_cast(context); + const auto _typeReference = reinterpret_cast(typeReference); + const auto _dimension = reinterpret_cast(dimension); + auto result = GetImpl()->CreateETSNewArrayInstanceExpression(_context, _typeReference, _dimension); + return result; +} +KOALA_INTEROP_3(CreateETSNewArrayInstanceExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSNewArrayInstanceExpression(KNativePointer context, KNativePointer original, KNativePointer typeReference, KNativePointer dimension) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeReference = reinterpret_cast(typeReference); + const auto _dimension = reinterpret_cast(dimension); + auto result = GetImpl()->UpdateETSNewArrayInstanceExpression(_context, _original, _typeReference, _dimension); + return result; +} +KOALA_INTEROP_4(UpdateETSNewArrayInstanceExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewArrayInstanceExpressionTypeReference(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSNewArrayInstanceExpressionTypeReference(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSNewArrayInstanceExpressionTypeReference, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewArrayInstanceExpressionTypeReferenceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSNewArrayInstanceExpressionTypeReferenceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSNewArrayInstanceExpressionTypeReferenceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewArrayInstanceExpressionDimension(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSNewArrayInstanceExpressionDimension(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSNewArrayInstanceExpressionDimension, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewArrayInstanceExpressionDimensionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSNewArrayInstanceExpressionDimensionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSNewArrayInstanceExpressionDimensionConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSNewArrayInstanceExpressionSetDimension(KNativePointer context, KNativePointer receiver, KNativePointer dimension) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _dimension = reinterpret_cast(dimension); + GetImpl()->ETSNewArrayInstanceExpressionSetDimension(_context, _receiver, _dimension); + return ; +} +KOALA_INTEROP_V3(ETSNewArrayInstanceExpressionSetDimension, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateAnnotationDeclaration(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateAnnotationDeclaration(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateAnnotationDeclaration, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateAnnotationDeclaration(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateAnnotationDeclaration(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateAnnotationDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateAnnotationDeclaration1(KNativePointer context, KNativePointer expr, KNativePointerArray properties, KUInt propertiesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + const auto _properties = reinterpret_cast(properties); + const auto _propertiesSequenceLength = static_cast(propertiesSequenceLength); + auto result = GetImpl()->CreateAnnotationDeclaration1(_context, _expr, _properties, _propertiesSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateAnnotationDeclaration1, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateAnnotationDeclaration1(KNativePointer context, KNativePointer original, KNativePointer expr, KNativePointerArray properties, KUInt propertiesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + const auto _properties = reinterpret_cast(properties); + const auto _propertiesSequenceLength = static_cast(propertiesSequenceLength); + auto result = GetImpl()->UpdateAnnotationDeclaration1(_context, _original, _expr, _properties, _propertiesSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateAnnotationDeclaration1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_AnnotationDeclarationInternalNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationDeclarationInternalNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(AnnotationDeclarationInternalNameConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AnnotationDeclarationSetInternalName(KNativePointer context, KNativePointer receiver, KStringPtr& internalName) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _internalName = getStringCopy(internalName); + GetImpl()->AnnotationDeclarationSetInternalName(_context, _receiver, _internalName); + return ; +} +KOALA_INTEROP_V3(AnnotationDeclarationSetInternalName, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_AnnotationDeclarationExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationDeclarationExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AnnotationDeclarationExprConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationDeclarationExpr(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationDeclarationExpr(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AnnotationDeclarationExpr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationDeclarationProperties(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AnnotationDeclarationProperties(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(AnnotationDeclarationProperties, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationDeclarationPropertiesConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AnnotationDeclarationPropertiesConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(AnnotationDeclarationPropertiesConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationDeclarationPropertiesPtrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AnnotationDeclarationPropertiesPtrConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(AnnotationDeclarationPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AnnotationDeclarationAddProperties(KNativePointer context, KNativePointer receiver, KNativePointerArray properties, KUInt propertiesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _properties = reinterpret_cast(properties); + const auto _propertiesSequenceLength = static_cast(propertiesSequenceLength); + GetImpl()->AnnotationDeclarationAddProperties(_context, _receiver, _properties, _propertiesSequenceLength); + return ; +} +KOALA_INTEROP_V4(AnnotationDeclarationAddProperties, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KBoolean impl_AnnotationDeclarationIsSourceRetentionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationDeclarationIsSourceRetentionConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AnnotationDeclarationIsSourceRetentionConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AnnotationDeclarationIsBytecodeRetentionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationDeclarationIsBytecodeRetentionConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AnnotationDeclarationIsBytecodeRetentionConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_AnnotationDeclarationIsRuntimeRetentionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationDeclarationIsRuntimeRetentionConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AnnotationDeclarationIsRuntimeRetentionConst, KBoolean, KNativePointer, KNativePointer); + +void impl_AnnotationDeclarationSetSourceRetention(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->AnnotationDeclarationSetSourceRetention(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(AnnotationDeclarationSetSourceRetention, KNativePointer, KNativePointer); + +void impl_AnnotationDeclarationSetBytecodeRetention(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->AnnotationDeclarationSetBytecodeRetention(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(AnnotationDeclarationSetBytecodeRetention, KNativePointer, KNativePointer); + +void impl_AnnotationDeclarationSetRuntimeRetention(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->AnnotationDeclarationSetRuntimeRetention(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(AnnotationDeclarationSetRuntimeRetention, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationDeclarationGetBaseNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationDeclarationGetBaseNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AnnotationDeclarationGetBaseNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationDeclarationAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AnnotationDeclarationAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(AnnotationDeclarationAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationDeclarationAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AnnotationDeclarationAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(AnnotationDeclarationAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AnnotationDeclarationSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->AnnotationDeclarationSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(AnnotationDeclarationSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateAnnotationUsageIr(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateAnnotationUsageIr(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateAnnotationUsageIr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateAnnotationUsageIr(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateAnnotationUsageIr(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateAnnotationUsageIr, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateAnnotationUsageIr1(KNativePointer context, KNativePointer expr, KNativePointerArray properties, KUInt propertiesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + const auto _properties = reinterpret_cast(properties); + const auto _propertiesSequenceLength = static_cast(propertiesSequenceLength); + auto result = GetImpl()->CreateAnnotationUsageIr1(_context, _expr, _properties, _propertiesSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateAnnotationUsageIr1, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateAnnotationUsageIr1(KNativePointer context, KNativePointer original, KNativePointer expr, KNativePointerArray properties, KUInt propertiesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + const auto _properties = reinterpret_cast(properties); + const auto _propertiesSequenceLength = static_cast(propertiesSequenceLength); + auto result = GetImpl()->UpdateAnnotationUsageIr1(_context, _original, _expr, _properties, _propertiesSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateAnnotationUsageIr1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_AnnotationUsageIrExpr(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationUsageIrExpr(_context, _receiver); + return result; +} +KOALA_INTEROP_2(AnnotationUsageIrExpr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationUsageIrProperties(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AnnotationUsageIrProperties(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(AnnotationUsageIrProperties, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationUsageIrPropertiesConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AnnotationUsageIrPropertiesConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(AnnotationUsageIrPropertiesConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotationUsageIrPropertiesPtrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->AnnotationUsageIrPropertiesPtrConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(AnnotationUsageIrPropertiesPtrConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AnnotationUsageIrAddProperty(KNativePointer context, KNativePointer receiver, KNativePointer property) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _property = reinterpret_cast(property); + GetImpl()->AnnotationUsageIrAddProperty(_context, _receiver, _property); + return ; +} +KOALA_INTEROP_V3(AnnotationUsageIrAddProperty, KNativePointer, KNativePointer, KNativePointer); + +void impl_AnnotationUsageIrSetProperties(KNativePointer context, KNativePointer receiver, KNativePointerArray properties, KUInt propertiesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _properties = reinterpret_cast(properties); + const auto _propertiesSequenceLength = static_cast(propertiesSequenceLength); + GetImpl()->AnnotationUsageIrSetProperties(_context, _receiver, _properties, _propertiesSequenceLength); + return ; +} +KOALA_INTEROP_V4(AnnotationUsageIrSetProperties, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_AnnotationUsageIrGetBaseNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotationUsageIrGetBaseNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AnnotationUsageIrGetBaseNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateEmptyStatement(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateEmptyStatement(_context); + return result; +} +KOALA_INTEROP_1(CreateEmptyStatement, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateEmptyStatement(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateEmptyStatement(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateEmptyStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSLaunchExpression(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateETSLaunchExpression(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateETSLaunchExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSLaunchExpression(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateETSLaunchExpression(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateETSLaunchExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ETSLaunchExpressionIsStaticCallConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSLaunchExpressionIsStaticCallConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSLaunchExpressionIsStaticCallConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_ETSLaunchExpressionCallConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSLaunchExpressionCallConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSLaunchExpressionCallConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateWhileStatement(KNativePointer context, KNativePointer test, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _test = reinterpret_cast(test); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->CreateWhileStatement(_context, _test, _body); + return result; +} +KOALA_INTEROP_3(CreateWhileStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateWhileStatement(KNativePointer context, KNativePointer original, KNativePointer test, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _test = reinterpret_cast(test); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->UpdateWhileStatement(_context, _original, _test, _body); + return result; +} +KOALA_INTEROP_4(UpdateWhileStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_WhileStatementTestConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->WhileStatementTestConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(WhileStatementTestConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_WhileStatementTest(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->WhileStatementTest(_context, _receiver); + return result; +} +KOALA_INTEROP_2(WhileStatementTest, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_WhileStatementBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->WhileStatementBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(WhileStatementBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_WhileStatementBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->WhileStatementBody(_context, _receiver); + return result; +} +KOALA_INTEROP_2(WhileStatementBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateFunctionSignature(KNativePointer context, KNativePointer typeParams, KNativePointerArray params, KUInt paramsSequenceLength, KNativePointer returnTypeAnnotation, KBoolean hasReceiver) +{ + const auto _context = reinterpret_cast(context); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _params = reinterpret_cast(params); + const auto _paramsSequenceLength = static_cast(paramsSequenceLength); + const auto _returnTypeAnnotation = reinterpret_cast(returnTypeAnnotation); + const auto _hasReceiver = static_cast(hasReceiver); + auto result = GetImpl()->CreateFunctionSignature(_context, _typeParams, _params, _paramsSequenceLength, _returnTypeAnnotation, _hasReceiver); + return result; +} +KOALA_INTEROP_6(CreateFunctionSignature, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KBoolean); + +KNativePointer impl_FunctionSignatureParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->FunctionSignatureParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(FunctionSignatureParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionSignatureParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->FunctionSignatureParams(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(FunctionSignatureParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionSignatureTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionSignatureTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionSignatureTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionSignatureTypeParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionSignatureTypeParamsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(FunctionSignatureTypeParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionSignatureReturnType(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionSignatureReturnType(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionSignatureReturnType, KNativePointer, KNativePointer, KNativePointer); + +void impl_FunctionSignatureSetReturnType(KNativePointer context, KNativePointer receiver, KNativePointer type) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _type = reinterpret_cast(type); + GetImpl()->FunctionSignatureSetReturnType(_context, _receiver, _type); + return ; +} +KOALA_INTEROP_V3(FunctionSignatureSetReturnType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionSignatureReturnTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionSignatureReturnTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(FunctionSignatureReturnTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_FunctionSignatureClone(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionSignatureClone(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionSignatureClone, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_FunctionSignatureHasReceiverConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->FunctionSignatureHasReceiverConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(FunctionSignatureHasReceiverConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateChainExpression(KNativePointer context, KNativePointer expression) +{ + const auto _context = reinterpret_cast(context); + const auto _expression = reinterpret_cast(expression); + auto result = GetImpl()->CreateChainExpression(_context, _expression); + return result; +} +KOALA_INTEROP_2(CreateChainExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateChainExpression(KNativePointer context, KNativePointer original, KNativePointer expression) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expression = reinterpret_cast(expression); + auto result = GetImpl()->UpdateChainExpression(_context, _original, _expression); + return result; +} +KOALA_INTEROP_3(UpdateChainExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ChainExpressionGetExpressionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ChainExpressionGetExpressionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ChainExpressionGetExpressionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ChainExpressionGetExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ChainExpressionGetExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ChainExpressionGetExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSIntersectionType(KNativePointer context, KNativePointerArray types, KUInt typesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _types = reinterpret_cast(types); + const auto _typesSequenceLength = static_cast(typesSequenceLength); + auto result = GetImpl()->CreateTSIntersectionType(_context, _types, _typesSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateTSIntersectionType, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateTSIntersectionType(KNativePointer context, KNativePointer original, KNativePointerArray types, KUInt typesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _types = reinterpret_cast(types); + const auto _typesSequenceLength = static_cast(typesSequenceLength); + auto result = GetImpl()->UpdateTSIntersectionType(_context, _original, _types, _typesSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateTSIntersectionType, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TSIntersectionTypeTypesConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSIntersectionTypeTypesConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSIntersectionTypeTypesConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateUpdateExpression(KNativePointer context, KNativePointer argument, KInt updateOperator, KBoolean isPrefix) +{ + const auto _context = reinterpret_cast(context); + const auto _argument = reinterpret_cast(argument); + const auto _updateOperator = static_cast(updateOperator); + const auto _isPrefix = static_cast(isPrefix); + auto result = GetImpl()->CreateUpdateExpression(_context, _argument, _updateOperator, _isPrefix); + return result; +} +KOALA_INTEROP_4(CreateUpdateExpression, KNativePointer, KNativePointer, KNativePointer, KInt, KBoolean); + +KNativePointer impl_UpdateUpdateExpression(KNativePointer context, KNativePointer original, KNativePointer argument, KInt updateOperator, KBoolean isPrefix) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _argument = reinterpret_cast(argument); + const auto _updateOperator = static_cast(updateOperator); + const auto _isPrefix = static_cast(isPrefix); + auto result = GetImpl()->UpdateUpdateExpression(_context, _original, _argument, _updateOperator, _isPrefix); + return result; +} +KOALA_INTEROP_5(UpdateUpdateExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KBoolean); + +KInt impl_UpdateExpressionOperatorTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->UpdateExpressionOperatorTypeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(UpdateExpressionOperatorTypeConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateExpressionArgument(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->UpdateExpressionArgument(_context, _receiver); + return result; +} +KOALA_INTEROP_2(UpdateExpressionArgument, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateExpressionArgumentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->UpdateExpressionArgumentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(UpdateExpressionArgumentConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_UpdateExpressionIsPrefixConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->UpdateExpressionIsPrefixConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(UpdateExpressionIsPrefixConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateBlockExpression(KNativePointer context, KNativePointerArray statements, KUInt statementsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _statements = reinterpret_cast(statements); + const auto _statementsSequenceLength = static_cast(statementsSequenceLength); + auto result = GetImpl()->CreateBlockExpression(_context, _statements, _statementsSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateBlockExpression, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateBlockExpression(KNativePointer context, KNativePointer original, KNativePointerArray statements, KUInt statementsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _statements = reinterpret_cast(statements); + const auto _statementsSequenceLength = static_cast(statementsSequenceLength); + auto result = GetImpl()->UpdateBlockExpression(_context, _original, _statements, _statementsSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateBlockExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_BlockExpressionStatementsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->BlockExpressionStatementsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(BlockExpressionStatementsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BlockExpressionStatements(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->BlockExpressionStatements(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(BlockExpressionStatements, KNativePointer, KNativePointer, KNativePointer); + +void impl_BlockExpressionAddStatements(KNativePointer context, KNativePointer receiver, KNativePointerArray statements, KUInt statementsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _statements = reinterpret_cast(statements); + const auto _statementsSequenceLength = static_cast(statementsSequenceLength); + GetImpl()->BlockExpressionAddStatements(_context, _receiver, _statements, _statementsSequenceLength); + return ; +} +KOALA_INTEROP_V4(BlockExpressionAddStatements, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +void impl_BlockExpressionAddStatement(KNativePointer context, KNativePointer receiver, KNativePointer statement) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _statement = reinterpret_cast(statement); + GetImpl()->BlockExpressionAddStatement(_context, _receiver, _statement); + return ; +} +KOALA_INTEROP_V3(BlockExpressionAddStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeLiteral(KNativePointer context, KNativePointerArray members, KUInt membersSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _members = reinterpret_cast(members); + const auto _membersSequenceLength = static_cast(membersSequenceLength); + auto result = GetImpl()->CreateTSTypeLiteral(_context, _members, _membersSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateTSTypeLiteral, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateTSTypeLiteral(KNativePointer context, KNativePointer original, KNativePointerArray members, KUInt membersSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _members = reinterpret_cast(members); + const auto _membersSequenceLength = static_cast(membersSequenceLength); + auto result = GetImpl()->UpdateTSTypeLiteral(_context, _original, _members, _membersSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateTSTypeLiteral, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TSTypeLiteralMembersConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTypeLiteralMembersConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTypeLiteralMembersConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeParameter(KNativePointer context, KNativePointer name, KNativePointer constraint, KNativePointer defaultType) +{ + const auto _context = reinterpret_cast(context); + const auto _name = reinterpret_cast(name); + const auto _constraint = reinterpret_cast(constraint); + const auto _defaultType = reinterpret_cast(defaultType); + auto result = GetImpl()->CreateTSTypeParameter(_context, _name, _constraint, _defaultType); + return result; +} +KOALA_INTEROP_4(CreateTSTypeParameter, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSTypeParameter(KNativePointer context, KNativePointer original, KNativePointer name, KNativePointer constraint, KNativePointer defaultType) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = reinterpret_cast(name); + const auto _constraint = reinterpret_cast(constraint); + const auto _defaultType = reinterpret_cast(defaultType); + auto result = GetImpl()->UpdateTSTypeParameter(_context, _original, _name, _constraint, _defaultType); + return result; +} +KOALA_INTEROP_5(UpdateTSTypeParameter, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypeParameter1(KNativePointer context, KNativePointer name, KNativePointer constraint, KNativePointer defaultType, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _name = reinterpret_cast(name); + const auto _constraint = reinterpret_cast(constraint); + const auto _defaultType = reinterpret_cast(defaultType); + const auto _flags = static_cast(flags); + auto result = GetImpl()->CreateTSTypeParameter1(_context, _name, _constraint, _defaultType, _flags); + return result; +} +KOALA_INTEROP_5(CreateTSTypeParameter1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateTSTypeParameter1(KNativePointer context, KNativePointer original, KNativePointer name, KNativePointer constraint, KNativePointer defaultType, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = reinterpret_cast(name); + const auto _constraint = reinterpret_cast(constraint); + const auto _defaultType = reinterpret_cast(defaultType); + const auto _flags = static_cast(flags); + auto result = GetImpl()->UpdateTSTypeParameter1(_context, _original, _name, _constraint, _defaultType, _flags); + return result; +} +KOALA_INTEROP_6(UpdateTSTypeParameter1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_TSTypeParameterNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeParameterNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeParameterNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeParameterName(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeParameterName(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSTypeParameterName, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeParameterConstraint(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeParameterConstraint(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSTypeParameterConstraint, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeParameterConstraintConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeParameterConstraintConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeParameterConstraintConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSTypeParameterSetConstraint(KNativePointer context, KNativePointer receiver, KNativePointer constraint) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _constraint = reinterpret_cast(constraint); + GetImpl()->TSTypeParameterSetConstraint(_context, _receiver, _constraint); + return ; +} +KOALA_INTEROP_V3(TSTypeParameterSetConstraint, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeParameterDefaultTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeParameterDefaultTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypeParameterDefaultTypeConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSTypeParameterSetDefaultType(KNativePointer context, KNativePointer receiver, KNativePointer defaultType) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _defaultType = reinterpret_cast(defaultType); + GetImpl()->TSTypeParameterSetDefaultType(_context, _receiver, _defaultType); + return ; +} +KOALA_INTEROP_V3(TSTypeParameterSetDefaultType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeParameterAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTypeParameterAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTypeParameterAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypeParameterAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTypeParameterAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTypeParameterAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSTypeParameterSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->TSTypeParameterSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(TSTypeParameterSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateTSBooleanKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSBooleanKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSBooleanKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSBooleanKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSBooleanKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSBooleanKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateSpreadElement(KNativePointer context, KInt nodeType, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _nodeType = static_cast(nodeType); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->CreateSpreadElement(_context, _nodeType, _argument); + return result; +} +KOALA_INTEROP_3(CreateSpreadElement, KNativePointer, KNativePointer, KInt, KNativePointer); + +KNativePointer impl_UpdateSpreadElement(KNativePointer context, KNativePointer original, KInt nodeType, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _nodeType = static_cast(nodeType); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->UpdateSpreadElement(_context, _original, _nodeType, _argument); + return result; +} +KOALA_INTEROP_4(UpdateSpreadElement, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointer); + +KNativePointer impl_SpreadElementArgumentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SpreadElementArgumentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(SpreadElementArgumentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_SpreadElementArgument(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SpreadElementArgument(_context, _receiver); + return result; +} +KOALA_INTEROP_2(SpreadElementArgument, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_SpreadElementIsOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SpreadElementIsOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(SpreadElementIsOptionalConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_SpreadElementDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->SpreadElementDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(SpreadElementDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_SpreadElementSetOptional(KNativePointer context, KNativePointer receiver, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _optional_arg = static_cast(optional_arg); + GetImpl()->SpreadElementSetOptional(_context, _receiver, _optional_arg); + return ; +} +KOALA_INTEROP_V3(SpreadElementSetOptional, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_SpreadElementValidateExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SpreadElementValidateExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(SpreadElementValidateExpression, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_SpreadElementConvertibleToRest(KNativePointer context, KNativePointer receiver, KBoolean isDeclaration, KBoolean allowPattern) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _isDeclaration = static_cast(isDeclaration); + const auto _allowPattern = static_cast(allowPattern); + auto result = GetImpl()->SpreadElementConvertibleToRest(_context, _receiver, _isDeclaration, _allowPattern); + return result; +} +KOALA_INTEROP_4(SpreadElementConvertibleToRest, KBoolean, KNativePointer, KNativePointer, KBoolean, KBoolean); + +KNativePointer impl_SpreadElementTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SpreadElementTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(SpreadElementTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_SpreadElementSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->SpreadElementSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(SpreadElementSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSTypePredicate(KNativePointer context, KNativePointer parameterName, KNativePointer typeAnnotation, KBoolean asserts) +{ + const auto _context = reinterpret_cast(context); + const auto _parameterName = reinterpret_cast(parameterName); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _asserts = static_cast(asserts); + auto result = GetImpl()->CreateTSTypePredicate(_context, _parameterName, _typeAnnotation, _asserts); + return result; +} +KOALA_INTEROP_4(CreateTSTypePredicate, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateTSTypePredicate(KNativePointer context, KNativePointer original, KNativePointer parameterName, KNativePointer typeAnnotation, KBoolean asserts) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _parameterName = reinterpret_cast(parameterName); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _asserts = static_cast(asserts); + auto result = GetImpl()->UpdateTSTypePredicate(_context, _original, _parameterName, _typeAnnotation, _asserts); + return result; +} +KOALA_INTEROP_5(UpdateTSTypePredicate, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSTypePredicateParameterNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypePredicateParameterNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypePredicateParameterNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSTypePredicateTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypePredicateTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSTypePredicateTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSTypePredicateAssertsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypePredicateAssertsConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSTypePredicateAssertsConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateImportNamespaceSpecifier(KNativePointer context, KNativePointer local) +{ + const auto _context = reinterpret_cast(context); + const auto _local = reinterpret_cast(local); + auto result = GetImpl()->CreateImportNamespaceSpecifier(_context, _local); + return result; +} +KOALA_INTEROP_2(CreateImportNamespaceSpecifier, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateImportNamespaceSpecifier(KNativePointer context, KNativePointer original, KNativePointer local) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _local = reinterpret_cast(local); + auto result = GetImpl()->UpdateImportNamespaceSpecifier(_context, _original, _local); + return result; +} +KOALA_INTEROP_3(UpdateImportNamespaceSpecifier, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportNamespaceSpecifierLocal(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportNamespaceSpecifierLocal(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ImportNamespaceSpecifierLocal, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportNamespaceSpecifierLocalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportNamespaceSpecifierLocalConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ImportNamespaceSpecifierLocalConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateExportNamedDeclaration(KNativePointer context, KNativePointer source, KNativePointerArray specifiers, KUInt specifiersSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _source = reinterpret_cast(source); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + auto result = GetImpl()->CreateExportNamedDeclaration(_context, _source, _specifiers, _specifiersSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateExportNamedDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateExportNamedDeclaration(KNativePointer context, KNativePointer original, KNativePointer source, KNativePointerArray specifiers, KUInt specifiersSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _source = reinterpret_cast(source); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + auto result = GetImpl()->UpdateExportNamedDeclaration(_context, _original, _source, _specifiers, _specifiersSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateExportNamedDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateExportNamedDeclaration1(KNativePointer context, KNativePointer decl, KNativePointerArray specifiers, KUInt specifiersSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _decl = reinterpret_cast(decl); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + auto result = GetImpl()->CreateExportNamedDeclaration1(_context, _decl, _specifiers, _specifiersSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateExportNamedDeclaration1, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateExportNamedDeclaration1(KNativePointer context, KNativePointer original, KNativePointer decl, KNativePointerArray specifiers, KUInt specifiersSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _decl = reinterpret_cast(decl); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + auto result = GetImpl()->UpdateExportNamedDeclaration1(_context, _original, _decl, _specifiers, _specifiersSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateExportNamedDeclaration1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateExportNamedDeclaration2(KNativePointer context, KNativePointer decl) +{ + const auto _context = reinterpret_cast(context); + const auto _decl = reinterpret_cast(decl); + auto result = GetImpl()->CreateExportNamedDeclaration2(_context, _decl); + return result; +} +KOALA_INTEROP_2(CreateExportNamedDeclaration2, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateExportNamedDeclaration2(KNativePointer context, KNativePointer original, KNativePointer decl) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _decl = reinterpret_cast(decl); + auto result = GetImpl()->UpdateExportNamedDeclaration2(_context, _original, _decl); + return result; +} +KOALA_INTEROP_3(UpdateExportNamedDeclaration2, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExportNamedDeclarationDeclConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportNamedDeclarationDeclConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExportNamedDeclarationDeclConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExportNamedDeclarationSourceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExportNamedDeclarationSourceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExportNamedDeclarationSourceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExportNamedDeclarationSpecifiersConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ExportNamedDeclarationSpecifiersConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ExportNamedDeclarationSpecifiersConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSParameterExpression(KNativePointer context, KNativePointer identOrSpread, KBoolean isOptional) +{ + const auto _context = reinterpret_cast(context); + const auto _identOrSpread = reinterpret_cast(identOrSpread); + const auto _isOptional = static_cast(isOptional); + auto result = GetImpl()->CreateETSParameterExpression(_context, _identOrSpread, _isOptional); + return result; +} +KOALA_INTEROP_3(CreateETSParameterExpression, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateETSParameterExpression(KNativePointer context, KNativePointer original, KNativePointer identOrSpread, KBoolean isOptional) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _identOrSpread = reinterpret_cast(identOrSpread); + const auto _isOptional = static_cast(isOptional); + auto result = GetImpl()->UpdateETSParameterExpression(_context, _original, _identOrSpread, _isOptional); + return result; +} +KOALA_INTEROP_4(UpdateETSParameterExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_CreateETSParameterExpression1(KNativePointer context, KNativePointer identOrSpread, KNativePointer initializer) +{ + const auto _context = reinterpret_cast(context); + const auto _identOrSpread = reinterpret_cast(identOrSpread); + const auto _initializer = reinterpret_cast(initializer); + auto result = GetImpl()->CreateETSParameterExpression1(_context, _identOrSpread, _initializer); + return result; +} +KOALA_INTEROP_3(CreateETSParameterExpression1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSParameterExpression1(KNativePointer context, KNativePointer original, KNativePointer identOrSpread, KNativePointer initializer) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _identOrSpread = reinterpret_cast(identOrSpread); + const auto _initializer = reinterpret_cast(initializer); + auto result = GetImpl()->UpdateETSParameterExpression1(_context, _original, _identOrSpread, _initializer); + return result; +} +KOALA_INTEROP_4(UpdateETSParameterExpression1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ETSParameterExpressionNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionIdentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionIdentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSParameterExpressionIdentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionIdent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionIdent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSParameterExpressionIdent, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSParameterExpressionSetIdent(KNativePointer context, KNativePointer receiver, KNativePointer ident) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _ident = reinterpret_cast(ident); + GetImpl()->ETSParameterExpressionSetIdent(_context, _receiver, _ident); + return ; +} +KOALA_INTEROP_V3(ETSParameterExpressionSetIdent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionRestParameterConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionRestParameterConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSParameterExpressionRestParameterConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionRestParameter(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionRestParameter(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSParameterExpressionRestParameter, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionInitializerConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionInitializerConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSParameterExpressionInitializerConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionInitializer(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionInitializer(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSParameterExpressionInitializer, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSParameterExpressionSetLexerSaved(KNativePointer context, KNativePointer receiver, KStringPtr& s) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _s = getStringCopy(s); + GetImpl()->ETSParameterExpressionSetLexerSaved(_context, _receiver, _s); + return ; +} +KOALA_INTEROP_V3(ETSParameterExpressionSetLexerSaved, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_ETSParameterExpressionLexerSavedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionLexerSavedConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ETSParameterExpressionLexerSavedConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSParameterExpressionTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionTypeAnnotation(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionTypeAnnotation(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSParameterExpressionTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSParameterExpressionSetTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeNode) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeNode = reinterpret_cast(typeNode); + GetImpl()->ETSParameterExpressionSetTypeAnnotation(_context, _receiver, _typeNode); + return ; +} +KOALA_INTEROP_V3(ETSParameterExpressionSetTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ETSParameterExpressionIsOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionIsOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSParameterExpressionIsOptionalConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ETSParameterExpressionSetOptional(KNativePointer context, KNativePointer receiver, KBoolean value) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _value = static_cast(value); + GetImpl()->ETSParameterExpressionSetOptional(_context, _receiver, _value); + return ; +} +KOALA_INTEROP_V3(ETSParameterExpressionSetOptional, KNativePointer, KNativePointer, KBoolean); + +void impl_ETSParameterExpressionSetInitializer(KNativePointer context, KNativePointer receiver, KNativePointer initExpr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _initExpr = reinterpret_cast(initExpr); + GetImpl()->ETSParameterExpressionSetInitializer(_context, _receiver, _initExpr); + return ; +} +KOALA_INTEROP_V3(ETSParameterExpressionSetInitializer, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ETSParameterExpressionIsRestParameterConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionIsRestParameterConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSParameterExpressionIsRestParameterConst, KBoolean, KNativePointer, KNativePointer); + +KUInt impl_ETSParameterExpressionGetRequiredParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSParameterExpressionGetRequiredParamsConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSParameterExpressionGetRequiredParamsConst, KUInt, KNativePointer, KNativePointer); + +void impl_ETSParameterExpressionSetRequiredParams(KNativePointer context, KNativePointer receiver, KUInt value) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _value = static_cast(value); + GetImpl()->ETSParameterExpressionSetRequiredParams(_context, _receiver, _value); + return ; +} +KOALA_INTEROP_V3(ETSParameterExpressionSetRequiredParams, KNativePointer, KNativePointer, KUInt); + +KNativePointer impl_ETSParameterExpressionAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSParameterExpressionAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSParameterExpressionAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSParameterExpressionAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSParameterExpressionAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSParameterExpressionAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSParameterExpressionSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->ETSParameterExpressionSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(ETSParameterExpressionSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateTSTypeParameterInstantiation(KNativePointer context, KNativePointerArray params, KUInt paramsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _params = reinterpret_cast(params); + const auto _paramsSequenceLength = static_cast(paramsSequenceLength); + auto result = GetImpl()->CreateTSTypeParameterInstantiation(_context, _params, _paramsSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateTSTypeParameterInstantiation, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateTSTypeParameterInstantiation(KNativePointer context, KNativePointer original, KNativePointerArray params, KUInt paramsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _params = reinterpret_cast(params); + const auto _paramsSequenceLength = static_cast(paramsSequenceLength); + auto result = GetImpl()->UpdateTSTypeParameterInstantiation(_context, _original, _params, _paramsSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateTSTypeParameterInstantiation, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TSTypeParameterInstantiationParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTypeParameterInstantiationParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTypeParameterInstantiationParamsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateNullLiteral(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateNullLiteral(_context); + return result; +} +KOALA_INTEROP_1(CreateNullLiteral, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateNullLiteral(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateNullLiteral(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateNullLiteral, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSInferType(KNativePointer context, KNativePointer typeParam) +{ + const auto _context = reinterpret_cast(context); + const auto _typeParam = reinterpret_cast(typeParam); + auto result = GetImpl()->CreateTSInferType(_context, _typeParam); + return result; +} +KOALA_INTEROP_2(CreateTSInferType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSInferType(KNativePointer context, KNativePointer original, KNativePointer typeParam) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeParam = reinterpret_cast(typeParam); + auto result = GetImpl()->UpdateTSInferType(_context, _original, _typeParam); + return result; +} +KOALA_INTEROP_3(UpdateTSInferType, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInferTypeTypeParamConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInferTypeTypeParamConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSInferTypeTypeParamConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateSwitchCaseStatement(KNativePointer context, KNativePointer test, KNativePointerArray consequent, KUInt consequentSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _test = reinterpret_cast(test); + const auto _consequent = reinterpret_cast(consequent); + const auto _consequentSequenceLength = static_cast(consequentSequenceLength); + auto result = GetImpl()->CreateSwitchCaseStatement(_context, _test, _consequent, _consequentSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateSwitchCaseStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateSwitchCaseStatement(KNativePointer context, KNativePointer original, KNativePointer test, KNativePointerArray consequent, KUInt consequentSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _test = reinterpret_cast(test); + const auto _consequent = reinterpret_cast(consequent); + const auto _consequentSequenceLength = static_cast(consequentSequenceLength); + auto result = GetImpl()->UpdateSwitchCaseStatement(_context, _original, _test, _consequent, _consequentSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateSwitchCaseStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_SwitchCaseStatementTest(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SwitchCaseStatementTest(_context, _receiver); + return result; +} +KOALA_INTEROP_2(SwitchCaseStatementTest, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_SwitchCaseStatementTestConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SwitchCaseStatementTestConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(SwitchCaseStatementTestConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_SwitchCaseStatementConsequentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->SwitchCaseStatementConsequentConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(SwitchCaseStatementConsequentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateYieldExpression(KNativePointer context, KNativePointer argument, KBoolean isDelegate) +{ + const auto _context = reinterpret_cast(context); + const auto _argument = reinterpret_cast(argument); + const auto _isDelegate = static_cast(isDelegate); + auto result = GetImpl()->CreateYieldExpression(_context, _argument, _isDelegate); + return result; +} +KOALA_INTEROP_3(CreateYieldExpression, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateYieldExpression(KNativePointer context, KNativePointer original, KNativePointer argument, KBoolean isDelegate) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _argument = reinterpret_cast(argument); + const auto _isDelegate = static_cast(isDelegate); + auto result = GetImpl()->UpdateYieldExpression(_context, _original, _argument, _isDelegate); + return result; +} +KOALA_INTEROP_4(UpdateYieldExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KBoolean impl_YieldExpressionHasDelegateConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->YieldExpressionHasDelegateConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(YieldExpressionHasDelegateConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_YieldExpressionArgumentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->YieldExpressionArgumentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(YieldExpressionArgumentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSImportEqualsDeclaration(KNativePointer context, KNativePointer id, KNativePointer moduleReference, KBoolean isExport) +{ + const auto _context = reinterpret_cast(context); + const auto _id = reinterpret_cast(id); + const auto _moduleReference = reinterpret_cast(moduleReference); + const auto _isExport = static_cast(isExport); + auto result = GetImpl()->CreateTSImportEqualsDeclaration(_context, _id, _moduleReference, _isExport); + return result; +} +KOALA_INTEROP_4(CreateTSImportEqualsDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateTSImportEqualsDeclaration(KNativePointer context, KNativePointer original, KNativePointer id, KNativePointer moduleReference, KBoolean isExport) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _id = reinterpret_cast(id); + const auto _moduleReference = reinterpret_cast(moduleReference); + const auto _isExport = static_cast(isExport); + auto result = GetImpl()->UpdateTSImportEqualsDeclaration(_context, _original, _id, _moduleReference, _isExport); + return result; +} +KOALA_INTEROP_5(UpdateTSImportEqualsDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSImportEqualsDeclarationIdConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSImportEqualsDeclarationIdConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSImportEqualsDeclarationIdConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSImportEqualsDeclarationModuleReferenceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSImportEqualsDeclarationModuleReferenceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSImportEqualsDeclarationModuleReferenceConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSImportEqualsDeclarationIsExportConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSImportEqualsDeclarationIsExportConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSImportEqualsDeclarationIsExportConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateBooleanLiteral(KNativePointer context, KBoolean value) +{ + const auto _context = reinterpret_cast(context); + const auto _value = static_cast(value); + auto result = GetImpl()->CreateBooleanLiteral(_context, _value); + return result; +} +KOALA_INTEROP_2(CreateBooleanLiteral, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateBooleanLiteral(KNativePointer context, KNativePointer original, KBoolean value) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _value = static_cast(value); + auto result = GetImpl()->UpdateBooleanLiteral(_context, _original, _value); + return result; +} +KOALA_INTEROP_3(UpdateBooleanLiteral, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KBoolean impl_BooleanLiteralValueConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BooleanLiteralValueConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BooleanLiteralValueConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSNumberKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSNumberKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSNumberKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSNumberKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSNumberKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSNumberKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateClassStaticBlock(KNativePointer context, KNativePointer value) +{ + const auto _context = reinterpret_cast(context); + const auto _value = reinterpret_cast(value); + auto result = GetImpl()->CreateClassStaticBlock(_context, _value); + return result; +} +KOALA_INTEROP_2(CreateClassStaticBlock, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateClassStaticBlock(KNativePointer context, KNativePointer original, KNativePointer value) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _value = reinterpret_cast(value); + auto result = GetImpl()->UpdateClassStaticBlock(_context, _original, _value); + return result; +} +KOALA_INTEROP_3(UpdateClassStaticBlock, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassStaticBlockFunction(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassStaticBlockFunction(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassStaticBlockFunction, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassStaticBlockFunctionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassStaticBlockFunctionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassStaticBlockFunctionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassStaticBlockNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassStaticBlockNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ClassStaticBlockNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSNonNullExpression(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateTSNonNullExpression(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateTSNonNullExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSNonNullExpression(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateTSNonNullExpression(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateTSNonNullExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSNonNullExpressionExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSNonNullExpressionExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSNonNullExpressionExprConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSNonNullExpressionExpr(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSNonNullExpressionExpr(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSNonNullExpressionExpr, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSNonNullExpressionSetExpr(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->TSNonNullExpressionSetExpr(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(TSNonNullExpressionSetExpr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreatePrefixAssertionExpression(KNativePointer context, KNativePointer expr, KNativePointer type) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + const auto _type = reinterpret_cast(type); + auto result = GetImpl()->CreatePrefixAssertionExpression(_context, _expr, _type); + return result; +} +KOALA_INTEROP_3(CreatePrefixAssertionExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdatePrefixAssertionExpression(KNativePointer context, KNativePointer original, KNativePointer expr, KNativePointer type) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + const auto _type = reinterpret_cast(type); + auto result = GetImpl()->UpdatePrefixAssertionExpression(_context, _original, _expr, _type); + return result; +} +KOALA_INTEROP_4(UpdatePrefixAssertionExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_PrefixAssertionExpressionExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PrefixAssertionExpressionExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(PrefixAssertionExpressionExprConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_PrefixAssertionExpressionTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->PrefixAssertionExpressionTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(PrefixAssertionExpressionTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateClassExpression(KNativePointer context, KNativePointer def) +{ + const auto _context = reinterpret_cast(context); + const auto _def = reinterpret_cast(def); + auto result = GetImpl()->CreateClassExpression(_context, _def); + return result; +} +KOALA_INTEROP_2(CreateClassExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateClassExpression(KNativePointer context, KNativePointer original, KNativePointer def) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _def = reinterpret_cast(def); + auto result = GetImpl()->UpdateClassExpression(_context, _original, _def); + return result; +} +KOALA_INTEROP_3(UpdateClassExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassExpressionDefinitionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassExpressionDefinitionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassExpressionDefinitionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateForOfStatement(KNativePointer context, KNativePointer left, KNativePointer right, KNativePointer body, KBoolean isAwait) +{ + const auto _context = reinterpret_cast(context); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _body = reinterpret_cast(body); + const auto _isAwait = static_cast(isAwait); + auto result = GetImpl()->CreateForOfStatement(_context, _left, _right, _body, _isAwait); + return result; +} +KOALA_INTEROP_5(CreateForOfStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateForOfStatement(KNativePointer context, KNativePointer original, KNativePointer left, KNativePointer right, KNativePointer body, KBoolean isAwait) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + const auto _body = reinterpret_cast(body); + const auto _isAwait = static_cast(isAwait); + auto result = GetImpl()->UpdateForOfStatement(_context, _original, _left, _right, _body, _isAwait); + return result; +} +KOALA_INTEROP_6(UpdateForOfStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_ForOfStatementLeft(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForOfStatementLeft(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForOfStatementLeft, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForOfStatementLeftConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForOfStatementLeftConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForOfStatementLeftConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForOfStatementRight(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForOfStatementRight(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForOfStatementRight, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForOfStatementRightConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForOfStatementRightConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForOfStatementRightConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForOfStatementBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForOfStatementBody(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForOfStatementBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForOfStatementBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForOfStatementBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForOfStatementBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ForOfStatementIsAwaitConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForOfStatementIsAwaitConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForOfStatementIsAwaitConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTemplateLiteral(KNativePointer context, KNativePointerArray quasis, KUInt quasisSequenceLength, KNativePointerArray expressions, KUInt expressionsSequenceLength, KStringPtr& multilineString) +{ + const auto _context = reinterpret_cast(context); + const auto _quasis = reinterpret_cast(quasis); + const auto _quasisSequenceLength = static_cast(quasisSequenceLength); + const auto _expressions = reinterpret_cast(expressions); + const auto _expressionsSequenceLength = static_cast(expressionsSequenceLength); + const auto _multilineString = getStringCopy(multilineString); + auto result = GetImpl()->CreateTemplateLiteral(_context, _quasis, _quasisSequenceLength, _expressions, _expressionsSequenceLength, _multilineString); + return result; +} +KOALA_INTEROP_6(CreateTemplateLiteral, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointerArray, KUInt, KStringPtr); + +KNativePointer impl_UpdateTemplateLiteral(KNativePointer context, KNativePointer original, KNativePointerArray quasis, KUInt quasisSequenceLength, KNativePointerArray expressions, KUInt expressionsSequenceLength, KStringPtr& multilineString) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _quasis = reinterpret_cast(quasis); + const auto _quasisSequenceLength = static_cast(quasisSequenceLength); + const auto _expressions = reinterpret_cast(expressions); + const auto _expressionsSequenceLength = static_cast(expressionsSequenceLength); + const auto _multilineString = getStringCopy(multilineString); + auto result = GetImpl()->UpdateTemplateLiteral(_context, _original, _quasis, _quasisSequenceLength, _expressions, _expressionsSequenceLength, _multilineString); + return result; +} +KOALA_INTEROP_7(UpdateTemplateLiteral, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointerArray, KUInt, KStringPtr); + +KNativePointer impl_TemplateLiteralQuasisConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TemplateLiteralQuasisConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TemplateLiteralQuasisConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TemplateLiteralExpressionsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TemplateLiteralExpressionsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TemplateLiteralExpressionsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TemplateLiteralGetMultilineStringConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TemplateLiteralGetMultilineStringConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(TemplateLiteralGetMultilineStringConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSUnionType(KNativePointer context, KNativePointerArray types, KUInt typesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _types = reinterpret_cast(types); + const auto _typesSequenceLength = static_cast(typesSequenceLength); + auto result = GetImpl()->CreateTSUnionType(_context, _types, _typesSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateTSUnionType, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateTSUnionType(KNativePointer context, KNativePointer original, KNativePointerArray types, KUInt typesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _types = reinterpret_cast(types); + const auto _typesSequenceLength = static_cast(typesSequenceLength); + auto result = GetImpl()->UpdateTSUnionType(_context, _original, _types, _typesSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateTSUnionType, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_TSUnionTypeTypesConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSUnionTypeTypesConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSUnionTypeTypesConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSUnknownKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSUnknownKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSUnknownKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSUnknownKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSUnknownKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSUnknownKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateIdentifier(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateIdentifier(_context); + return result; +} +KOALA_INTEROP_1(CreateIdentifier, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateIdentifier(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateIdentifier(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateIdentifier, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateIdentifier1(KNativePointer context, KStringPtr& name) +{ + const auto _context = reinterpret_cast(context); + const auto _name = getStringCopy(name); + auto result = GetImpl()->CreateIdentifier1(_context, _name); + return result; +} +KOALA_INTEROP_2(CreateIdentifier1, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_UpdateIdentifier1(KNativePointer context, KNativePointer original, KStringPtr& name) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = getStringCopy(name); + auto result = GetImpl()->UpdateIdentifier1(_context, _original, _name); + return result; +} +KOALA_INTEROP_3(UpdateIdentifier1, KNativePointer, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_CreateIdentifier2(KNativePointer context, KStringPtr& name, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _name = getStringCopy(name); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + auto result = GetImpl()->CreateIdentifier2(_context, _name, _typeAnnotation); + return result; +} +KOALA_INTEROP_3(CreateIdentifier2, KNativePointer, KNativePointer, KStringPtr, KNativePointer); + +KNativePointer impl_UpdateIdentifier2(KNativePointer context, KNativePointer original, KStringPtr& name, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = getStringCopy(name); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + auto result = GetImpl()->UpdateIdentifier2(_context, _original, _name, _typeAnnotation); + return result; +} +KOALA_INTEROP_4(UpdateIdentifier2, KNativePointer, KNativePointer, KNativePointer, KStringPtr, KNativePointer); + +KNativePointer impl_IdentifierNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(IdentifierNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IdentifierName(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierName(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(IdentifierName, KNativePointer, KNativePointer, KNativePointer); + +void impl_IdentifierSetName(KNativePointer context, KNativePointer receiver, KStringPtr& newName) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _newName = getStringCopy(newName); + GetImpl()->IdentifierSetName(_context, _receiver, _newName); + return ; +} +KOALA_INTEROP_V3(IdentifierSetName, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_IdentifierDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->IdentifierDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(IdentifierDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsErrorPlaceHolderConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsErrorPlaceHolderConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsErrorPlaceHolderConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsOptionalConst, KBoolean, KNativePointer, KNativePointer); + +void impl_IdentifierSetOptional(KNativePointer context, KNativePointer receiver, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _optional_arg = static_cast(optional_arg); + GetImpl()->IdentifierSetOptional(_context, _receiver, _optional_arg); + return ; +} +KOALA_INTEROP_V3(IdentifierSetOptional, KNativePointer, KNativePointer, KBoolean); + +KBoolean impl_IdentifierIsReferenceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsReferenceConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsReferenceConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsTdzConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsTdzConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsTdzConst, KBoolean, KNativePointer, KNativePointer); + +void impl_IdentifierSetTdz(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->IdentifierSetTdz(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(IdentifierSetTdz, KNativePointer, KNativePointer); + +void impl_IdentifierSetAccessor(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->IdentifierSetAccessor(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(IdentifierSetAccessor, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsAccessorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsAccessorConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsAccessorConst, KBoolean, KNativePointer, KNativePointer); + +void impl_IdentifierSetMutator(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->IdentifierSetMutator(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(IdentifierSetMutator, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsMutatorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsMutatorConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsMutatorConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsReceiverConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsReceiverConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsReceiverConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsPrivateIdentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsPrivateIdentConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsPrivateIdentConst, KBoolean, KNativePointer, KNativePointer); + +void impl_IdentifierSetPrivate(KNativePointer context, KNativePointer receiver, KBoolean isPrivate) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _isPrivate = static_cast(isPrivate); + GetImpl()->IdentifierSetPrivate(_context, _receiver, _isPrivate); + return ; +} +KOALA_INTEROP_V3(IdentifierSetPrivate, KNativePointer, KNativePointer, KBoolean); + +KBoolean impl_IdentifierIsIgnoreBoxConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsIgnoreBoxConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsIgnoreBoxConst, KBoolean, KNativePointer, KNativePointer); + +void impl_IdentifierSetIgnoreBox(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->IdentifierSetIgnoreBox(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(IdentifierSetIgnoreBox, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsAnnotationDeclConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsAnnotationDeclConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsAnnotationDeclConst, KBoolean, KNativePointer, KNativePointer); + +void impl_IdentifierSetAnnotationDecl(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->IdentifierSetAnnotationDecl(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(IdentifierSetAnnotationDecl, KNativePointer, KNativePointer); + +KBoolean impl_IdentifierIsAnnotationUsageConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierIsAnnotationUsageConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierIsAnnotationUsageConst, KBoolean, KNativePointer, KNativePointer); + +void impl_IdentifierSetAnnotationUsage(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->IdentifierSetAnnotationUsage(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(IdentifierSetAnnotationUsage, KNativePointer, KNativePointer); + +KNativePointer impl_IdentifierCloneReference(KNativePointer context, KNativePointer receiver, KNativePointer parent) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _parent = reinterpret_cast(parent); + auto result = GetImpl()->IdentifierCloneReference(_context, _receiver, _parent); + return result; +} +KOALA_INTEROP_3(IdentifierCloneReference, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IdentifierValidateExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierValidateExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(IdentifierValidateExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_IdentifierTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->IdentifierTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(IdentifierTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_IdentifierSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->IdentifierSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(IdentifierSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateOpaqueTypeNode1(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateOpaqueTypeNode1(_context); + return result; +} +KOALA_INTEROP_1(CreateOpaqueTypeNode1, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateOpaqueTypeNode1(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateOpaqueTypeNode1(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateOpaqueTypeNode1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateBlockStatement(KNativePointer context, KNativePointerArray statementList, KUInt statementListSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _statementList = reinterpret_cast(statementList); + const auto _statementListSequenceLength = static_cast(statementListSequenceLength); + auto result = GetImpl()->CreateBlockStatement(_context, _statementList, _statementListSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateBlockStatement, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateBlockStatement(KNativePointer context, KNativePointer original, KNativePointerArray statementList, KUInt statementListSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _statementList = reinterpret_cast(statementList); + const auto _statementListSequenceLength = static_cast(statementListSequenceLength); + auto result = GetImpl()->UpdateBlockStatement(_context, _original, _statementList, _statementListSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateBlockStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_BlockStatementStatementsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->BlockStatementStatementsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(BlockStatementStatementsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BlockStatementStatements(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->BlockStatementStatements(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(BlockStatementStatements, KNativePointer, KNativePointer, KNativePointer); + +void impl_BlockStatementSetStatements(KNativePointer context, KNativePointer receiver, KNativePointerArray statementList, KUInt statementListSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _statementList = reinterpret_cast(statementList); + const auto _statementListSequenceLength = static_cast(statementListSequenceLength); + GetImpl()->BlockStatementSetStatements(_context, _receiver, _statementList, _statementListSequenceLength); + return ; +} +KOALA_INTEROP_V4(BlockStatementSetStatements, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +void impl_BlockStatementAddTrailingBlock(KNativePointer context, KNativePointer receiver, KNativePointer stmt, KNativePointer trailingBlock) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _stmt = reinterpret_cast(stmt); + const auto _trailingBlock = reinterpret_cast(trailingBlock); + GetImpl()->BlockStatementAddTrailingBlock(_context, _receiver, _stmt, _trailingBlock); + return ; +} +KOALA_INTEROP_V4(BlockStatementAddTrailingBlock, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateDirectEvalExpression(KNativePointer context, KNativePointer callee, KNativePointerArray _arguments, KUInt _argumentsSequenceLength, KNativePointer typeParams, KBoolean optional_arg, KUInt parserStatus) +{ + const auto _context = reinterpret_cast(context); + const auto _callee = reinterpret_cast(callee); + const auto __arguments = reinterpret_cast(_arguments); + const auto __argumentsSequenceLength = static_cast(_argumentsSequenceLength); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _optional_arg = static_cast(optional_arg); + const auto _parserStatus = static_cast(parserStatus); + auto result = GetImpl()->CreateDirectEvalExpression(_context, _callee, __arguments, __argumentsSequenceLength, _typeParams, _optional_arg, _parserStatus); + return result; +} +KOALA_INTEROP_7(CreateDirectEvalExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KBoolean, KUInt); + +KNativePointer impl_UpdateDirectEvalExpression(KNativePointer context, KNativePointer original, KNativePointer callee, KNativePointerArray _arguments, KUInt _argumentsSequenceLength, KNativePointer typeParams, KBoolean optional_arg, KUInt parserStatus) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _callee = reinterpret_cast(callee); + const auto __arguments = reinterpret_cast(_arguments); + const auto __argumentsSequenceLength = static_cast(_argumentsSequenceLength); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _optional_arg = static_cast(optional_arg); + const auto _parserStatus = static_cast(parserStatus); + auto result = GetImpl()->UpdateDirectEvalExpression(_context, _original, _callee, __arguments, __argumentsSequenceLength, _typeParams, _optional_arg, _parserStatus); + return result; +} +KOALA_INTEROP_8(UpdateDirectEvalExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KBoolean, KUInt); + +KNativePointer impl_CreateTSTypeParameterDeclaration(KNativePointer context, KNativePointerArray params, KUInt paramsSequenceLength, KUInt requiredParams) +{ + const auto _context = reinterpret_cast(context); + const auto _params = reinterpret_cast(params); + const auto _paramsSequenceLength = static_cast(paramsSequenceLength); + const auto _requiredParams = static_cast(requiredParams); + auto result = GetImpl()->CreateTSTypeParameterDeclaration(_context, _params, _paramsSequenceLength, _requiredParams); + return result; +} +KOALA_INTEROP_4(CreateTSTypeParameterDeclaration, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KUInt); + +KNativePointer impl_UpdateTSTypeParameterDeclaration(KNativePointer context, KNativePointer original, KNativePointerArray params, KUInt paramsSequenceLength, KUInt requiredParams) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _params = reinterpret_cast(params); + const auto _paramsSequenceLength = static_cast(paramsSequenceLength); + const auto _requiredParams = static_cast(requiredParams); + auto result = GetImpl()->UpdateTSTypeParameterDeclaration(_context, _original, _params, _paramsSequenceLength, _requiredParams); + return result; +} +KOALA_INTEROP_5(UpdateTSTypeParameterDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KUInt); + +KNativePointer impl_TSTypeParameterDeclarationParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TSTypeParameterDeclarationParamsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TSTypeParameterDeclarationParamsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSTypeParameterDeclarationAddParam(KNativePointer context, KNativePointer receiver, KNativePointer param) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _param = reinterpret_cast(param); + GetImpl()->TSTypeParameterDeclarationAddParam(_context, _receiver, _param); + return ; +} +KOALA_INTEROP_V3(TSTypeParameterDeclarationAddParam, KNativePointer, KNativePointer, KNativePointer); + +KUInt impl_TSTypeParameterDeclarationRequiredParamsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSTypeParameterDeclarationRequiredParamsConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSTypeParameterDeclarationRequiredParamsConst, KUInt, KNativePointer, KNativePointer); + +KNativePointer impl_CreateMethodDefinition(KNativePointer context, KInt kind, KNativePointer key, KNativePointer value, KInt modifiers, KBoolean isComputed) +{ + const auto _context = reinterpret_cast(context); + const auto _kind = static_cast(kind); + const auto _key = reinterpret_cast(key); + const auto _value = reinterpret_cast(value); + const auto _modifiers = static_cast(modifiers); + const auto _isComputed = static_cast(isComputed); + auto result = GetImpl()->CreateMethodDefinition(_context, _kind, _key, _value, _modifiers, _isComputed); + return result; +} +KOALA_INTEROP_6(CreateMethodDefinition, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer, KInt, KBoolean); + +KNativePointer impl_UpdateMethodDefinition(KNativePointer context, KNativePointer original, KInt kind, KNativePointer key, KNativePointer value, KInt modifiers, KBoolean isComputed) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _kind = static_cast(kind); + const auto _key = reinterpret_cast(key); + const auto _value = reinterpret_cast(value); + const auto _modifiers = static_cast(modifiers); + const auto _isComputed = static_cast(isComputed); + auto result = GetImpl()->UpdateMethodDefinition(_context, _original, _kind, _key, _value, _modifiers, _isComputed); + return result; +} +KOALA_INTEROP_7(UpdateMethodDefinition, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer, KInt, KBoolean); + +KInt impl_MethodDefinitionKindConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionKindConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MethodDefinitionKindConst, KInt, KNativePointer, KNativePointer); + +KBoolean impl_MethodDefinitionIsConstructorConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionIsConstructorConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MethodDefinitionIsConstructorConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_MethodDefinitionIsExtensionMethodConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionIsExtensionMethodConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MethodDefinitionIsExtensionMethodConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_MethodDefinitionOverloadsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->MethodDefinitionOverloadsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(MethodDefinitionOverloadsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MethodDefinitionBaseOverloadMethodConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionBaseOverloadMethodConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(MethodDefinitionBaseOverloadMethodConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MethodDefinitionBaseOverloadMethod(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionBaseOverloadMethod(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MethodDefinitionBaseOverloadMethod, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MethodDefinitionAsyncPairMethodConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionAsyncPairMethodConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(MethodDefinitionAsyncPairMethodConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MethodDefinitionAsyncPairMethod(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionAsyncPairMethod(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MethodDefinitionAsyncPairMethod, KNativePointer, KNativePointer, KNativePointer); + +void impl_MethodDefinitionSetOverloads(KNativePointer context, KNativePointer receiver, KNativePointerArray overloads, KUInt overloadsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _overloads = reinterpret_cast(overloads); + const auto _overloadsSequenceLength = static_cast(overloadsSequenceLength); + GetImpl()->MethodDefinitionSetOverloads(_context, _receiver, _overloads, _overloadsSequenceLength); + return ; +} +KOALA_INTEROP_V4(MethodDefinitionSetOverloads, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +void impl_MethodDefinitionClearOverloads(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->MethodDefinitionClearOverloads(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(MethodDefinitionClearOverloads, KNativePointer, KNativePointer); + +void impl_MethodDefinitionAddOverload(KNativePointer context, KNativePointer receiver, KNativePointer overload) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _overload = reinterpret_cast(overload); + GetImpl()->MethodDefinitionAddOverload(_context, _receiver, _overload); + return ; +} +KOALA_INTEROP_V3(MethodDefinitionAddOverload, KNativePointer, KNativePointer, KNativePointer); + +void impl_MethodDefinitionSetBaseOverloadMethod(KNativePointer context, KNativePointer receiver, KNativePointer baseOverloadMethod) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _baseOverloadMethod = reinterpret_cast(baseOverloadMethod); + GetImpl()->MethodDefinitionSetBaseOverloadMethod(_context, _receiver, _baseOverloadMethod); + return ; +} +KOALA_INTEROP_V3(MethodDefinitionSetBaseOverloadMethod, KNativePointer, KNativePointer, KNativePointer); + +void impl_MethodDefinitionSetAsyncPairMethod(KNativePointer context, KNativePointer receiver, KNativePointer method) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _method = reinterpret_cast(method); + GetImpl()->MethodDefinitionSetAsyncPairMethod(_context, _receiver, _method); + return ; +} +KOALA_INTEROP_V3(MethodDefinitionSetAsyncPairMethod, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_MethodDefinitionHasOverload(KNativePointer context, KNativePointer receiver, KNativePointer overload) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _overload = reinterpret_cast(overload); + auto result = GetImpl()->MethodDefinitionHasOverload(_context, _receiver, _overload); + return result; +} +KOALA_INTEROP_3(MethodDefinitionHasOverload, KBoolean, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MethodDefinitionFunction(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionFunction(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MethodDefinitionFunction, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_MethodDefinitionFunctionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MethodDefinitionFunctionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(MethodDefinitionFunctionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSNullKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSNullKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSNullKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSNullKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSNullKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSNullKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSInterfaceHeritage(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateTSInterfaceHeritage(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateTSInterfaceHeritage, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSInterfaceHeritage(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateTSInterfaceHeritage(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateTSInterfaceHeritage, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceHeritageExpr(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceHeritageExpr(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSInterfaceHeritageExpr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSInterfaceHeritageExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSInterfaceHeritageExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSInterfaceHeritageExprConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ExpressionIsGroupedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionIsGroupedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionIsGroupedConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ExpressionSetGrouped(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->ExpressionSetGrouped(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(ExpressionSetGrouped, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionAsLiteralConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionAsLiteralConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExpressionAsLiteralConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionAsLiteral(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionAsLiteral(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionAsLiteral, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ExpressionIsLiteralConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionIsLiteralConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionIsLiteralConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ExpressionIsTypeNodeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionIsTypeNodeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionIsTypeNodeConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_ExpressionIsAnnotatedExpressionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionIsAnnotatedExpressionConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionIsAnnotatedExpressionConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionAsTypeNode(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionAsTypeNode(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionAsTypeNode, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionAsTypeNodeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionAsTypeNodeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExpressionAsTypeNodeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionAsAnnotatedExpression(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionAsAnnotatedExpression(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionAsAnnotatedExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionAsAnnotatedExpressionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionAsAnnotatedExpressionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ExpressionAsAnnotatedExpressionConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ExpressionIsBrokenExpressionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionIsBrokenExpressionConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ExpressionIsBrokenExpressionConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_ExpressionToStringConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ExpressionToStringConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ExpressionToStringConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AnnotatedExpressionTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AnnotatedExpressionTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AnnotatedExpressionTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_AnnotatedExpressionSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->AnnotatedExpressionSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(AnnotatedExpressionSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_MaybeOptionalExpressionIsOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->MaybeOptionalExpressionIsOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(MaybeOptionalExpressionIsOptionalConst, KBoolean, KNativePointer, KNativePointer); + +void impl_MaybeOptionalExpressionClearOptional(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->MaybeOptionalExpressionClearOptional(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(MaybeOptionalExpressionClearOptional, KNativePointer, KNativePointer); + +KNativePointer impl_CreateSrcDumper(KNativePointer context, KNativePointer node) +{ + const auto _context = reinterpret_cast(context); + const auto _node = reinterpret_cast(node); + auto result = GetImpl()->CreateSrcDumper(_context, _node); + return result; +} +KOALA_INTEROP_2(CreateSrcDumper, KNativePointer, KNativePointer, KNativePointer); + +void impl_SrcDumperAdd(KNativePointer context, KNativePointer receiver, KStringPtr& str) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _str = getStringCopy(str); + GetImpl()->SrcDumperAdd(_context, _receiver, _str); + return ; +} +KOALA_INTEROP_V3(SrcDumperAdd, KNativePointer, KNativePointer, KStringPtr); + +void impl_SrcDumperAdd1(KNativePointer context, KNativePointer receiver, KInt i) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _i = static_cast(i); + GetImpl()->SrcDumperAdd1(_context, _receiver, _i); + return ; +} +KOALA_INTEROP_V3(SrcDumperAdd1, KNativePointer, KNativePointer, KInt); + +void impl_SrcDumperAdd2(KNativePointer context, KNativePointer receiver, KLong l) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _l = static_cast(l); + GetImpl()->SrcDumperAdd2(_context, _receiver, _l); + return ; +} +KOALA_INTEROP_V3(SrcDumperAdd2, KNativePointer, KNativePointer, KLong); + +void impl_SrcDumperAdd3(KNativePointer context, KNativePointer receiver, KFloat f) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _f = static_cast(f); + GetImpl()->SrcDumperAdd3(_context, _receiver, _f); + return ; +} +KOALA_INTEROP_V3(SrcDumperAdd3, KNativePointer, KNativePointer, KFloat); + +void impl_SrcDumperAdd4(KNativePointer context, KNativePointer receiver, KDouble d) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _d = static_cast(d); + GetImpl()->SrcDumperAdd4(_context, _receiver, _d); + return ; +} +KOALA_INTEROP_V3(SrcDumperAdd4, KNativePointer, KNativePointer, KDouble); + +KNativePointer impl_SrcDumperStrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SrcDumperStrConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(SrcDumperStrConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_SrcDumperIncrIndent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->SrcDumperIncrIndent(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(SrcDumperIncrIndent, KNativePointer, KNativePointer); + +void impl_SrcDumperDecrIndent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + GetImpl()->SrcDumperDecrIndent(_context, _receiver); + return ; +} +KOALA_INTEROP_V2(SrcDumperDecrIndent, KNativePointer, KNativePointer); + +void impl_SrcDumperEndl(KNativePointer context, KNativePointer receiver, KUInt num) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _num = static_cast(num); + GetImpl()->SrcDumperEndl(_context, _receiver, _num); + return ; +} +KOALA_INTEROP_V3(SrcDumperEndl, KNativePointer, KNativePointer, KUInt); + +KNativePointer impl_CreateETSClassLiteral(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateETSClassLiteral(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateETSClassLiteral, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSClassLiteral(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateETSClassLiteral(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateETSClassLiteral, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSClassLiteralExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSClassLiteralExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSClassLiteralExprConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateBreakStatement(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateBreakStatement(_context); + return result; +} +KOALA_INTEROP_1(CreateBreakStatement, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateBreakStatement(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateBreakStatement(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateBreakStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateBreakStatement1(KNativePointer context, KNativePointer ident) +{ + const auto _context = reinterpret_cast(context); + const auto _ident = reinterpret_cast(ident); + auto result = GetImpl()->CreateBreakStatement1(_context, _ident); + return result; +} +KOALA_INTEROP_2(CreateBreakStatement1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateBreakStatement1(KNativePointer context, KNativePointer original, KNativePointer ident) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _ident = reinterpret_cast(ident); + auto result = GetImpl()->UpdateBreakStatement1(_context, _original, _ident); + return result; +} +KOALA_INTEROP_3(UpdateBreakStatement1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BreakStatementIdentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BreakStatementIdentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(BreakStatementIdentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BreakStatementIdent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BreakStatementIdent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(BreakStatementIdent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_BreakStatementTargetConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->BreakStatementTargetConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(BreakStatementTargetConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_BreakStatementSetTarget(KNativePointer context, KNativePointer receiver, KNativePointer target) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _target = reinterpret_cast(target); + GetImpl()->BreakStatementSetTarget(_context, _receiver, _target); + return ; +} +KOALA_INTEROP_V3(BreakStatementSetTarget, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateRegExpLiteral(KNativePointer context, KStringPtr& pattern, KInt flags, KStringPtr& flagsStr) +{ + const auto _context = reinterpret_cast(context); + const auto _pattern = getStringCopy(pattern); + const auto _flags = static_cast(flags); + const auto _flagsStr = getStringCopy(flagsStr); + auto result = GetImpl()->CreateRegExpLiteral(_context, _pattern, _flags, _flagsStr); + return result; +} +KOALA_INTEROP_4(CreateRegExpLiteral, KNativePointer, KNativePointer, KStringPtr, KInt, KStringPtr); + +KNativePointer impl_UpdateRegExpLiteral(KNativePointer context, KNativePointer original, KStringPtr& pattern, KInt flags, KStringPtr& flagsStr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _pattern = getStringCopy(pattern); + const auto _flags = static_cast(flags); + const auto _flagsStr = getStringCopy(flagsStr); + auto result = GetImpl()->UpdateRegExpLiteral(_context, _original, _pattern, _flags, _flagsStr); + return result; +} +KOALA_INTEROP_5(UpdateRegExpLiteral, KNativePointer, KNativePointer, KNativePointer, KStringPtr, KInt, KStringPtr); + +KNativePointer impl_RegExpLiteralPatternConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->RegExpLiteralPatternConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(RegExpLiteralPatternConst, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_RegExpLiteralFlagsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->RegExpLiteralFlagsConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(RegExpLiteralFlagsConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSMappedType(KNativePointer context, KNativePointer typeParameter, KNativePointer typeAnnotation, KInt readonly_arg, KInt optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _typeParameter = reinterpret_cast(typeParameter); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _readonly_arg = static_cast(readonly_arg); + const auto _optional_arg = static_cast(optional_arg); + auto result = GetImpl()->CreateTSMappedType(_context, _typeParameter, _typeAnnotation, _readonly_arg, _optional_arg); + return result; +} +KOALA_INTEROP_5(CreateTSMappedType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KInt); + +KNativePointer impl_UpdateTSMappedType(KNativePointer context, KNativePointer original, KNativePointer typeParameter, KNativePointer typeAnnotation, KInt readonly_arg, KInt optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeParameter = reinterpret_cast(typeParameter); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _readonly_arg = static_cast(readonly_arg); + const auto _optional_arg = static_cast(optional_arg); + auto result = GetImpl()->UpdateTSMappedType(_context, _original, _typeParameter, _typeAnnotation, _readonly_arg, _optional_arg); + return result; +} +KOALA_INTEROP_6(UpdateTSMappedType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt, KInt); + +KNativePointer impl_TSMappedTypeTypeParameter(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMappedTypeTypeParameter(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMappedTypeTypeParameter, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSMappedTypeTypeAnnotation(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMappedTypeTypeAnnotation(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMappedTypeTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KInt impl_TSMappedTypeReadonly(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMappedTypeReadonly(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMappedTypeReadonly, KInt, KNativePointer, KNativePointer); + +KInt impl_TSMappedTypeOptional(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSMappedTypeOptional(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSMappedTypeOptional, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSAnyKeyword(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSAnyKeyword(_context); + return result; +} +KOALA_INTEROP_1(CreateTSAnyKeyword, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSAnyKeyword(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSAnyKeyword(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSAnyKeyword, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateClassDeclaration(KNativePointer context, KNativePointer def) +{ + const auto _context = reinterpret_cast(context); + const auto _def = reinterpret_cast(def); + auto result = GetImpl()->CreateClassDeclaration(_context, _def); + return result; +} +KOALA_INTEROP_2(CreateClassDeclaration, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateClassDeclaration(KNativePointer context, KNativePointer original, KNativePointer def) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _def = reinterpret_cast(def); + auto result = GetImpl()->UpdateClassDeclaration(_context, _original, _def); + return result; +} +KOALA_INTEROP_3(UpdateClassDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDeclarationDefinition(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDeclarationDefinition(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ClassDeclarationDefinition, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDeclarationDefinitionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ClassDeclarationDefinitionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ClassDeclarationDefinitionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ClassDeclarationDecoratorsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ClassDeclarationDecoratorsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ClassDeclarationDecoratorsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSIndexedAccessType(KNativePointer context, KNativePointer objectType, KNativePointer indexType) +{ + const auto _context = reinterpret_cast(context); + const auto _objectType = reinterpret_cast(objectType); + const auto _indexType = reinterpret_cast(indexType); + auto result = GetImpl()->CreateTSIndexedAccessType(_context, _objectType, _indexType); + return result; +} +KOALA_INTEROP_3(CreateTSIndexedAccessType, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSIndexedAccessType(KNativePointer context, KNativePointer original, KNativePointer objectType, KNativePointer indexType) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _objectType = reinterpret_cast(objectType); + const auto _indexType = reinterpret_cast(indexType); + auto result = GetImpl()->UpdateTSIndexedAccessType(_context, _original, _objectType, _indexType); + return result; +} +KOALA_INTEROP_4(UpdateTSIndexedAccessType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSIndexedAccessTypeObjectTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSIndexedAccessTypeObjectTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSIndexedAccessTypeObjectTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSIndexedAccessTypeIndexTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSIndexedAccessTypeIndexTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSIndexedAccessTypeIndexTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSQualifiedName(KNativePointer context, KNativePointer left, KNativePointer right) +{ + const auto _context = reinterpret_cast(context); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + auto result = GetImpl()->CreateTSQualifiedName(_context, _left, _right); + return result; +} +KOALA_INTEROP_3(CreateTSQualifiedName, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSQualifiedName(KNativePointer context, KNativePointer original, KNativePointer left, KNativePointer right) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _left = reinterpret_cast(left); + const auto _right = reinterpret_cast(right); + auto result = GetImpl()->UpdateTSQualifiedName(_context, _original, _left, _right); + return result; +} +KOALA_INTEROP_4(UpdateTSQualifiedName, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSQualifiedNameLeftConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSQualifiedNameLeftConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSQualifiedNameLeftConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSQualifiedNameLeft(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSQualifiedNameLeft(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSQualifiedNameLeft, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSQualifiedNameRightConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSQualifiedNameRightConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSQualifiedNameRightConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSQualifiedNameRight(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSQualifiedNameRight(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSQualifiedNameRight, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSQualifiedNameNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSQualifiedNameNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(TSQualifiedNameNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSQualifiedNameResolveLeftMostQualifiedName(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSQualifiedNameResolveLeftMostQualifiedName(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSQualifiedNameResolveLeftMostQualifiedName, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSQualifiedNameResolveLeftMostQualifiedNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSQualifiedNameResolveLeftMostQualifiedNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSQualifiedNameResolveLeftMostQualifiedNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateAwaitExpression(KNativePointer context, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->CreateAwaitExpression(_context, _argument); + return result; +} +KOALA_INTEROP_2(CreateAwaitExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateAwaitExpression(KNativePointer context, KNativePointer original, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->UpdateAwaitExpression(_context, _original, _argument); + return result; +} +KOALA_INTEROP_3(UpdateAwaitExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AwaitExpressionArgumentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AwaitExpressionArgumentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(AwaitExpressionArgumentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateValidationInfo(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateValidationInfo(_context); + return result; +} +KOALA_INTEROP_1(CreateValidationInfo, KNativePointer, KNativePointer); + +KBoolean impl_ValidationInfoFailConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ValidationInfoFailConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ValidationInfoFailConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateContinueStatement(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateContinueStatement(_context); + return result; +} +KOALA_INTEROP_1(CreateContinueStatement, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateContinueStatement(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateContinueStatement(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateContinueStatement, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateContinueStatement1(KNativePointer context, KNativePointer ident) +{ + const auto _context = reinterpret_cast(context); + const auto _ident = reinterpret_cast(ident); + auto result = GetImpl()->CreateContinueStatement1(_context, _ident); + return result; +} +KOALA_INTEROP_2(CreateContinueStatement1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateContinueStatement1(KNativePointer context, KNativePointer original, KNativePointer ident) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _ident = reinterpret_cast(ident); + auto result = GetImpl()->UpdateContinueStatement1(_context, _original, _ident); + return result; +} +KOALA_INTEROP_3(UpdateContinueStatement1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ContinueStatementIdentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ContinueStatementIdentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ContinueStatementIdentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ContinueStatementIdent(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ContinueStatementIdent(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ContinueStatementIdent, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ContinueStatementTargetConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ContinueStatementTargetConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ContinueStatementTargetConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ContinueStatementSetTarget(KNativePointer context, KNativePointer receiver, KNativePointer target) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _target = reinterpret_cast(target); + GetImpl()->ContinueStatementSetTarget(_context, _receiver, _target); + return ; +} +KOALA_INTEROP_V3(ContinueStatementSetTarget, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSNewMultiDimArrayInstanceExpression(KNativePointer context, KNativePointer typeReference, KNativePointerArray dimensions, KUInt dimensionsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _typeReference = reinterpret_cast(typeReference); + const auto _dimensions = reinterpret_cast(dimensions); + const auto _dimensionsSequenceLength = static_cast(dimensionsSequenceLength); + auto result = GetImpl()->CreateETSNewMultiDimArrayInstanceExpression(_context, _typeReference, _dimensions, _dimensionsSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateETSNewMultiDimArrayInstanceExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateETSNewMultiDimArrayInstanceExpression(KNativePointer context, KNativePointer original, KNativePointer typeReference, KNativePointerArray dimensions, KUInt dimensionsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeReference = reinterpret_cast(typeReference); + const auto _dimensions = reinterpret_cast(dimensions); + const auto _dimensionsSequenceLength = static_cast(dimensionsSequenceLength); + auto result = GetImpl()->UpdateETSNewMultiDimArrayInstanceExpression(_context, _original, _typeReference, _dimensions, _dimensionsSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateETSNewMultiDimArrayInstanceExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateETSNewMultiDimArrayInstanceExpression1(KNativePointer context, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->CreateETSNewMultiDimArrayInstanceExpression1(_context, _other); + return result; +} +KOALA_INTEROP_2(CreateETSNewMultiDimArrayInstanceExpression1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSNewMultiDimArrayInstanceExpression1(KNativePointer context, KNativePointer original, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->UpdateETSNewMultiDimArrayInstanceExpression1(_context, _original, _other); + return result; +} +KOALA_INTEROP_3(UpdateETSNewMultiDimArrayInstanceExpression1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewMultiDimArrayInstanceExpressionTypeReference(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSNewMultiDimArrayInstanceExpressionTypeReference(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSNewMultiDimArrayInstanceExpressionTypeReference, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewMultiDimArrayInstanceExpressionTypeReferenceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSNewMultiDimArrayInstanceExpressionTypeReferenceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSNewMultiDimArrayInstanceExpressionTypeReferenceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewMultiDimArrayInstanceExpressionDimensions(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSNewMultiDimArrayInstanceExpressionDimensions(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSNewMultiDimArrayInstanceExpressionDimensions, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewMultiDimArrayInstanceExpressionDimensionsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSNewMultiDimArrayInstanceExpressionDimensionsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSNewMultiDimArrayInstanceExpressionDimensionsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSNamedTupleMember(KNativePointer context, KNativePointer label, KNativePointer elementType, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _label = reinterpret_cast(label); + const auto _elementType = reinterpret_cast(elementType); + const auto _optional_arg = static_cast(optional_arg); + auto result = GetImpl()->CreateTSNamedTupleMember(_context, _label, _elementType, _optional_arg); + return result; +} +KOALA_INTEROP_4(CreateTSNamedTupleMember, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateTSNamedTupleMember(KNativePointer context, KNativePointer original, KNativePointer label, KNativePointer elementType, KBoolean optional_arg) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _label = reinterpret_cast(label); + const auto _elementType = reinterpret_cast(elementType); + const auto _optional_arg = static_cast(optional_arg); + auto result = GetImpl()->UpdateTSNamedTupleMember(_context, _original, _label, _elementType, _optional_arg); + return result; +} +KOALA_INTEROP_5(UpdateTSNamedTupleMember, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSNamedTupleMemberLabelConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSNamedTupleMemberLabelConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSNamedTupleMemberLabelConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSNamedTupleMemberElementType(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSNamedTupleMemberElementType(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSNamedTupleMemberElementType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSNamedTupleMemberElementTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSNamedTupleMemberElementTypeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSNamedTupleMemberElementTypeConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSNamedTupleMemberIsOptionalConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSNamedTupleMemberIsOptionalConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSNamedTupleMemberIsOptionalConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateImportExpression(KNativePointer context, KNativePointer source) +{ + const auto _context = reinterpret_cast(context); + const auto _source = reinterpret_cast(source); + auto result = GetImpl()->CreateImportExpression(_context, _source); + return result; +} +KOALA_INTEROP_2(CreateImportExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateImportExpression(KNativePointer context, KNativePointer original, KNativePointer source) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _source = reinterpret_cast(source); + auto result = GetImpl()->UpdateImportExpression(_context, _original, _source); + return result; +} +KOALA_INTEROP_3(UpdateImportExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportExpressionSource(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportExpressionSource(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ImportExpressionSource, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ImportExpressionSourceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ImportExpressionSourceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ImportExpressionSourceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateAstDumper(KNativePointer context, KNativePointer node, KStringPtr& sourceCode) +{ + const auto _context = reinterpret_cast(context); + const auto _node = reinterpret_cast(node); + const auto _sourceCode = getStringCopy(sourceCode); + auto result = GetImpl()->CreateAstDumper(_context, _node, _sourceCode); + return result; +} +KOALA_INTEROP_3(CreateAstDumper, KNativePointer, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_AstDumperModifierToString(KNativePointer context, KNativePointer receiver, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _flags = static_cast(flags); + auto result = GetImpl()->AstDumperModifierToString(_context, _receiver, _flags); + return new std::string(result); +} +KOALA_INTEROP_3(AstDumperModifierToString, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_AstDumperTypeOperatorToString(KNativePointer context, KNativePointer receiver, KInt operatorType) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _operatorType = static_cast(operatorType); + auto result = GetImpl()->AstDumperTypeOperatorToString(_context, _receiver, _operatorType); + return new std::string(result); +} +KOALA_INTEROP_3(AstDumperTypeOperatorToString, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_AstDumperStrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->AstDumperStrConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(AstDumperStrConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSNullTypeIr(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateETSNullTypeIr(_context); + return result; +} +KOALA_INTEROP_1(CreateETSNullTypeIr, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSNullTypeIr(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateETSNullTypeIr(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateETSNullTypeIr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSUndefinedTypeIr(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateETSUndefinedTypeIr(_context); + return result; +} +KOALA_INTEROP_1(CreateETSUndefinedTypeIr, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSUndefinedTypeIr(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateETSUndefinedTypeIr(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateETSUndefinedTypeIr, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTypeofExpression(KNativePointer context, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->CreateTypeofExpression(_context, _argument); + return result; +} +KOALA_INTEROP_2(CreateTypeofExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTypeofExpression(KNativePointer context, KNativePointer original, KNativePointer argument) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _argument = reinterpret_cast(argument); + auto result = GetImpl()->UpdateTypeofExpression(_context, _original, _argument); + return result; +} +KOALA_INTEROP_3(UpdateTypeofExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TypeofExpressionArgumentConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TypeofExpressionArgumentConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TypeofExpressionArgumentConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSEnumMember(KNativePointer context, KNativePointer key, KNativePointer init) +{ + const auto _context = reinterpret_cast(context); + const auto _key = reinterpret_cast(key); + const auto _init = reinterpret_cast(init); + auto result = GetImpl()->CreateTSEnumMember(_context, _key, _init); + return result; +} +KOALA_INTEROP_3(CreateTSEnumMember, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSEnumMember(KNativePointer context, KNativePointer original, KNativePointer key, KNativePointer init) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _key = reinterpret_cast(key); + const auto _init = reinterpret_cast(init); + auto result = GetImpl()->UpdateTSEnumMember(_context, _original, _key, _init); + return result; +} +KOALA_INTEROP_4(UpdateTSEnumMember, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSEnumMember1(KNativePointer context, KNativePointer key, KNativePointer init, KBoolean isGenerated) +{ + const auto _context = reinterpret_cast(context); + const auto _key = reinterpret_cast(key); + const auto _init = reinterpret_cast(init); + const auto _isGenerated = static_cast(isGenerated); + auto result = GetImpl()->CreateTSEnumMember1(_context, _key, _init, _isGenerated); + return result; +} +KOALA_INTEROP_4(CreateTSEnumMember1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateTSEnumMember1(KNativePointer context, KNativePointer original, KNativePointer key, KNativePointer init, KBoolean isGenerated) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _key = reinterpret_cast(key); + const auto _init = reinterpret_cast(init); + const auto _isGenerated = static_cast(isGenerated); + auto result = GetImpl()->UpdateTSEnumMember1(_context, _original, _key, _init, _isGenerated); + return result; +} +KOALA_INTEROP_5(UpdateTSEnumMember1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSEnumMemberKeyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumMemberKeyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSEnumMemberKeyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSEnumMemberKey(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumMemberKey(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSEnumMemberKey, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSEnumMemberInitConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumMemberInitConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSEnumMemberInitConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSEnumMemberInit(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumMemberInit(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSEnumMemberInit, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSEnumMemberIsGeneratedConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumMemberIsGeneratedConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSEnumMemberIsGeneratedConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_TSEnumMemberNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSEnumMemberNameConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(TSEnumMemberNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateSwitchStatement(KNativePointer context, KNativePointer discriminant, KNativePointerArray cases, KUInt casesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _discriminant = reinterpret_cast(discriminant); + const auto _cases = reinterpret_cast(cases); + const auto _casesSequenceLength = static_cast(casesSequenceLength); + auto result = GetImpl()->CreateSwitchStatement(_context, _discriminant, _cases, _casesSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateSwitchStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateSwitchStatement(KNativePointer context, KNativePointer original, KNativePointer discriminant, KNativePointerArray cases, KUInt casesSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _discriminant = reinterpret_cast(discriminant); + const auto _cases = reinterpret_cast(cases); + const auto _casesSequenceLength = static_cast(casesSequenceLength); + auto result = GetImpl()->UpdateSwitchStatement(_context, _original, _discriminant, _cases, _casesSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateSwitchStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_SwitchStatementDiscriminantConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SwitchStatementDiscriminantConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(SwitchStatementDiscriminantConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_SwitchStatementDiscriminant(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->SwitchStatementDiscriminant(_context, _receiver); + return result; +} +KOALA_INTEROP_2(SwitchStatementDiscriminant, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_SwitchStatementCasesConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->SwitchStatementCasesConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(SwitchStatementCasesConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_SwitchStatementCases(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->SwitchStatementCases(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(SwitchStatementCases, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateDoWhileStatement(KNativePointer context, KNativePointer body, KNativePointer test) +{ + const auto _context = reinterpret_cast(context); + const auto _body = reinterpret_cast(body); + const auto _test = reinterpret_cast(test); + auto result = GetImpl()->CreateDoWhileStatement(_context, _body, _test); + return result; +} +KOALA_INTEROP_3(CreateDoWhileStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateDoWhileStatement(KNativePointer context, KNativePointer original, KNativePointer body, KNativePointer test) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _body = reinterpret_cast(body); + const auto _test = reinterpret_cast(test); + auto result = GetImpl()->UpdateDoWhileStatement(_context, _original, _body, _test); + return result; +} +KOALA_INTEROP_4(UpdateDoWhileStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_DoWhileStatementBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->DoWhileStatementBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(DoWhileStatementBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_DoWhileStatementBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->DoWhileStatementBody(_context, _receiver); + return result; +} +KOALA_INTEROP_2(DoWhileStatementBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_DoWhileStatementTestConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->DoWhileStatementTestConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(DoWhileStatementTestConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_DoWhileStatementTest(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->DoWhileStatementTest(_context, _receiver); + return result; +} +KOALA_INTEROP_2(DoWhileStatementTest, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateCatchClause(KNativePointer context, KNativePointer param, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _param = reinterpret_cast(param); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->CreateCatchClause(_context, _param, _body); + return result; +} +KOALA_INTEROP_3(CreateCatchClause, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateCatchClause(KNativePointer context, KNativePointer original, KNativePointer param, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _param = reinterpret_cast(param); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->UpdateCatchClause(_context, _original, _param, _body); + return result; +} +KOALA_INTEROP_4(UpdateCatchClause, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CatchClauseParam(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CatchClauseParam(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CatchClauseParam, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CatchClauseParamConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CatchClauseParamConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(CatchClauseParamConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CatchClauseBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CatchClauseBody(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CatchClauseBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CatchClauseBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CatchClauseBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(CatchClauseBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_CatchClauseIsDefaultCatchClauseConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->CatchClauseIsDefaultCatchClauseConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(CatchClauseIsDefaultCatchClauseConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_CreateSequenceExpression(KNativePointer context, KNativePointerArray sequence_arg, KUInt sequence_argSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _sequence_arg = reinterpret_cast(sequence_arg); + const auto _sequence_argSequenceLength = static_cast(sequence_argSequenceLength); + auto result = GetImpl()->CreateSequenceExpression(_context, _sequence_arg, _sequence_argSequenceLength); + return result; +} +KOALA_INTEROP_3(CreateSequenceExpression, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateSequenceExpression(KNativePointer context, KNativePointer original, KNativePointerArray sequence_arg, KUInt sequence_argSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _sequence_arg = reinterpret_cast(sequence_arg); + const auto _sequence_argSequenceLength = static_cast(sequence_argSequenceLength); + auto result = GetImpl()->UpdateSequenceExpression(_context, _original, _sequence_arg, _sequence_argSequenceLength); + return result; +} +KOALA_INTEROP_4(UpdateSequenceExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_SequenceExpressionSequenceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->SequenceExpressionSequenceConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(SequenceExpressionSequenceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_SequenceExpressionSequence(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->SequenceExpressionSequence(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(SequenceExpressionSequence, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateArrowFunctionExpression(KNativePointer context, KNativePointer func) +{ + const auto _context = reinterpret_cast(context); + const auto _func = reinterpret_cast(func); + auto result = GetImpl()->CreateArrowFunctionExpression(_context, _func); + return result; +} +KOALA_INTEROP_2(CreateArrowFunctionExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateArrowFunctionExpression(KNativePointer context, KNativePointer original, KNativePointer func) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _func = reinterpret_cast(func); + auto result = GetImpl()->UpdateArrowFunctionExpression(_context, _original, _func); + return result; +} +KOALA_INTEROP_3(UpdateArrowFunctionExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateArrowFunctionExpression1(KNativePointer context, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->CreateArrowFunctionExpression1(_context, _other); + return result; +} +KOALA_INTEROP_2(CreateArrowFunctionExpression1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateArrowFunctionExpression1(KNativePointer context, KNativePointer original, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->UpdateArrowFunctionExpression1(_context, _original, _other); + return result; +} +KOALA_INTEROP_3(UpdateArrowFunctionExpression1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ArrowFunctionExpressionFunctionConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ArrowFunctionExpressionFunctionConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ArrowFunctionExpressionFunctionConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ArrowFunctionExpressionFunction(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ArrowFunctionExpressionFunction(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ArrowFunctionExpressionFunction, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ArrowFunctionExpressionCreateTypeAnnotation(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ArrowFunctionExpressionCreateTypeAnnotation(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ArrowFunctionExpressionCreateTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ArrowFunctionExpressionAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ArrowFunctionExpressionAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ArrowFunctionExpressionAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ArrowFunctionExpressionAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ArrowFunctionExpressionAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ArrowFunctionExpressionAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ArrowFunctionExpressionSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->ArrowFunctionExpressionSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(ArrowFunctionExpressionSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateOmittedExpression(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateOmittedExpression(_context); + return result; +} +KOALA_INTEROP_1(CreateOmittedExpression, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateOmittedExpression(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateOmittedExpression(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateOmittedExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSNewClassInstanceExpression(KNativePointer context, KNativePointer typeReference, KNativePointerArray _arguments, KUInt _argumentsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _typeReference = reinterpret_cast(typeReference); + const auto __arguments = reinterpret_cast(_arguments); + const auto __argumentsSequenceLength = static_cast(_argumentsSequenceLength); + auto result = GetImpl()->CreateETSNewClassInstanceExpression(_context, _typeReference, __arguments, __argumentsSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateETSNewClassInstanceExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateETSNewClassInstanceExpression(KNativePointer context, KNativePointer original, KNativePointer typeReference, KNativePointerArray _arguments, KUInt _argumentsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeReference = reinterpret_cast(typeReference); + const auto __arguments = reinterpret_cast(_arguments); + const auto __argumentsSequenceLength = static_cast(_argumentsSequenceLength); + auto result = GetImpl()->UpdateETSNewClassInstanceExpression(_context, _original, _typeReference, __arguments, __argumentsSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateETSNewClassInstanceExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateETSNewClassInstanceExpression1(KNativePointer context, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->CreateETSNewClassInstanceExpression1(_context, _other); + return result; +} +KOALA_INTEROP_2(CreateETSNewClassInstanceExpression1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSNewClassInstanceExpression1(KNativePointer context, KNativePointer original, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->UpdateETSNewClassInstanceExpression1(_context, _original, _other); + return result; +} +KOALA_INTEROP_3(UpdateETSNewClassInstanceExpression1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewClassInstanceExpressionGetTypeRefConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSNewClassInstanceExpressionGetTypeRefConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSNewClassInstanceExpressionGetTypeRefConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewClassInstanceExpressionGetArguments(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSNewClassInstanceExpressionGetArguments(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSNewClassInstanceExpressionGetArguments, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSNewClassInstanceExpressionGetArgumentsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->ETSNewClassInstanceExpressionGetArgumentsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(ETSNewClassInstanceExpressionGetArgumentsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_ETSNewClassInstanceExpressionSetArguments(KNativePointer context, KNativePointer receiver, KNativePointerArray _arguments, KUInt _argumentsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto __arguments = reinterpret_cast(_arguments); + const auto __argumentsSequenceLength = static_cast(_argumentsSequenceLength); + GetImpl()->ETSNewClassInstanceExpressionSetArguments(_context, _receiver, __arguments, __argumentsSequenceLength); + return ; +} +KOALA_INTEROP_V4(ETSNewClassInstanceExpressionSetArguments, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +void impl_ETSNewClassInstanceExpressionAddToArgumentsFront(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->ETSNewClassInstanceExpressionAddToArgumentsFront(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(ETSNewClassInstanceExpressionAddToArgumentsFront, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSAsExpression(KNativePointer context, KNativePointer expression, KNativePointer typeAnnotation, KBoolean isConst) +{ + const auto _context = reinterpret_cast(context); + const auto _expression = reinterpret_cast(expression); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _isConst = static_cast(isConst); + auto result = GetImpl()->CreateTSAsExpression(_context, _expression, _typeAnnotation, _isConst); + return result; +} +KOALA_INTEROP_4(CreateTSAsExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_UpdateTSAsExpression(KNativePointer context, KNativePointer original, KNativePointer expression, KNativePointer typeAnnotation, KBoolean isConst) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expression = reinterpret_cast(expression); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + const auto _isConst = static_cast(isConst); + auto result = GetImpl()->UpdateTSAsExpression(_context, _original, _expression, _typeAnnotation, _isConst); + return result; +} +KOALA_INTEROP_5(UpdateTSAsExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSAsExpressionExprConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSAsExpressionExprConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSAsExpressionExprConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TSAsExpressionExpr(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSAsExpressionExpr(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSAsExpressionExpr, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSAsExpressionSetExpr(KNativePointer context, KNativePointer receiver, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _expr = reinterpret_cast(expr); + GetImpl()->TSAsExpressionSetExpr(_context, _receiver, _expr); + return ; +} +KOALA_INTEROP_V3(TSAsExpressionSetExpr, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_TSAsExpressionIsConstConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSAsExpressionIsConstConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSAsExpressionIsConstConst, KBoolean, KNativePointer, KNativePointer); + +void impl_TSAsExpressionSetUncheckedCast(KNativePointer context, KNativePointer receiver, KBoolean isUncheckedCast) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _isUncheckedCast = static_cast(isUncheckedCast); + GetImpl()->TSAsExpressionSetUncheckedCast(_context, _receiver, _isUncheckedCast); + return ; +} +KOALA_INTEROP_V3(TSAsExpressionSetUncheckedCast, KNativePointer, KNativePointer, KBoolean); + +KNativePointer impl_TSAsExpressionTypeAnnotationConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSAsExpressionTypeAnnotationConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSAsExpressionTypeAnnotationConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TSAsExpressionSetTsTypeAnnotation(KNativePointer context, KNativePointer receiver, KNativePointer typeAnnotation) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _typeAnnotation = reinterpret_cast(typeAnnotation); + GetImpl()->TSAsExpressionSetTsTypeAnnotation(_context, _receiver, _typeAnnotation); + return ; +} +KOALA_INTEROP_V3(TSAsExpressionSetTsTypeAnnotation, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateForUpdateStatement(KNativePointer context, KNativePointer init, KNativePointer test, KNativePointer update, KNativePointer body) +{ + const auto _context = reinterpret_cast(context); + const auto _init = reinterpret_cast(init); + const auto _test = reinterpret_cast(test); + const auto _update = reinterpret_cast(update); + const auto _body = reinterpret_cast(body); + auto result = GetImpl()->CreateForUpdateStatement(_context, _init, _test, _update, _body); + return result; +} +KOALA_INTEROP_5(CreateForUpdateStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForUpdateStatementInit(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForUpdateStatementInit(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForUpdateStatementInit, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForUpdateStatementInitConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForUpdateStatementInitConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForUpdateStatementInitConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForUpdateStatementTest(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForUpdateStatementTest(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForUpdateStatementTest, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForUpdateStatementTestConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForUpdateStatementTestConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForUpdateStatementTestConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForUpdateStatementUpdateConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForUpdateStatementUpdateConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForUpdateStatementUpdateConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForUpdateStatementBody(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForUpdateStatementBody(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ForUpdateStatementBody, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ForUpdateStatementBodyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ForUpdateStatementBodyConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ForUpdateStatementBodyConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSTypeReferencePart(KNativePointer context, KNativePointer name, KNativePointer typeParams, KNativePointer prev) +{ + const auto _context = reinterpret_cast(context); + const auto _name = reinterpret_cast(name); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _prev = reinterpret_cast(prev); + auto result = GetImpl()->CreateETSTypeReferencePart(_context, _name, _typeParams, _prev); + return result; +} +KOALA_INTEROP_4(CreateETSTypeReferencePart, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSTypeReferencePart(KNativePointer context, KNativePointer original, KNativePointer name, KNativePointer typeParams, KNativePointer prev) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = reinterpret_cast(name); + const auto _typeParams = reinterpret_cast(typeParams); + const auto _prev = reinterpret_cast(prev); + auto result = GetImpl()->UpdateETSTypeReferencePart(_context, _original, _name, _typeParams, _prev); + return result; +} +KOALA_INTEROP_5(UpdateETSTypeReferencePart, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSTypeReferencePart1(KNativePointer context, KNativePointer name) +{ + const auto _context = reinterpret_cast(context); + const auto _name = reinterpret_cast(name); + auto result = GetImpl()->CreateETSTypeReferencePart1(_context, _name); + return result; +} +KOALA_INTEROP_2(CreateETSTypeReferencePart1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSTypeReferencePart1(KNativePointer context, KNativePointer original, KNativePointer name) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _name = reinterpret_cast(name); + auto result = GetImpl()->UpdateETSTypeReferencePart1(_context, _original, _name); + return result; +} +KOALA_INTEROP_3(UpdateETSTypeReferencePart1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTypeReferencePartPrevious(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTypeReferencePartPrevious(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSTypeReferencePartPrevious, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTypeReferencePartPreviousConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTypeReferencePartPreviousConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSTypeReferencePartPreviousConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTypeReferencePartName(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTypeReferencePartName(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSTypeReferencePartName, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTypeReferencePartTypeParams(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTypeReferencePartTypeParams(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSTypeReferencePartTypeParams, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSTypeReferencePartNameConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSTypeReferencePartNameConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSTypeReferencePartNameConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSReExportDeclarationGetETSImportDeclarationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSReExportDeclarationGetETSImportDeclarationsConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSReExportDeclarationGetETSImportDeclarationsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSReExportDeclarationGetETSImportDeclarations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSReExportDeclarationGetETSImportDeclarations(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSReExportDeclarationGetETSImportDeclarations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSReExportDeclarationGetProgramPathConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSReExportDeclarationGetProgramPathConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(ETSReExportDeclarationGetProgramPathConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSPrimitiveType(KNativePointer context, KInt type) +{ + const auto _context = reinterpret_cast(context); + const auto _type = static_cast(type); + auto result = GetImpl()->CreateETSPrimitiveType(_context, _type); + return result; +} +KOALA_INTEROP_2(CreateETSPrimitiveType, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateETSPrimitiveType(KNativePointer context, KNativePointer original, KInt type) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _type = static_cast(type); + auto result = GetImpl()->UpdateETSPrimitiveType(_context, _original, _type); + return result; +} +KOALA_INTEROP_3(UpdateETSPrimitiveType, KNativePointer, KNativePointer, KNativePointer, KInt); + +KInt impl_ETSPrimitiveTypeGetPrimitiveTypeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSPrimitiveTypeGetPrimitiveTypeConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSPrimitiveTypeGetPrimitiveTypeConst, KInt, KNativePointer, KNativePointer); + +KNativePointer impl_TypeNodeAnnotations(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TypeNodeAnnotations(_context, _receiver, &length); + return new std::vector(result, result + length); +} +KOALA_INTEROP_2(TypeNodeAnnotations, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_TypeNodeAnnotationsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->TypeNodeAnnotationsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(TypeNodeAnnotationsConst, KNativePointer, KNativePointer, KNativePointer); + +void impl_TypeNodeSetAnnotations(KNativePointer context, KNativePointer receiver, KNativePointerArray annotations, KUInt annotationsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _annotations = reinterpret_cast(annotations); + const auto _annotationsSequenceLength = static_cast(annotationsSequenceLength); + GetImpl()->TypeNodeSetAnnotations(_context, _receiver, _annotations, _annotationsSequenceLength); + return ; +} +KOALA_INTEROP_V4(TypeNodeSetAnnotations, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_CreateNewExpression(KNativePointer context, KNativePointer callee, KNativePointerArray _arguments, KUInt _argumentsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _callee = reinterpret_cast(callee); + const auto __arguments = reinterpret_cast(_arguments); + const auto __argumentsSequenceLength = static_cast(_argumentsSequenceLength); + auto result = GetImpl()->CreateNewExpression(_context, _callee, __arguments, __argumentsSequenceLength); + return result; +} +KOALA_INTEROP_4(CreateNewExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateNewExpression(KNativePointer context, KNativePointer original, KNativePointer callee, KNativePointerArray _arguments, KUInt _argumentsSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _callee = reinterpret_cast(callee); + const auto __arguments = reinterpret_cast(_arguments); + const auto __argumentsSequenceLength = static_cast(_argumentsSequenceLength); + auto result = GetImpl()->UpdateNewExpression(_context, _original, _callee, __arguments, __argumentsSequenceLength); + return result; +} +KOALA_INTEROP_5(UpdateNewExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt); + +KNativePointer impl_NewExpressionCalleeConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->NewExpressionCalleeConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(NewExpressionCalleeConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_NewExpressionArgumentsConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + std::size_t length; + auto result = GetImpl()->NewExpressionArgumentsConst(_context, _receiver, &length); + return (void*)new std::vector(result, result + length); +} +KOALA_INTEROP_2(NewExpressionArgumentsConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSParameterProperty(KNativePointer context, KInt accessibility, KNativePointer parameter, KBoolean readonly_arg, KBoolean isStatic, KBoolean isExport) +{ + const auto _context = reinterpret_cast(context); + const auto _accessibility = static_cast(accessibility); + const auto _parameter = reinterpret_cast(parameter); + const auto _readonly_arg = static_cast(readonly_arg); + const auto _isStatic = static_cast(isStatic); + const auto _isExport = static_cast(isExport); + auto result = GetImpl()->CreateTSParameterProperty(_context, _accessibility, _parameter, _readonly_arg, _isStatic, _isExport); + return result; +} +KOALA_INTEROP_6(CreateTSParameterProperty, KNativePointer, KNativePointer, KInt, KNativePointer, KBoolean, KBoolean, KBoolean); + +KNativePointer impl_UpdateTSParameterProperty(KNativePointer context, KNativePointer original, KInt accessibility, KNativePointer parameter, KBoolean readonly_arg, KBoolean isStatic, KBoolean isExport) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _accessibility = static_cast(accessibility); + const auto _parameter = reinterpret_cast(parameter); + const auto _readonly_arg = static_cast(readonly_arg); + const auto _isStatic = static_cast(isStatic); + const auto _isExport = static_cast(isExport); + auto result = GetImpl()->UpdateTSParameterProperty(_context, _original, _accessibility, _parameter, _readonly_arg, _isStatic, _isExport); + return result; +} +KOALA_INTEROP_7(UpdateTSParameterProperty, KNativePointer, KNativePointer, KNativePointer, KInt, KNativePointer, KBoolean, KBoolean, KBoolean); + +KInt impl_TSParameterPropertyAccessibilityConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSParameterPropertyAccessibilityConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSParameterPropertyAccessibilityConst, KInt, KNativePointer, KNativePointer); + +KBoolean impl_TSParameterPropertyReadonlyConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSParameterPropertyReadonlyConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSParameterPropertyReadonlyConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSParameterPropertyIsStaticConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSParameterPropertyIsStaticConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSParameterPropertyIsStaticConst, KBoolean, KNativePointer, KNativePointer); + +KBoolean impl_TSParameterPropertyIsExportConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSParameterPropertyIsExportConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(TSParameterPropertyIsExportConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_TSParameterPropertyParameterConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->TSParameterPropertyParameterConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(TSParameterPropertyParameterConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateETSWildcardType(KNativePointer context, KNativePointer typeReference, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _typeReference = reinterpret_cast(typeReference); + const auto _flags = static_cast(flags); + auto result = GetImpl()->CreateETSWildcardType(_context, _typeReference, _flags); + return result; +} +KOALA_INTEROP_3(CreateETSWildcardType, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_UpdateETSWildcardType(KNativePointer context, KNativePointer original, KNativePointer typeReference, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _typeReference = reinterpret_cast(typeReference); + const auto _flags = static_cast(flags); + auto result = GetImpl()->UpdateETSWildcardType(_context, _original, _typeReference, _flags); + return result; +} +KOALA_INTEROP_4(UpdateETSWildcardType, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KInt); + +KNativePointer impl_ETSWildcardTypeTypeReference(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSWildcardTypeTypeReference(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSWildcardTypeTypeReference, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_ETSWildcardTypeTypeReferenceConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSWildcardTypeTypeReferenceConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSWildcardTypeTypeReferenceConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateTSThisType(KNativePointer context) +{ + const auto _context = reinterpret_cast(context); + auto result = GetImpl()->CreateTSThisType(_context); + return result; +} +KOALA_INTEROP_1(CreateTSThisType, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTSThisType(KNativePointer context, KNativePointer original) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + auto result = GetImpl()->UpdateTSThisType(_context, _original); + return result; +} +KOALA_INTEROP_2(UpdateTSThisType, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_CreateInterfaceDecl(KNativePointer context, KStringPtr& name) +{ + const auto _context = reinterpret_cast(context); + const auto _name = getStringCopy(name); + auto result = GetImpl()->CreateInterfaceDecl(_context, _name); + return result; +} +KOALA_INTEROP_2(CreateInterfaceDecl, KNativePointer, KNativePointer, KStringPtr); + +KNativePointer impl_CreateInterfaceDecl1(KNativePointer context, KStringPtr& name, KNativePointer declNode) +{ + const auto _context = reinterpret_cast(context); + const auto _name = getStringCopy(name); + const auto _declNode = reinterpret_cast(declNode); + auto result = GetImpl()->CreateInterfaceDecl1(_context, _name, _declNode); + return result; +} +KOALA_INTEROP_3(CreateInterfaceDecl1, KNativePointer, KNativePointer, KStringPtr, KNativePointer); + +KNativePointer impl_CreateFunctionDecl(KNativePointer context, KStringPtr& name, KNativePointer node) +{ + const auto _context = reinterpret_cast(context); + const auto _name = getStringCopy(name); + const auto _node = reinterpret_cast(node); + auto result = GetImpl()->CreateFunctionDecl(_context, _name, _node); + return result; +} +KOALA_INTEROP_3(CreateFunctionDecl, KNativePointer, KNativePointer, KStringPtr, KNativePointer); + diff --git a/koala-wrapper/package.json b/koala-wrapper/package.json new file mode 100644 index 000000000..397203cec --- /dev/null +++ b/koala-wrapper/package.json @@ -0,0 +1,81 @@ +{ + "name": "@koalaui/libarkts", + "version": "1.0.0", + "private": true, + "main": "./build/lib/es2panda.js", + "types": "./build/src/arkts-api/index.d.ts", + "exports": { + ".": "./build/lib/arkts-api/index.js", + "./build/lib/es2panda": "./build/lib/es2panda.js" + }, + "files": [ + "./build/*" + ], + "config": { + "gen_version": "3.0.19" + }, + "devDependencies": { + "@babel/cli": "7.20.7", + "@babel/core": "7.20.12", + "@babel/plugin-proposal-class-properties": "7.18.6", + "@babel/preset-env": "7.20.2", + "@babel/preset-typescript": "7.18.6", + "@babel/runtime": "7.20.13", + "@tsconfig/recommended": "1.0.8", + "node-addon-api": "^8.3.0", + "typescript": "^5.0.0", + "@types/node": "^18.0.0" + }, + "imports": { + "#koalaui/interop": { + "default": "./koalaui/interop/dist/lib/src/interop/index.js" + }, + "#koalaui/common": { + "default": "./koalaui/common/dist/lib/src/index.js" + }, + "#koalaui/compat": { + "default": "./koalaui/compat/dist/src/index.js" + }, + "#common/wrappers": { + "browser": "./koalaui/interop/dist/lib/src/wasm/wrappers/index.js", + "node": "./koalaui/interop/dist/lib/src/napi/wrappers/index.js" + }, + "#common/wrappers/*": { + "browser": "./koalaui/interop/dist/lib/src/wasm/wrappers/*.js", + "node": "./koalaui/interop/dist/lib/src/napi/wrappers/*.js", + "default": "./koalaui/interop/dist/lib/src/napi/wrappers/*.js" + }, + "#platform": { + "ark": "./koalaui/compat/dist/src/ohos/index.js", + "ios": "./koalaui/compat/dist/src/typescript/index.js", + "browser": "./koalaui/compat/dist/src/typescript/index.js", + "node": "./koalaui/compat/dist/src/typescript/index.js", + "default": "./koalaui/compat/dist/src/typescript/index.js" + } + }, + "scripts": { + "clean": "rimraf build native/build*", + "compile:meson": "cd native && meson setup build && meson compile -C build", + "copy:.node": "mkdir -p ./build/lib/native/ && cp ./native/build/es2panda.node ./build/lib/native", + "compile:native": "npm run compile:meson && npm run copy:.node", + "compile:src": "./node_modules/.bin/babel ./src --out-dir build/lib --extensions .ts", + "compile:types": "npx tsc -p ./tsconfig.json --emitDeclarationOnly", + "compile:src:tsc": "tsc -p ./tsconfig.json", + "compile:tsc": "npm run compile:src && npm run compile:types", + "compile": "npm run compile:native && npm run compile:src && npm run compile:types", + "compile:plugins": "npx ets-tsc -p plugins/tsconfig.json", + "restart": "PANDA_SDK_PATH=../../incremental/tools/panda/node_modules/@panda/sdk node . --file ./plugins/input/main.sts --output ./build/abc/main.abc --dump-plugin-ast --arktsconfig ./arktsconfig.json --restart-stages", + "direct": "PANDA_SDK_PATH=../../incremental/tools/panda/node_modules/@panda/sdk node . --file ./plugins/input/no-import-no-struct.sts --output ./build/abc/no-import-no-struct.abc --dump-plugin-ast --arktsconfig ./arktsconfig-print-only.json", + "memo": "PANDA_SDK_PATH=../../incremental/tools/panda/node_modules/@panda/sdk node . --file ./plugins/input/memo.sts --output ./build/abc/memo.abc --dump-plugin-ast --arktsconfig ./arktsconfig-memo.json --restart-stages", + "run": "npm run compile && npm run compile:plugins && npm run restart", + "run:memo": "npm run compile && npm run compile:plugins && npm run compile --prefix ../memo-plugin && npm run memo", + "run:abc": "../../incremental/tools/panda/node_modules/@panda/sdk/linux_host_tools/bin/ark --load-runtimes=ets --boot-panda-files=../../incremental/tools/panda/node_modules/@panda/sdk/ets/etsstdlib.abc ./main.abc main.ETSGLOBAL::main", + "compile:playground": "cd playground && meson setup build && meson compile -C build", + "run:playground": "npm run compile:playground && ./playground/build/playground.out", + "panda:sdk:clean": "cd ../../incremental/tools/panda && rimraf node_modules", + "panda:sdk:install": "cd ../../incremental/tools/panda && npm run panda:sdk:install", + "panda:sdk:reinstall": "npm run panda:sdk:clean && npm run panda:sdk:install", + "regenerate": "npx @idlizer/libarkts-gen@$npm_package_config_gen_version --input-file $npm_package_config_input_file --output-dir ../ --files bridges,nativeModule", + "reinstall:regenerate": "npm run panda:sdk:reinstall && npm run regenerate" + } +} diff --git a/koala-wrapper/src/Es2pandaEnums.ts b/koala-wrapper/src/Es2pandaEnums.ts new file mode 100644 index 000000000..bf820a759 --- /dev/null +++ b/koala-wrapper/src/Es2pandaEnums.ts @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2022-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. + */ + +// HANDWRITTEN (for now) + +export enum Es2pandaAstNodeType { + AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, + AST_NODE_TYPE_ANNOTATION_DECLARATION, + AST_NODE_TYPE_ANNOTATION_USAGE, + AST_NODE_TYPE_ASSERT_STATEMENT, + AST_NODE_TYPE_AWAIT_EXPRESSION, + AST_NODE_TYPE_BIGINT_LITERAL, + AST_NODE_TYPE_BINARY_EXPRESSION, + AST_NODE_TYPE_BLOCK_STATEMENT, + AST_NODE_TYPE_BOOLEAN_LITERAL, + AST_NODE_TYPE_BREAK_STATEMENT, + AST_NODE_TYPE_CALL_EXPRESSION, + AST_NODE_TYPE_CATCH_CLAUSE, + AST_NODE_TYPE_CHAIN_EXPRESSION, + AST_NODE_TYPE_CHAR_LITERAL, + AST_NODE_TYPE_CLASS_DEFINITION, + AST_NODE_TYPE_CLASS_DECLARATION, + AST_NODE_TYPE_CLASS_EXPRESSION, + AST_NODE_TYPE_CLASS_PROPERTY, + AST_NODE_TYPE_CLASS_STATIC_BLOCK, + AST_NODE_TYPE_CONDITIONAL_EXPRESSION, + AST_NODE_TYPE_CONTINUE_STATEMENT, + AST_NODE_TYPE_DEBUGGER_STATEMENT, + AST_NODE_TYPE_DECORATOR, + AST_NODE_TYPE_DIRECT_EVAL, + AST_NODE_TYPE_DO_WHILE_STATEMENT, + AST_NODE_TYPE_EMPTY_STATEMENT, + AST_NODE_TYPE_EXPORT_ALL_DECLARATION, + AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION, + AST_NODE_TYPE_EXPORT_NAMED_DECLARATION, + AST_NODE_TYPE_EXPORT_SPECIFIER, + AST_NODE_TYPE_EXPRESSION_STATEMENT, + AST_NODE_TYPE_FOR_IN_STATEMENT, + AST_NODE_TYPE_FOR_OF_STATEMENT, + AST_NODE_TYPE_FOR_UPDATE_STATEMENT, + AST_NODE_TYPE_FUNCTION_DECLARATION, + AST_NODE_TYPE_FUNCTION_EXPRESSION, + AST_NODE_TYPE_IDENTIFIER, + AST_NODE_TYPE_DUMMYNODE, + AST_NODE_TYPE_IF_STATEMENT, + AST_NODE_TYPE_IMPORT_DECLARATION, + AST_NODE_TYPE_IMPORT_EXPRESSION, + AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER, + AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER, + AST_NODE_TYPE_IMPORT_SPECIFIER, + AST_NODE_TYPE_LABELLED_STATEMENT, + AST_NODE_TYPE_MEMBER_EXPRESSION, + AST_NODE_TYPE_META_PROPERTY_EXPRESSION, + AST_NODE_TYPE_METHOD_DEFINITION, + AST_NODE_TYPE_NAMED_TYPE, + AST_NODE_TYPE_NEW_EXPRESSION, + AST_NODE_TYPE_NULL_LITERAL, + AST_NODE_TYPE_UNDEFINED_LITERAL, + AST_NODE_TYPE_NUMBER_LITERAL, + AST_NODE_TYPE_OMITTED_EXPRESSION, + AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION, + AST_NODE_TYPE_PROPERTY, + AST_NODE_TYPE_REGEXP_LITERAL, + AST_NODE_TYPE_REEXPORT_STATEMENT, + AST_NODE_TYPE_RETURN_STATEMENT, + AST_NODE_TYPE_SCRIPT_FUNCTION, + AST_NODE_TYPE_SEQUENCE_EXPRESSION, + AST_NODE_TYPE_STRING_LITERAL, + AST_NODE_TYPE_ETS_NULL_TYPE, + AST_NODE_TYPE_ETS_UNDEFINED_TYPE, + AST_NODE_TYPE_ETS_NEVER_TYPE, + AST_NODE_TYPE_ETS_STRING_LITERAL_TYPE, + AST_NODE_TYPE_ETS_FUNCTION_TYPE, + AST_NODE_TYPE_ETS_WILDCARD_TYPE, + AST_NODE_TYPE_ETS_PRIMITIVE_TYPE, + AST_NODE_TYPE_ETS_PACKAGE_DECLARATION, + AST_NODE_TYPE_ETS_CLASS_LITERAL, + AST_NODE_TYPE_ETS_TYPE_REFERENCE, + AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, + AST_NODE_TYPE_ETS_UNION_TYPE, + AST_NODE_TYPE_ETS_KEYOF_TYPE, + AST_NODE_TYPE_ETS_LAUNCH_EXPRESSION, + AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION, + AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION, + AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION, + AST_NODE_TYPE_ETS_IMPORT_DECLARATION, + AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, + AST_NODE_TYPE_ETS_TUPLE, + AST_NODE_TYPE_ETS_MODULE, + AST_NODE_TYPE_SUPER_EXPRESSION, + AST_NODE_TYPE_STRUCT_DECLARATION, + AST_NODE_TYPE_SWITCH_CASE_STATEMENT, + AST_NODE_TYPE_SWITCH_STATEMENT, + AST_NODE_TYPE_TS_ENUM_DECLARATION, + AST_NODE_TYPE_TS_ENUM_MEMBER, + AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE, + AST_NODE_TYPE_TS_NUMBER_KEYWORD, + AST_NODE_TYPE_TS_ANY_KEYWORD, + AST_NODE_TYPE_TS_STRING_KEYWORD, + AST_NODE_TYPE_TS_BOOLEAN_KEYWORD, + AST_NODE_TYPE_TS_VOID_KEYWORD, + AST_NODE_TYPE_TS_UNDEFINED_KEYWORD, + AST_NODE_TYPE_TS_UNKNOWN_KEYWORD, + AST_NODE_TYPE_TS_OBJECT_KEYWORD, + AST_NODE_TYPE_TS_BIGINT_KEYWORD, + AST_NODE_TYPE_TS_NEVER_KEYWORD, + AST_NODE_TYPE_TS_NON_NULL_EXPRESSION, + AST_NODE_TYPE_TS_NULL_KEYWORD, + AST_NODE_TYPE_TS_ARRAY_TYPE, + AST_NODE_TYPE_TS_UNION_TYPE, + AST_NODE_TYPE_TS_TYPE_LITERAL, + AST_NODE_TYPE_TS_PROPERTY_SIGNATURE, + AST_NODE_TYPE_TS_METHOD_SIGNATURE, + AST_NODE_TYPE_TS_SIGNATURE_DECLARATION, + AST_NODE_TYPE_TS_PARENT_TYPE, + AST_NODE_TYPE_TS_LITERAL_TYPE, + AST_NODE_TYPE_TS_INFER_TYPE, + AST_NODE_TYPE_TS_CONDITIONAL_TYPE, + AST_NODE_TYPE_TS_IMPORT_TYPE, + AST_NODE_TYPE_TS_INTERSECTION_TYPE, + AST_NODE_TYPE_TS_MAPPED_TYPE, + AST_NODE_TYPE_TS_MODULE_BLOCK, + AST_NODE_TYPE_TS_THIS_TYPE, + AST_NODE_TYPE_TS_TYPE_OPERATOR, + AST_NODE_TYPE_TS_TYPE_PARAMETER, + AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION, + AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION, + AST_NODE_TYPE_TS_TYPE_PREDICATE, + AST_NODE_TYPE_TS_PARAMETER_PROPERTY, + AST_NODE_TYPE_TS_MODULE_DECLARATION, + AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION, + AST_NODE_TYPE_TS_FUNCTION_TYPE, + AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE, + AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION, + AST_NODE_TYPE_TS_TYPE_REFERENCE, + AST_NODE_TYPE_TS_QUALIFIED_NAME, + AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE, + AST_NODE_TYPE_TS_INTERFACE_DECLARATION, + AST_NODE_TYPE_TS_INTERFACE_BODY, + AST_NODE_TYPE_TS_INTERFACE_HERITAGE, + AST_NODE_TYPE_TS_TUPLE_TYPE, + AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER, + AST_NODE_TYPE_TS_INDEX_SIGNATURE, + AST_NODE_TYPE_TS_TYPE_QUERY, + AST_NODE_TYPE_TS_AS_EXPRESSION, + AST_NODE_TYPE_TS_CLASS_IMPLEMENTS, + AST_NODE_TYPE_TS_TYPE_ASSERTION, + AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION, + AST_NODE_TYPE_TEMPLATE_ELEMENT, + AST_NODE_TYPE_TEMPLATE_LITERAL, + AST_NODE_TYPE_THIS_EXPRESSION, + AST_NODE_TYPE_TYPEOF_EXPRESSION, + AST_NODE_TYPE_THROW_STATEMENT, + AST_NODE_TYPE_TRY_STATEMENT, + AST_NODE_TYPE_UNARY_EXPRESSION, + AST_NODE_TYPE_UPDATE_EXPRESSION, + AST_NODE_TYPE_VARIABLE_DECLARATION, + AST_NODE_TYPE_VARIABLE_DECLARATOR, + AST_NODE_TYPE_WHILE_STATEMENT, + AST_NODE_TYPE_YIELD_EXPRESSION, + AST_NODE_TYPE_OPAQUE_TYPE_NODE, + AST_NODE_TYPE_BLOCK_EXPRESSION, + AST_NODE_TYPE_ERROR_TYPE_NODE, + AST_NODE_TYPE_ARRAY_EXPRESSION, + AST_NODE_TYPE_ARRAY_PATTERN, + AST_NODE_TYPE_ASSIGNMENT_EXPRESSION, + AST_NODE_TYPE_ASSIGNMENT_PATTERN, + AST_NODE_TYPE_OBJECT_EXPRESSION, + AST_NODE_TYPE_OBJECT_PATTERN, + AST_NODE_TYPE_SPREAD_ELEMENT, + AST_NODE_TYPE_REST_ELEMENT, +} diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts new file mode 100644 index 000000000..748275bf5 --- /dev/null +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -0,0 +1,661 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + KNativePointer as KPtr, + KInt, + KBoolean, + KNativePointer, + registerNativeModuleLibraryName, + loadNativeModuleLibrary, + KDouble +} from "@koalaui/interop" +import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from "./generated/Es2pandaNativeModule" +import * as path from "path" + +// TODO: this type should be in interop +export type KPtrArray = BigUint64Array + +export class Es2pandaNativeModule { + _ClassDefinitionSuper(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateTSInterfaceDeclaration(_context: KPtr, _extends: KPtrArray, _extendsLen: KInt, _id: KPtr, _typeParams: KPtr, _body: KPtr, _isStatic: KBoolean, _isExternal: KBoolean): KPtr { + throw new Error("Not implemented") + } + _CreateTSTypeParameterInstantiation(context: KPtr, params: KPtrArray, paramsLen: KInt): KPtr { + throw new Error("Not implemented") + } + _ClassElementKey(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ClassElementValue(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _AnnotationUsageIrExpr(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _AnnotationUsageIrPropertiesConst(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _AnnotationAllowedAnnotations(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _AnnotationAllowedAnnotationsConst(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeRebind(context: KPtr, node: KPtr): void { + throw new Error("Not implemented") + } + _AstNodeRecheck(context: KPtr, node: KPtr): void { + throw new Error("Not implemented") + } + + _ContextState(context: KPtr): KInt { + throw new Error("Not implemented") + } + _ContextErrorMessage(context: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeChildren(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ETSParserCreateExpression(context: KPtr, sourceCode: String, flags: KInt): KPtr { + throw new Error("Not implemented") + } + _AstNodeDumpModifiers(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateAstDumper(context: KPtr, node: KPtr, source: String): KPtr { + throw new Error("Not implemented") + } + _AstDumperModifierToString(context: KPtr, dumper: KPtr, flags: KInt): KPtr { + throw new Error("Not implemented") + } + + _CreateConfig(argc: number, argv: string[]): KPtr { + throw new Error("Not implemented") + } + _DestroyConfig(config: KPtr): void { + throw new Error("Not implemented") + } + _CreateContextFromString(config: KPtr, source: String, filename: String): KPtr { + throw new Error("Not implemented") + } + _CreateContextFromFile(config: KPtr, filename: String): KPtr { + throw new Error("Not implemented") + } + _DestroyContext(context: KPtr): void { + throw new Error("Not implemented") + } + _ProceedToState(context: KPtr, state: number): void { + throw new Error("Not implemented") + } + _ContextProgram(context: KPtr): KPtr { + throw new Error("Not implemented") + } + _ProgramAst(context: KPtr, program: KPtr): KPtr { + throw new Error("Not implemented") + } + _CheckerStartChecker(context: KPtr): KBoolean { + throw new Error("Not implemented") + } + _VarBinderIdentifierAnalysis(context: KPtr): void { + throw new Error("Not implemented") + } + _VarBinderInitTopScope(context: KPtr): void { + throw new Error("Not implemented") + } + _VarBinderSetGenStdLib(context: KPtr, genStdLibT: KBoolean): void { + throw new Error("Not implemented") + } + _SourceFileGetChildren(node: KPtr): KPtr { + throw new Error("Not implemented") + } + _BlockGetStatements(node: KPtr): KPtr { + throw new Error("Not implemented") + } + _FunctionDeclarationIsAnonymousConst(context: KPtr, node: KPtr): KBoolean { + throw new Error("Not implemented") + } + _ExpressionStatementGetExpression(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _CallExpressionArguments(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _CallExpressionCallee(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _IdentifierGetText(node: KPtr): KPtr { + throw new Error("Not implemented") + } + _IdentifierIsPrivateIdentConst(context: KPtr, node: KPtr): KBoolean { + throw new Error("Not implemented") + } + _PropertyAccessExpressionGetExpression(node: KPtr): KPtr { + throw new Error("Not implemented") + } + _PropertyAccessExpressionGetName(node: KPtr): KPtr { + throw new Error("Not implemented") + } + + _FunctionDeclarationFunction(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionSignature(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionParams(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionId(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionBody(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionAnnotations(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionSetIdent(context: KPtr, ast: KPtr, id: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionSetSignature(context: KPtr, ast: KPtr, signature: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionSetBody(context: KPtr, ast: KPtr, body: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionSetScope(context: KPtr, ast: KPtr, scope: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionSetAnnotations(context: KPtr, ast: KPtr, annotations: KPtrArray, annotationsLen: KInt): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionDeclareConst(context: KPtr, node: KPtr): KBoolean { + throw new Error("Not implemented") + } + _ScriptFunctionFlagsConst(context: KPtr, node: KPtr): KInt { + throw new Error("Not implemented") + } + _ScriptFunctionTypeParams(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionReturnTypeAnnotation(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ScriptFunctionAddFlag(context: KPtr, node: KPtr, flags: KInt): void { + throw new Error("Not implemented") + } + _ClassPropertyAnnotations(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _ClassPropertySetAnnotations(context: KPtr, ast: KPtr, annotations: KPtrArray, annotationsLen: KInt): KPtr { + throw new Error("Not implemented") + } + _UpdateBlockStatement(context: KPtr, original: KPtr, statementList: KPtrArray, statementListLen: KInt): KPtr { + throw new Error("Not implemented") + } + _BlockStatementSetScope(context: KPtr, node: KPtr, scope: KPtrArray): void { + throw new Error("Not implemented") + } + _CreateIdentifier1(context: KPtr, name: String): KPtr { + throw new Error("Not implemented") + } + _CreateIdentifier2(context: KPtr, name: String, type_annotation: KPtr): KPtr { + throw new Error("Not implemented") + } + _IdentifierSetName(context: KPtr, node: KPtr, name: String): void { + throw new Error("Not implemented") + } + _IdentifierIdentifierFlags(context: KPtr, node: KPtr): KInt { + throw new Error("Not implemented") + } + _CreateFunctionDeclaration(context: KPtr, func: KPtr, annotations: KPtrArray, annotationsLen: KInt, isAnon: KBoolean): KPtr { + throw new Error("Not implemented") + } + _UpdateFunctionDeclaration(context: KPtr, node: KPtr, annotations: KPtrArray, annotationsLen: KInt, func: KPtr, isAnon: KBoolean): KPtr { + throw new Error("Not implemented") + } + _CreateReturnStatement1(context: KPtr, argument: KPtr): KPtr { + throw new Error("Not implemented") + } + _ReturnStatementArgument(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateIfStatement(context: KPtr, test: KPtr, consequent: KPtr, alternate: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateBinaryExpression(context: KPtr, left: KPtr, right: KPtr, operatorType: KInt): KPtr { + throw new Error("Not implemented") + } + _CreateAssignmentExpression(context: KPtr, left: KPtr, right: KPtr, assignmentOperator: KInt): KPtr { + throw new Error("Not implemented") + } + _CreateMethodDefinition(context: KPtr, kind: KInt, key: KPtr, value: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr { + throw new Error("Not implemented") + } + _CreateClassProperty(context: KPtr, key: KPtr, value: KPtr, typeAnnotation: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr { + throw new Error("Not implemented") + } + _CreateETSImportDeclaration(context: KPtr, source: KPtr, specifiers: KPtrArray, specifiersLen: KInt, importKind: KInt): KNativePointer { + throw new Error("Not implemented") + } + _ETSImportDeclarationSourceConst(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ETSImportDeclarationResolvedSource(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ETSImportDeclarationHasDeclConst(context: KPtr, node: KPtr): KBoolean { + throw new Error("Not implemented") + } + _CreateImportSource(context: KPtr, source: KPtr, resolvedSource: KPtr, hasDecl: KBoolean): KNativePointer { + throw new Error("Not implemented") + } + _CreateImportSpecifier(context: KPtr, imported: KPtr, local: KPtr): KNativePointer { + throw new Error("Not implemented") + } + + _CreateFunctionSignature(context: KPtr, typeParams: KPtr, params: KPtrArray, paramsLen: KInt, returnTypeAnnotation: KPtr, hasReceiver: KBoolean): KPtr { + throw new Error("Not implemented") + } + _CreateScriptFunction(context: KPtr, databody: KPtr, datasignature: KPtr, datafuncFlags: KInt, dataflags: KInt): KPtr { + throw new Error("Not implemented") + } + _UpdateScriptFunction(context: KPtr, original: KPtr, databody: KPtr, datasignature: KPtr, datafuncFlags: KInt, dataflags: KInt, datadeclare: KBoolean): KPtr { + throw new Error("Not implemented") + } + _CreateBlockStatement(context: KPtr, statementList: KPtrArray, statementListLen: KInt): KPtr { + throw new Error("Not implemented") + } + _AstNodeScopeConst(context: KPtr, ast: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeParent(context: KPtr, ast: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeSetParent(context: KPtr, ast: KPtr, parent: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeClone(context: KPtr, ast: KPtr, parent: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeModifiers(context: KPtr, ast: KPtr): KInt { + throw new Error("Not implemented") + } + _AstNodeAddModifier(context: KPtr, ast: KPtr, flags: KInt): void { + throw new Error("Not implemented") + } + _AstNodeClearModifier(context: KPtr, ast: KPtr, flags: KInt): void { + throw new Error("Not implemented") + } + _AstNodeVariableConst(context: KPtr, ast: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeTypeConst(context: KPtr, ast: KPtr): KInt { + throw new Error("Not implemented") + } + _FunctionSignatureTypeParams(context: KPtr, ast: KPtr): KPtr { + throw new Error("Not implemented") + } + _FunctionSignatureReturnType(context: KPtr, ast: KPtr): KPtr { + throw new Error("Not implemented") + } + _FunctionSignatureParamsConst(context: KPtr, ast: KPtr, returnTypeLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _UpdateIdentifier1(context: KPtr, ast: KPtr, name: string): KPtr { + throw new Error("Not implemented") + } + _UpdateIdentifier2(context: KPtr, ast: KPtr, name: string, typeAnnotation: KPtr): KPtr { + throw new Error("Not implemented") + } + _UpdateMethodDefinition(context: KPtr, node: KPtr, kind: KInt, key: KPtr, value: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr { + throw new Error("Not implemented") + } + _MethodDefinitionFunction(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _MethodDefinitionKindConst(context: KPtr, node: KPtr): KInt { + throw new Error("Not implemented") + } + + _CreateMemberExpression(context: KPtr, object: KPtr, property: KPtr, kind: KInt, computed: KBoolean, optional: KBoolean): KPtr { + throw new Error("Not implemented") + } + _UpdateMemberExpression(context: KPtr, node: KPtr, object: KPtr, property: KPtr, kind: KInt, computed: KBoolean, optional: KBoolean): KPtr { + throw new Error("Not implemented") + } + _MemberExpressionObject(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _MemberExpressionProperty(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _MemberExpressionKindConst(context: KPtr, node: KPtr): KInt { + throw new Error("Not implemented") + } + _CreateCallExpression(context: KPtr, callee: KPtr, args: KPtrArray, argsLen: KInt, typeParams: KPtr, optional: KBoolean, trailingComma: KBoolean): KPtr { + throw new Error("Not implemented") + } + _UpdateCallExpression(context: KPtr, node: KPtr, callee: KPtr, args: KPtrArray, argsLen: KInt, typeParams: KPtr, optional: KBoolean, trailingComma: KBoolean): KPtr { + throw new Error("Not implemented") + } + _CreateArrowFunctionExpression(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _FunctionExpressionFunction(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ArrowFunctionExpressionFunction(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ArrowFunctionExpressionCreateTypeAnnotation(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateFunctionExpression(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _UpdateFunctionExpression(context: KPtr, original: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + + _CreateExpressionStatement(context: KPtr, expr: KPtr): KPtr { + throw new Error("Not implemented") + } + _UpdateExpressionStatement(context: KPtr, node: KPtr, expr: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateETSParameterExpression(context: KPtr, identifier: KPtr, initializer: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateETSPrimitiveType(context: KPtr, type: KInt): KPtr { + throw new Error("Not implemented") + } + _ETSPrimitiveTypeGetPrimitiveTypeConst(context: KPtr, node: KNativePointer): KInt { + throw new Error("Not implemented") + } + _CreateETSTypeReference(context: KPtr, part: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateETSTypeReferencePart(context: KPtr, name: KPtr, typeParams: KPtr, prev: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateETSTypeReferencePart1(context: KPtr, name: KPtr): KPtr { + throw new Error("Not implemented") + } + _IsIdentifier(node: KPtr): KBoolean { + throw new Error("Not implemented") + } + _IdentifierName(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ETSParameterExpressionIdent(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ETSParameterExpressionAnnotations(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _ETSParameterExpressionSetAnnotations(context: KPtr, ast: KPtr, annotations: KPtrArray, annotationsLen: KInt): KPtr { + throw new Error("Not implemented") + } + _CreateTSTypeParameterDeclaration(context: KPtr, params: KPtrArray, paramsLen: KInt, requiredParams: KInt): KPtr { + throw new Error("Not implemented") + } + _TSTypeParameterDeclarationParamsConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateTSTypeParameter(context: KPtr, name: KPtr, constraint: KPtr, defaultType: KPtr): KPtr { + throw new Error("Not implemented") + } + _TSTypeParameterName(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + + _CreateTSUnionType(context: KPtr, types: KPtrArray, typesLen: KInt): KPtr { + throw new Error("Not implemented") + } + _TSUnionTypeTypesConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateETSUnionTypeIr(context: KPtr, types: KPtrArray, typesLen: KInt): KPtr { + throw new Error("Not implemented") + } + _ETSUnionTypeIrTypesConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr { + throw new Error("Not implemented") + } + + _CreateVariableDeclaration(context: KPtr, kind: KInt, declarators: KPtrArray, declaratorsLen: KInt): KPtr { + throw new Error("Not implemented") + } + _UpdateVariableDeclaration(context: KPtr, original: KPtr, kind: KInt, declarators: KPtrArray, declaratorsLen: KInt, declare: KBoolean): KPtr { + throw new Error("Not implemented") + } + _CreateVariableDeclarator(context: KPtr, flag: KInt, ident: KPtr): KPtr { + throw new Error("Not implemented") + } + _VariableDeclarationDeclaratorsConst(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _VariableDeclarationKindConst(context: KPtr, node: KPtr): KInt { + throw new Error("Not implemented") + } + _VariableDeclaratorId(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _VariableDeclaratorSetInit(context: KPtr, node: KPtr, init: KPtr): void { + throw new Error("Not implemented") + } + + _CreateStringLiteral(context: KPtr, string: string): KPtr { + throw new Error("Not implemented") + } + _CreateNumberLiteral(context: KPtr, value: KDouble): KPtr { + throw new Error("Not implemented") + } + _NumberLiteralStrConst(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _StringLiteralStrConst(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + + _BlockStatementStatements(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _BlockStatementSetStatements(context: KPtr, node: KPtr, statements: KPtrArray, statementsLen: KInt): void { + throw new Error("Not implemented") + } + _ClassDeclarationDefinition(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ClassDefinitionBody(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ClassDefinitionIdent(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _ClassDefinitionTypeParamsConst(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateETSStructDeclaration(context: KPtr, def: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateClassDeclaration(context: KPtr, def: KPtr): KPtr { + throw new Error("Not implemented") + } + _UpdateClassDeclaration(context: KPtr, original: KPtr, def: KPtr): KPtr { + throw new Error("Not implemented") + } + _CreateClassDefinition1(context: KPtr, ident: KPtr, body: KPtrArray, bodyLen: KInt, modifiers: KInt, flags: KInt): KPtr { + throw new Error("Not implemented") + } + _ClassDefinitionSetTypeParams(context: KPtr, ast: KPtr, typeParams: KPtr): void { + throw new Error("Not implemented") + } + _ClassDefinitionSetSuper(context: KPtr, ast: KPtr, superClass: KPtr): void { + throw new Error("Not implemented") + } + _UpdateClassDefinition1(context: KPtr, original: KPtr, ident: KPtr, body: KPtrArray, bodyLen: KInt, modifiers: KInt, flags: KInt): KPtr { + throw new Error("Not implemented") + } + _CreateETSFunctionTypeIr(context: KPtr, signature: KPtr, funcFlags: KInt): KPtr { + throw new Error("Not implemented") + } + _CreateSuperExpression(context: KPtr): KPtr { + throw new Error("Not implemented") + } + _UpdateSuperExpression(context: KPtr, original: KPtr): KPtr { + throw new Error("Not implemented") + } + + _IsProgram(context: KPtr, node: KPtr): KBoolean { + throw new Error("Not implemented") + } + _AstNodeDumpJSONConst(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeDumpEtsSrcConst(context: KPtr, node: KPtr): KPtr { + throw new Error("Not implemented") + } + _AstNodeUpdateChildren(context: KPtr, node: KPtr): void { + throw new Error("Not implemented") + } + _AstNodeUpdateAll(context: KPtr, node: KPtr): void { + throw new Error("Not implemented") + } + _AstNodeSetOriginalNode(context: KPtr, ast: KPtr, originalNode: KPtr): void { + throw new Error("Not implemented") + } + _AstNodeOriginalNodeConst(context: KPtr, ast: KPtr): KPtr { + throw new Error("Not implemented") + } + + _VarBinderSetProgram(context: KPtr): void { + throw new Error("Not implemented") + } + _VarBinderSetContext(context: KPtr): void { + throw new Error("Not implemented") + } + + _VariableDeclaration(context: KPtr, variable: KPtr): KPtr { + throw new Error("Not implemented") + } + _DeclNode(context: KPtr, decl: KPtr): KPtr { + throw new Error("Not implemented") + } + + _ScopeSetParent(context: KPtr, ast: KPtr, scope: KPtr): void { + throw new Error("Not implemented") + } + + _CallExpressionSignature(context: KPtr, classInstance: KPtr): KPtr { + throw new Error("Not implemented") + } + _SignatureFunction(context: KPtr, classInstance: KPtr): KPtr { + throw new Error("Not implemented") + } + _DeclarationFromIdentifier(context: KPtr, identifier: KPtr): KPtr { + throw new Error("Not implemented") + } + _IsTSInterfaceDeclaration(ast: KNativePointer): KBoolean { + throw new Error("Not implemented") + } + + _IsAnnotationDeclaration(ast: KNativePointer): KBoolean { + throw new Error("Not implemented") + } + + _IsAnnotationUsage(ast: KNativePointer): KBoolean { + throw new Error("Not implemented") + } + + _IsClassProperty(ast: KNativePointer): KBoolean { + throw new Error("Not implemented") + } + + _CreateAnnotationUsageIr(context: KPtr, ast: KPtr): KPtr { + throw new Error("Not implemented") + } + + _IsETSUnionType(ast: KPtr): KBoolean { + throw new Error("Not implemented") + } + + _IsETSFunctionType(ast: KPtr): KBoolean { + throw new Error("Not implemented") + } + _ProgramExternalSources(context: KNativePointer, instance: KNativePointer): KNativePointer { + throw new Error("Not implemented"); + } + + _ExternalSourceName(instance: KNativePointer): KNativePointer { + throw new Error("Not implemented"); + } + + _ExternalSourcePrograms(instance: KNativePointer): KNativePointer { + throw new Error("Not implemented"); + } + + _GenerateTsDeclarationsFromContext(config: KPtr, outputDeclEts: String, outputEts: String, exportAll: KBoolean): KPtr { + throw new Error("Not implemented"); + } + + _InsertETSImportDeclarationAndParse(context: KNativePointer, importDeclaration: KNativePointer): void { + throw new Error("Not implemented"); + } + + _ETSParserGetImportPathManager(context: KNativePointer): KPtr { + throw new Error("Not implemented"); + } + + _CreateSourcePosition(context: KNativePointer, index: KInt, line: KInt): KNativePointer { + throw new Error("Not implemented"); + } + _SourcePositionIndex(context: KNativePointer, instance: KNativePointer): KInt { + throw new Error("Not implemented"); + } + _SourcePositionLine(context: KNativePointer, instance: KNativePointer): KInt { + throw new Error("Not implemented"); + } + _CreateETSStringLiteralType(context: KNativePointer, str: String): KNativePointer { + throw new Error("Not implemented") + } + + _ClassDefinitionIsFromStructConst(context: KNativePointer, instance: KNativePointer): KBoolean { + throw new Error("Not implemented"); + } + + _ClassDefinitionSetFromStructModifier(context: KNativePointer, instance: KNativePointer): void { + throw new Error("Not implemented"); + } +} + +export function initEs2panda(): Es2pandaNativeModule { + registerNativeModuleLibraryName("NativeModule", path.resolve(__dirname, "../native/es2panda.node")) + const instance = new Es2pandaNativeModule() + loadNativeModuleLibrary("NativeModule", instance) + return instance +} + +export function initGeneratedEs2panda(): GeneratedEs2pandaNativeModule { + registerNativeModuleLibraryName("NativeModule", path.resolve(__dirname, "../native/es2panda.node")) + const instance = new GeneratedEs2pandaNativeModule() + // registerNativeModule("InteropNativeModule", NativeModule) + loadNativeModuleLibrary("NativeModule", instance) + return instance +} \ No newline at end of file diff --git a/koala-wrapper/src/InteropNativeModule.ts b/koala-wrapper/src/InteropNativeModule.ts new file mode 100644 index 000000000..2018b318c --- /dev/null +++ b/koala-wrapper/src/InteropNativeModule.ts @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + KNativePointer as KPtr, + KInt, + registerNativeModuleLibraryName, + loadNativeModuleLibrary +} from "@koalaui/interop" +import * as path from "path" + +export class InteropNativeModule { + _StringLength(ptr: KPtr): KInt { + throw new Error("Not implemented") + } + _StringData(ptr: KPtr, buffer: KPtr, length: KInt): void { + throw new Error("Not implemented") + } + _GetStringFinalizer(): KPtr { + throw new Error("Not implemented") + } + _InvokeFinalizer(ptr: KPtr, finalizer: KPtr): void { + throw new Error("Not implemented") + } + _GetPtrVectorSize(ptr: KPtr): KInt { + throw new Error("Not implemented") + } + _GetPtrVectorElement(ptr: KPtr, index: KInt): KPtr { + throw new Error("Not implemented") + } +} + +export function initInterop(): InteropNativeModule { + registerNativeModuleLibraryName("InteropNativeModule", path.join(__dirname, "../native/es2panda.node")) + const instance = new InteropNativeModule() + loadNativeModuleLibrary("InteropNativeModule", instance) + return instance +} diff --git a/koala-wrapper/src/arkts-api/class-by-peer.ts b/koala-wrapper/src/arkts-api/class-by-peer.ts new file mode 100644 index 000000000..8c5692dc9 --- /dev/null +++ b/koala-wrapper/src/arkts-api/class-by-peer.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Es2pandaAstNodeType } from "../Es2pandaEnums" +import { throwError } from "../utils" +import { global } from "./static/global" +import { KNativePointer, nullptr } from "@koalaui/interop" +import { AstNode, UnsupportedNode } from "./peers/AstNode" + +export const nodeByType = new Map([]) + +export function classByPeer(peer: KNativePointer): T { + if (peer === nullptr) { + throwError('classByPeer: peer is NULLPTR') + } + const type = global.generatedEs2panda._AstNodeTypeConst(global.context, peer) + const node = nodeByType.get(type) ?? UnsupportedNode + return new node(peer) as T +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts new file mode 100644 index 000000000..b368f8798 --- /dev/null +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -0,0 +1,567 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { updateNodeByNode } from "../utilities/private" +import { + ArrowFunctionExpression, + AssignmentExpression, + CallExpression, + ETSParameterExpression, + EtsScript, + ExpressionStatement, + FunctionDeclaration, + FunctionExpression, + IfStatement, + MethodDefinition, + NumberLiteral, + StructDeclaration, + VariableDeclaration, + VariableDeclarator, + ETSStringLiteralType +} from "../types" +import { MemberExpression } from "../to-be-generated/MemberExpression" +import { AstNode } from "../peers/AstNode" +import { + AnnotationUsage, + BinaryExpression, + BlockStatement, + ClassDeclaration, + ClassDefinition, + ClassProperty, + ConditionalExpression, + ETSImportDeclaration, + ETSFunctionType, + ETSPrimitiveType, + ETSTypeReference, + ETSTypeReferencePart, + ETSUndefinedType, + ETSUnionType, + FunctionSignature, + Identifier, + ImportSpecifier, + NullLiteral, + ReturnStatement, + ScriptFunction, + StringLiteral, + SuperExpression, + ThisExpression, + TSInterfaceBody, + TSInterfaceDeclaration, + TSNonNullExpression, + TSTypeParameter, + TSTypeParameterDeclaration, + TSTypeParameterInstantiation, + TypeNode, + UndefinedLiteral, + TSAsExpression, + TSTypeAliasDeclaration, + ChainExpression, + BlockExpression, + ETSNewClassInstanceExpression +} from "../../generated" +import { + Es2pandaModifierFlags +} from "../../generated/Es2pandaEnums" +import { + classPropertySetOptional, + hasModifierFlag +} from "../utilities/public" + +/** + * @deprecated + */ +function compose( + create: (...args: ARGS) => T, + update: (node: T, original: T) => T = updateNodeByNode +): (node: T, ...args: ARGS) => T { + return (node: T, ...args: ARGS) => update(create(...args), node); +} + +function updateThenAttach( + update: (original: T, ...args: ARGS) => T, + ...attachFuncs: ((node: T, original: T) => T)[] +): (node: T, ...args: ARGS) => T { + return (node: T, ...args: ARGS) => { + let _node: T = update(node, ...args); + attachFuncs.forEach((attach) => { + _node = attach(_node, node); + }) + return _node; + } +} + +function attachModifiers( + node: T, + original: T +): T { + node.modifiers = original.modifiers; + return node; +} + +export const factory = { + get createIdentifier() { + return Identifier.create2Identifier + }, + get updateIdentifier() { + return updateThenAttach( + Identifier.update2Identifier, + attachModifiers + ) + }, + get createCallExpression() { + return CallExpression.create + }, + get updateCallExpression() { + return updateThenAttach( + CallExpression.update, + attachModifiers + ) + }, + get createExpressionStatement() { + return ExpressionStatement.create + }, + get updateExpressionStatement() { + return updateThenAttach( + ExpressionStatement.update, + attachModifiers + ) + }, + get createMemberExpression() { + return MemberExpression.create + }, + get updateMemberExpression() { + return updateThenAttach( + MemberExpression.update, + attachModifiers + ) + }, + get createEtsScript() { + return EtsScript.createFromSource + }, + get updateEtsScript() { + return EtsScript.updateByStatements + }, + get createFunctionDeclaration() { + return FunctionDeclaration.create + }, + get updateFunctionDeclaration() { + return updateThenAttach( + FunctionDeclaration.update, + attachModifiers + ) + }, + get createBlock() { + return BlockStatement.createBlockStatement + }, + get updateBlock() { + return updateThenAttach( + BlockStatement.updateBlockStatement, + attachModifiers + ) + }, + get createArrowFunction() { + return ArrowFunctionExpression.create + }, + get updateArrowFunction() { + return updateThenAttach( + ArrowFunctionExpression.update, + attachModifiers, + (node: ArrowFunctionExpression, original: ArrowFunctionExpression) => node.setAnnotations(original.annotations) + ) + }, + get createScriptFunction() { + return ScriptFunction.createScriptFunction + }, + get updateScriptFunction() { + return updateThenAttach( + ScriptFunction.updateScriptFunction, + (node: ScriptFunction, original: ScriptFunction) => ( !!original.id ? node.setIdent(original.id) : node ), + (node: ScriptFunction, original: ScriptFunction) => node.setAnnotations(original.annotations) + ) + }, + get createStringLiteral() { + return StringLiteral.create1StringLiteral + }, + get updateStringLiteral() { + return updateThenAttach( + StringLiteral.update1StringLiteral, + attachModifiers + ) + }, + get create1StringLiteral() { + return StringLiteral.create1StringLiteral + }, + get update1StringLiteral() { + return updateThenAttach( + StringLiteral.update1StringLiteral, + attachModifiers + ) + }, + get createNumericLiteral() { + return NumberLiteral.create + }, + get updateNumericLiteral() { + return updateThenAttach( + compose(NumberLiteral.create), // TODO: No UpdateNumberLiteral, need to change this + attachModifiers + ) + }, + get createParameterDeclaration() { + return ETSParameterExpression.create + }, + get updateParameterDeclaration() { + return updateThenAttach( + ETSParameterExpression.update, + attachModifiers, + (node: ETSParameterExpression, original: ETSParameterExpression) => { node.annotations = original.annotations; return node; } + ) + }, + get createTypeParameter() { + return TSTypeParameter.createTSTypeParameter + }, + get updateTypeParameter() { + return updateThenAttach( + TSTypeParameter.updateTSTypeParameter, + attachModifiers + ) + }, + get createTypeParameterDeclaration() { + return TSTypeParameterDeclaration.createTSTypeParameterDeclaration + }, + get updateTypeParameterDeclaration() { + return updateThenAttach( + TSTypeParameterDeclaration.updateTSTypeParameterDeclaration, + attachModifiers + ) + }, + get createPrimitiveType() { + return ETSPrimitiveType.createETSPrimitiveType + }, + get updatePrimitiveType() { + return updateThenAttach( + ETSPrimitiveType.updateETSPrimitiveType, + attachModifiers + ) + }, + get createTypeReference() { + return ETSTypeReference.createETSTypeReference + }, + get updateTypeReference() { + return updateThenAttach( + ETSTypeReference.updateETSTypeReference, + attachModifiers + ) + }, + get createTypeReferencePart() { + return ETSTypeReferencePart.createETSTypeReferencePart + }, + get updateTypeReferencePart() { + return updateThenAttach( + ETSTypeReferencePart.updateETSTypeReferencePart, + attachModifiers + ) + }, + get createImportDeclaration() { + return ETSImportDeclaration.createETSImportDeclaration + }, + get updateImportDeclaration() { + return updateThenAttach( + ETSImportDeclaration.updateETSImportDeclaration, + attachModifiers + ) + }, + get createImportSpecifier() { + return ImportSpecifier.createImportSpecifier + }, + get updateImportSpecifier() { + return updateThenAttach( + ImportSpecifier.updateImportSpecifier, + attachModifiers + ) + }, + get createVariableDeclaration() { + return VariableDeclaration.create + }, + get updateVariableDeclaration() { + return updateThenAttach( + VariableDeclaration.update, + attachModifiers + ) + }, + get createVariableDeclarator() { + return VariableDeclarator.create + }, + get updateVariableDeclarator() { + return updateThenAttach( + VariableDeclarator.update, + attachModifiers + ) + }, + get createUnionType() { + return ETSUnionType.createETSUnionType + }, + get updateUnionType() { + return updateThenAttach( + ETSUnionType.updateETSUnionType, + attachModifiers + ) + }, + get createReturnStatement() { + return ReturnStatement.create1ReturnStatement + }, + get updateReturnStatement() { + return updateThenAttach( + ReturnStatement.update1ReturnStatement, + attachModifiers + ) + }, + get createIfStatement() { + return IfStatement.create + }, + get updateIfStatement() { + return updateThenAttach( + IfStatement.update, + attachModifiers + ) + }, + get createBinaryExpression() { + return BinaryExpression.createBinaryExpression + }, + get updateBinaryExpression() { + return updateThenAttach( + BinaryExpression.updateBinaryExpression, + attachModifiers + ) + }, + get createClassDeclaration() { + return ClassDeclaration.createClassDeclaration + }, + get updateClassDeclaration() { + return updateThenAttach( + ClassDeclaration.updateClassDeclaration, + attachModifiers + ) + }, + get createStructDeclaration() { + return StructDeclaration.create + }, + get updateStructDeclaration() { + return updateThenAttach( + StructDeclaration.update, + attachModifiers + ) + }, + get createClassDefinition() { + return ClassDefinition.createClassDefinition + }, + get updateClassDefinition() { + return updateThenAttach( + ClassDefinition.updateClassDefinition, + (node: ClassDefinition, original: ClassDefinition) => node.setAnnotations(original.annotations) + ) + }, + get createClassProperty() { + return ClassProperty.createClassProperty + }, + get updateClassProperty() { + return updateThenAttach( + ClassProperty.updateClassProperty, + (node: ClassProperty, original: ClassProperty) => node.setAnnotations(original.annotations), + (node: ClassProperty, original: ClassProperty) => { + if (hasModifierFlag(original, Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL)) { + return classPropertySetOptional(node, true); + } + return node; + } + ) + }, + get createFunctionType() { + return ETSFunctionType.createETSFunctionType + }, + get updateFunctionType() { + return updateThenAttach( + ETSFunctionType.updateETSFunctionType, + attachModifiers, + (node: ETSFunctionType, original: ETSFunctionType) => node.setAnnotations(original.annotations) + ) + }, + get createFunctionExpression() { + return FunctionExpression.create + }, + get updateFunctionExpression() { + return updateThenAttach( + FunctionExpression.update, + attachModifiers + ) + }, + get createMethodDefinition() { + return MethodDefinition.create + }, + get updateMethodDefinition() { + return updateThenAttach( + MethodDefinition.update, + (node: MethodDefinition, original: MethodDefinition) => node.setOverloads(original.overloads) + ) + }, + get createSuperExpression() { + return SuperExpression.createSuperExpression + }, + get updateSuperExpression() { + return updateThenAttach( + SuperExpression.updateSuperExpression, + attachModifiers + ) + }, + get createTSTypeParameterInstantiation() { + return TSTypeParameterInstantiation.createTSTypeParameterInstantiation + }, + get updateTSTypeParameterInstantiation() { + return updateThenAttach( + TSTypeParameterInstantiation.updateTSTypeParameterInstantiation, + attachModifiers + ) + }, + get createInterfaceDeclaration() { + return TSInterfaceDeclaration.createTSInterfaceDeclaration + }, + get updateInterfaceDeclaration() { + return updateThenAttach( + TSInterfaceDeclaration.updateTSInterfaceDeclaration, + attachModifiers + ) + }, + get createInterfaceBody() { + return TSInterfaceBody.createTSInterfaceBody + }, + get updateInterfaceBody() { + return updateThenAttach( + TSInterfaceBody.updateTSInterfaceBody, + attachModifiers + ) + }, + get createUndefinedLiteral() { + return UndefinedLiteral.createUndefinedLiteral + }, + get updateUndefinedLiteral() { + return updateThenAttach( + UndefinedLiteral.updateUndefinedLiteral, + attachModifiers + ) + }, + get createAnnotationUsage() { + return AnnotationUsage.createAnnotationUsage + }, + get updateAnnotationUsage() { + return updateThenAttach( + AnnotationUsage.updateAnnotationUsage, + attachModifiers + ) + }, + get createAssignmentExpression() { + return AssignmentExpression.create + }, + get updateAssignmentExpression() { + return updateThenAttach( + AssignmentExpression.update, + attachModifiers + ) + }, + get createETSUndefinedType() { + return ETSUndefinedType.createETSUndefinedType + }, + get updateETSUndefinedType() { + return updateThenAttach( + ETSUndefinedType.updateETSUndefinedType, + attachModifiers + ) + }, + get createFunctionSignature() { + return FunctionSignature.createFunctionSignature + }, + get createConditionalExpression() { + return ConditionalExpression.createConditionalExpression + }, + get updateConditionalExpression() { + return updateThenAttach( + ConditionalExpression.updateConditionalExpression, + attachModifiers + ) + }, + get createTSAsExpression() { + return TSAsExpression.createTSAsExpression + }, + get updateTSAsExpression() { + return updateThenAttach( + TSAsExpression.updateTSAsExpression, + attachModifiers + ) + }, + get createThisExpression() { + return ThisExpression.createThisExpression + }, + get updateThisExpression() { + return updateThenAttach( + ThisExpression.updateThisExpression, + attachModifiers + ) + }, + get createTSTypeAliasDeclaration() { + return TSTypeAliasDeclaration.createTSTypeAliasDeclaration + }, + get updateTSTypeAliasDeclaration() { + return updateThenAttach( + TSTypeAliasDeclaration.updateTSTypeAliasDeclaration, + attachModifiers, + (node: TSTypeAliasDeclaration, original: TSTypeAliasDeclaration) => node.setAnnotations(original.annotations) + ) + }, + get createTSNonNullExpression() { + return TSNonNullExpression.createTSNonNullExpression + }, + get updateTSNonNullExpression() { + return TSNonNullExpression.updateTSNonNullExpression + }, + get createChainExpression() { + return ChainExpression.createChainExpression + }, + get updateChainExpression() { + return ChainExpression.updateChainExpression + }, + get createBlockExpression() { + return BlockExpression.createBlockExpression + }, + get updateBlockExpression() { + return BlockExpression.updateBlockExpression + }, + get createNullLiteral() { + return NullLiteral.createNullLiteral + }, + get updateNullLiteral() { + return NullLiteral.updateNullLiteral + }, + get createETSNewClassInstanceExpression() { + return ETSNewClassInstanceExpression.createETSNewClassInstanceExpression + }, + get updateETSNewClassInstanceExpression() { + return ETSNewClassInstanceExpression.updateETSNewClassInstanceExpression + }, + get createETSStringLiteralType(){ + return ETSStringLiteralType.create; + }, + /** @deprecated */ + createTypeParameter1_(name: Identifier, constraint?: TypeNode, defaultType?: TypeNode) { + return TSTypeParameter.createTSTypeParameter(Identifier.create1Identifier(name.name), constraint, defaultType) + }, +} diff --git a/koala-wrapper/src/arkts-api/factory/nodeTests.ts b/koala-wrapper/src/arkts-api/factory/nodeTests.ts new file mode 100644 index 000000000..b40a1a353 --- /dev/null +++ b/koala-wrapper/src/arkts-api/factory/nodeTests.ts @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { global } from "../static/global" +import { + ArrowFunctionExpression, + CallExpression, + ETSParameterExpression, + EtsScript, + ExpressionStatement, + FunctionDeclaration, + FunctionExpression, + IfStatement, + MethodDefinition, + // ScriptFunction, + StructDeclaration, + VariableDeclaration, + VariableDeclarator, +} from "../types" +import { MemberExpression } from "../to-be-generated/MemberExpression" +import { AstNode } from "../peers/AstNode" + +export function isCallExpression(node: AstNode): node is CallExpression { + return node instanceof CallExpression +} + +export function isMemberExpression(node: AstNode): node is MemberExpression { + return node instanceof MemberExpression +} + +export function isFunctionDeclaration(node: AstNode): node is FunctionDeclaration { + return node instanceof FunctionDeclaration +} + +export function isMethodDefinition(node: AstNode): node is MethodDefinition { + return node instanceof MethodDefinition +} + +export function isEtsScript(node: AstNode): node is EtsScript { + return node instanceof EtsScript +} + +export function isExpressionStatement(node: AstNode): node is ExpressionStatement { + return node instanceof ExpressionStatement +} + +export function isArrowFunctionExpression(node: AstNode): node is ArrowFunctionExpression { + return node instanceof ArrowFunctionExpression +} + +export function isStructDeclaration(node: AstNode): node is StructDeclaration { + return node instanceof StructDeclaration +} + +export function isFunctionExpression(node: AstNode): node is FunctionExpression { + return node instanceof FunctionExpression +} + +export function isEtsParameterExpression(node: AstNode): node is ETSParameterExpression { + return node instanceof ETSParameterExpression +} + +export function isVariableDeclaration(node: AstNode): node is VariableDeclaration { + return node instanceof VariableDeclaration +} + +// export function isScriptFunction(node: AstNode): node is ScriptFunction { +// return node instanceof ScriptFunction +// } + +export function isIfStatement(node: AstNode): node is IfStatement { + return node instanceof IfStatement +} + +export function isVariableDeclarator(node: AstNode): node is VariableDeclarator { + return node instanceof VariableDeclarator +} diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts new file mode 100644 index 000000000..7656ff330 --- /dev/null +++ b/koala-wrapper/src/arkts-api/index.ts @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022-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. + */ + +export * from "../Es2pandaEnums" +export * from "../generated/Es2pandaEnums" +export * from "../generated/peers/AnnotationUsage" +export * from "../generated/peers/BlockStatement" +export * from "../generated/peers/ETSPrimitiveType" +export * from "../generated/peers/TSInterfaceBody" +export * from "../generated/peers/TSInterfaceDeclaration" +export * from "../generated/peers/TSTypeParameterInstantiation" +export * from "../generated/peers/UndefinedLiteral" +export * from "../generated/peers/ETSUnionType" +export * from "../generated/peers/FunctionSignature" +export * from "../generated/peers/ETSFunctionType" +export * from "../generated/peers/StringLiteral" +export * from "../generated/peers/ThrowStatement" +export * from "../generated/peers/TypeNode" +export * from "../generated/peers/ClassDeclaration" +export * from "../generated/peers/ClassDefinition" +export * from "../generated/peers/Identifier" +export * from "../generated/peers/ETSTypeReference" +export * from "../generated/peers/ETSTypeReferencePart" +export * from "../generated/peers/ClassProperty" +export * from "../generated/peers/ReturnStatement" +export * from "../generated/peers/Expression" +export * from "../generated/peers/Statement" +export * from "../generated/peers/ImportSpecifier" +export * from "../generated/peers/TSAsExpression" +export * from "../generated/peers/ThisExpression" +export * from "../generated/peers/TSThisType" +export * from "../generated/peers/ETSImportDeclaration" +export * from "../generated/peers/ImportSource" +export * from "../generated/peers/ScriptFunction" +export * from "../generated/peers/TSTypeParameterDeclaration" +export * from "../generated/peers/TSTypeParameter" +export * from "../generated/peers/TSNonNullExpression" +export * from "../generated/peers/ChainExpression" +export * from "../generated/peers/ConditionalExpression" +export * from "../generated/peers/NullLiteral" +export * from "../generated/peers/TSTypeAliasDeclaration" +export * from "../generated/peers/ETSUndefinedType" +export * from "../generated/peers/ETSNewClassInstanceExpression" +export * from "../generated/peers/ObjectExpression" +export * from "../generated/peers/Property" +export * from "../generated/peers/BlockExpression" + +export * from "./types" +export * from "./utilities/private" +export * from "./utilities/public" +export * from "./factory/nodeFactory" +export * from "./factory/nodeTests" +export * from "./visitor" +export * from "./peers/AstNode" +import "../generated" + +export * from "./peers/Config" +export * from "./peers/Context" +export * from "./peers/Program" +export * from "./peers/ImportPathManager" +export * from "./peers/SourcePosition" +export * from "./to-be-generated/MemberExpression" +export { global as arktsGlobal } from "./static/global"; diff --git a/koala-wrapper/src/arkts-api/peers/ArktsObject.ts b/koala-wrapper/src/arkts-api/peers/ArktsObject.ts new file mode 100644 index 000000000..9bd967b5d --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/ArktsObject.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KNativePointer } from "@koalaui/interop" + +export abstract class ArktsObject { + protected constructor(peer: KNativePointer) { + this.peer = peer + } + + readonly peer: KNativePointer +} diff --git a/koala-wrapper/src/arkts-api/peers/AstNode.ts b/koala-wrapper/src/arkts-api/peers/AstNode.ts new file mode 100644 index 000000000..634da8e17 --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/AstNode.ts @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isNullPtr, KInt, KNativePointer as KPtr, KNativePointer, nullptr } from "@koalaui/interop" +import { global } from "../static/global" +import { allFlags, nodeType, unpackNodeArray, unpackNonNullableNode, unpackString } from "../utilities/private" +import { throwError } from "../../utils" +import { Es2pandaModifierFlags } from "../../generated/Es2pandaEnums" +import { ArktsObject } from "./ArktsObject" +import { Es2pandaAstNodeType } from "../../Es2pandaEnums" + +export abstract class AstNode extends ArktsObject { + protected constructor(peer: KNativePointer) { + if (isNullPtr(peer)) { + throwError(`attempted to create AstNode from nullptr`) + } + super(peer) + this.updateChildren() + } + + public get originalPeer(): KNativePointer { + return global.generatedEs2panda._AstNodeOriginalNodeConst(global.context, this.peer) + } + + public set originalPeer(peer: KNativePointer) { + global.generatedEs2panda._AstNodeSetOriginalNode(global.context, this.peer, peer) + } + + public getChildren(): readonly AstNode[] { + return unpackNodeArray(global.es2panda._AstNodeChildren(global.context, this.peer)) + } + + public getSubtree(): readonly AstNode[] { + return this.getChildren().reduce( + (prev: readonly AstNode[], curr) => { + return prev.concat(curr.getSubtree()) + }, + [this] + ) + } + + public updateChildren(): void { + if (this.peer === nullptr) { + throwError('updateChildren called on NULLPTR') + } + global.es2panda._AstNodeUpdateChildren(global.context, this.peer) + } + + public updateModifiers(modifierFlags: KInt | undefined): this { + global.generatedEs2panda._AstNodeClearModifier(global.context, this.peer, allFlags) + global.generatedEs2panda._AstNodeAddModifier(global.context, this.peer, modifierFlags ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE) + return this + } + + public dump(indentation: number = 0): string { + const children = this.getChildren() + .map((it) => it.dump(indentation + 1)) + const msg = + `${indentation}_` + + ` ` + + this.dumpMessage() + return "> " + " ".repeat(4 * indentation) + msg + "\n" + children.join("") + } + + protected dumpMessage(): string { + return `` + } + + public dumpJson(): string { + return unpackString(global.generatedEs2panda._AstNodeDumpJSONConst(global.context, this.peer)) + } + + public dumpSrc(): string { + return unpackString(global.generatedEs2panda._AstNodeDumpEtsSrcConst(global.context, this.peer)) + } + + public dumpModifiers(): string { + return unpackString(global.es2panda._AstNodeDumpModifiers(global.context, this.peer)) + } + + public clone(): this { + return unpackNonNullableNode(global.generatedEs2panda._AstNodeClone(global.context, this.peer, this.parent.peer)); + } + + public get parent(): AstNode { + const parent = global.generatedEs2panda._AstNodeParent(global.context, this.peer) + if (parent === nullptr) { + throwError(`no parent`) + } + return unpackNonNullableNode(parent) + } + + public set parent(node: AstNode) { + global.generatedEs2panda._AstNodeSetParent(global.context, this.peer, node.peer) + } + + public get modifiers(): KInt { + return global.generatedEs2panda._AstNodeModifiers(global.context, this.peer) + } + + public set modifiers(flags: KInt | undefined) { + global.generatedEs2panda._AstNodeClearModifier(global.context, this.peer, allFlags) + global.generatedEs2panda._AstNodeAddModifier(global.context, this.peer, flags ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE) + } + + public get isStatic(): boolean { + return global.generatedEs2panda._AstNodeIsStaticConst(global.context, this.peer) + } +} + + +export class UnsupportedNode extends AstNode { + constructor(peer: KPtr) { + super(peer) + + } +} diff --git a/koala-wrapper/src/arkts-api/peers/Config.ts b/koala-wrapper/src/arkts-api/peers/Config.ts new file mode 100644 index 000000000..cde8c26fc --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/Config.ts @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from "./ArktsObject" +import { global } from "../static/global" +import { passStringArray } from "../utilities/private" +import { KNativePointer } from "@koalaui/interop" + +export class Config extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer) + // TODO: wait for getter from api + this.path = `` + } + + static create( + input: readonly string[] + ): Config { + console.log("[TS WRAPPER] CREATE CONFIG"); + return new Config( + global.es2panda._CreateConfig(input.length, passStringArray(input)) + ) + } + + static createDefault(): Config { + if (global.configIsInitialized()) { + console.warn(`Config already initialized`) + return new Config( + global.config + ) + } + return new Config( + global.es2panda._CreateConfig( + 4, + passStringArray(["", "--arktsconfig", "./arktsconfig.json", global.filePath]) + ) + ) + } + + readonly path: string +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/peers/Context.ts b/koala-wrapper/src/arkts-api/peers/Context.ts new file mode 100644 index 000000000..81a1ec31f --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/Context.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from "./ArktsObject" +import { global } from "../static/global" +import { throwError, filterSource } from "../../utils" +import { passString } from "../utilities/private" +import { KNativePointer } from "@koalaui/interop" +import { AstNode } from "./AstNode" +import { Program } from "./Program" +export class Context extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer) + } + + static createFromString( + source: string + ): Context { + if (!global.configIsInitialized()) { + throwError(`Config not initialized`) + } + return new Context( + global.es2panda._CreateContextFromString( + global.config, + passString(source), + passString(global.filePath) + ) + ) + } + static destroyAndRecreate( + ast: AstNode + ): Context { + console.log("[TS WRAPPER] DESTROY AND RECREATE"); + const source = filterSource(ast.dumpSrc()) + global.es2panda._DestroyContext(global.context) + global.compilerContext = Context.createFromString(source) + + return new Context(global.context); + } + + get program(): Program { + return new Program(global.es2panda._ContextProgram(this.peer)); + } +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/peers/ImportPathManager.ts b/koala-wrapper/src/arkts-api/peers/ImportPathManager.ts new file mode 100644 index 000000000..eeeecf1dc --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/ImportPathManager.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from "./ArktsObject" +import { global } from "../static/global" +import { KNativePointer } from "@koalaui/interop" +import { passString, unpackString } from "../utilities/private"; +import { SourcePosition } from "./SourcePosition"; + +export class ImportPathManager extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer) + } + + static create(): ImportPathManager { + return new ImportPathManager( + global.es2panda._ETSParserGetImportPathManager(global.context) + ); + } + + resolvePath(currentModulePath: string, importPath: string): string { + return ''; // TODO: no longer support this. + } +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/peers/Program.ts b/koala-wrapper/src/arkts-api/peers/Program.ts new file mode 100644 index 000000000..6671cc8bb --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/Program.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from "./ArktsObject" +import { global } from "../static/global" +import { acceptNativeObjectArrayResult, unpackString } from "../utilities/private" +import { KNativePointer } from "@koalaui/interop" +import { EtsScript } from "../types" + +export class Program extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer) + } + + get astNode(): EtsScript { + return new EtsScript(global.es2panda._ProgramAst(global.context, this.peer)); + } + + get externalSources(): ExternalSource[] { + return acceptNativeObjectArrayResult( + global.es2panda._ProgramExternalSources(global.context, this.peer), + (instance: KNativePointer) => new ExternalSource(instance) + ); + } + +} + +export class ExternalSource extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer) + } + + getName(): string { + return unpackString(global.es2panda._ExternalSourceName(this.peer)); + } + + get programs(): Program[] { + return acceptNativeObjectArrayResult( + global.es2panda._ExternalSourcePrograms(this.peer), + (instance: KNativePointer) => new Program(instance) + ); + } +} diff --git a/koala-wrapper/src/arkts-api/peers/SourcePosition.ts b/koala-wrapper/src/arkts-api/peers/SourcePosition.ts new file mode 100644 index 000000000..9d84847a6 --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/SourcePosition.ts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from "./ArktsObject" +import { global } from "../static/global" +import { KNativePointer } from "@koalaui/interop" + +export class SourcePosition extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer) + } + + static create(index: number, line: number): SourcePosition { + return new SourcePosition( + global.es2panda._CreateSourcePosition(global.context, index, line) + ); + } + + index(): number { + return global.es2panda._SourcePositionIndex(global.context, this.peer); + } + + line(): number { + return global.es2panda._SourcePositionLine(global.context, this.peer); + } +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/static/global.ts b/koala-wrapper/src/arkts-api/static/global.ts new file mode 100644 index 000000000..80504c6bc --- /dev/null +++ b/koala-wrapper/src/arkts-api/static/global.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { throwError } from "../../utils" +import { KNativePointer } from "@koalaui/interop" +import { initEs2panda, Es2pandaNativeModule, initGeneratedEs2panda } from "../../Es2pandaNativeModule" +import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from "../../generated/Es2pandaNativeModule" +import { initInterop, InteropNativeModule } from "../../InteropNativeModule" +import { Context } from "../peers/Context" + +export class global { + public static filePath: string = "./plugins/input/main.sts" + + private static _config?: KNativePointer + public static set config(config: KNativePointer) { + if (global._config !== undefined) { + throwError('Global.config already initialized') + } + global._config = config + } + public static get config(): KNativePointer { + return global._config ?? throwError('Global.config not initialized') + } + public static configIsInitialized(): boolean { + return global._config !== undefined + } + + // TODO: rename to contextPeer + public static get context(): KNativePointer { + return global.compilerContext.peer ?? throwError('Global.context not initialized') + } + + // TODO: rename to context when the pointer valued one is eliminated + public static compilerContext: Context + + private static _es2panda: Es2pandaNativeModule | undefined = undefined + public static get es2panda(): Es2pandaNativeModule { + if (this._es2panda === undefined) { + this._es2panda = initEs2panda() + } + return this._es2panda + } + + private static _generatedEs2panda: GeneratedEs2pandaNativeModule | undefined = undefined + public static get generatedEs2panda(): GeneratedEs2pandaNativeModule { + if (this._generatedEs2panda === undefined) { + this._generatedEs2panda = initGeneratedEs2panda() + } + return this._generatedEs2panda + } + + private static _interop: InteropNativeModule | undefined = undefined + public static get interop(): InteropNativeModule { + if (this._interop === undefined) this._interop = initInterop() + return this._interop + } + + public static resetConfig() { + global._config = undefined; + } +} diff --git a/koala-wrapper/src/arkts-api/to-be-generated/MemberExpression.ts b/koala-wrapper/src/arkts-api/to-be-generated/MemberExpression.ts new file mode 100644 index 000000000..a8f50ec11 --- /dev/null +++ b/koala-wrapper/src/arkts-api/to-be-generated/MemberExpression.ts @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import { Expression } from "../../generated" +import { + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + Es2pandaMemberExpressionKind, + KNativePointer, + passNode, + unpackNonNullableNode, + global +} from "../../reexport-for-generated" + +export class MemberExpression extends Expression { + constructor(peer: KNativePointer) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION) + super(peer) + } + + static create( + object: AstNode, + property: AstNode, + kind: Es2pandaMemberExpressionKind, + computed: boolean, + optional: boolean + ): MemberExpression { + return new MemberExpression( + global.generatedEs2panda._CreateMemberExpression( + global.context, + passNode(object), + passNode(property), + kind, + computed, + optional + ) + ) + } + + static update( + node: MemberExpression, + object: AstNode, + property: AstNode, + kind: Es2pandaMemberExpressionKind, + computed: boolean, + optional: boolean + ): MemberExpression { + return new MemberExpression( + global.generatedEs2panda._UpdateMemberExpression( + global.context, + node.peer, + passNode(object), + passNode(property), + kind, + computed, + optional + ) + ) + } + + protected override dumpMessage(): string { + return ` ` + } + + get object(): AstNode { + return unpackNonNullableNode(global.generatedEs2panda._MemberExpressionObject(global.context, this.peer)) + } + + get property(): AstNode { + return unpackNonNullableNode(global.generatedEs2panda._MemberExpressionProperty(global.context, this.peer)) + } + + get kind(): Es2pandaMemberExpressionKind { + return global.generatedEs2panda._MemberExpressionKindConst(global.context, this.peer) + } + + get computed(): boolean { + return global.generatedEs2panda._MemberExpressionIsComputedConst(global.context, this.peer) + } + + get optional(): boolean { + return false // todo: no corresponding method in es2panda + } +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/types.ts b/koala-wrapper/src/arkts-api/types.ts new file mode 100644 index 000000000..af688c17d --- /dev/null +++ b/koala-wrapper/src/arkts-api/types.ts @@ -0,0 +1,1007 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { global } from "./static/global" +import { KInt, KNativePointer, KNativePointer as KPtr, nullptr } from "@koalaui/interop" +import { + Es2pandaContextState, + Es2pandaMethodDefinitionKind, + Es2pandaModifierFlags, + Es2pandaScriptFunctionFlags, + Es2pandaTokenType, + Es2pandaVariableDeclarationKind, + Es2pandaVariableDeclaratorFlag, +} from "../generated/Es2pandaEnums" +import { + allFlags, + arrayOfNullptr, + assertValidPeer, + nodeType, + passNode, + passNodeArray, + passString, + unpackNode, + unpackNodeArray, + unpackNonNullableNode, + unpackString, + updatePeerByNode, +} from "./utilities/private" +import { proceedToState } from "./utilities/public" +import { Es2pandaAstNodeType } from "../Es2pandaEnums" +import { AstNode } from "./peers/AstNode" +import { ArktsObject } from "./peers/ArktsObject" +import { Config } from "./peers/Config" +import { Context } from "./peers/Context" +import * as path from "node:path" +import { nodeByType } from "./class-by-peer" +import { MemberExpression } from "./to-be-generated/MemberExpression" +import { + AnnotationUsage, + BlockStatement, + ClassDefinition, + ETSTypeReference, + ETSTypeReferencePart, + Expression, + FunctionSignature, + Identifier, + ImportSpecifier, + Literal, + ObjectExpression, + ScriptFunction, + StringLiteral, + TSTypeParameterDeclaration, + TSTypeParameterInstantiation, + TypeNode +} from "../generated" + +export class EtsScript extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) + super(peer) + } + + // TODO: + // static create( + // statementList: Statement[] + // ): EtsScript { + // } + + static fromContext(): EtsScript { + console.log("[TS WRAPPER] GET AST FROM CONTEXT"); + return new EtsScript(global.es2panda._ProgramAst(global.context, global.es2panda._ContextProgram(global.context))) + } + + /** + * @deprecated + */ + static createFromSource( + source: string, + state: Es2pandaContextState = Es2pandaContextState.ES2PANDA_STATE_PARSED, + ): EtsScript { + if (!global.configIsInitialized()) { + global.config = Config.createDefault().peer + } + global.compilerContext = Context.createFromString(source) + proceedToState(state) + return new EtsScript(global.es2panda._ProgramAst(global.context, global.es2panda._ContextProgram(global.context))) + } + + /** + * @deprecated + */ + static updateByStatements( + node: EtsScript, + statements: readonly AstNode[], + ): EtsScript { + global.generatedEs2panda._BlockStatementSetStatements(global.context, node.peer, passNodeArray(statements), statements.length) + return node + } + + get statements(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._BlockStatementStatements(global.context, this.peer)) + } + + set statements(nodes: readonly AstNode[]) { + global.generatedEs2panda._BlockStatementSetStatements(global.context, this.peer, passNodeArray(nodes), nodes.length) + } +} + +export class ExpressionStatement extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT) + super(peer) + this.expression = unpackNonNullableNode(global.generatedEs2panda._ExpressionStatementGetExpression(global.context, this.peer)) + } + + static create( + expression: AstNode, + ): ExpressionStatement { + return new ExpressionStatement( + global.generatedEs2panda._CreateExpressionStatement( + global.context, + expression.peer + ) + ) + } + + static update( + node: ExpressionStatement, + expression: AstNode, + ): ExpressionStatement { + return new ExpressionStatement( + global.generatedEs2panda._UpdateExpressionStatement( + global.context, + node.peer, + expression.peer + ) + ) + } + + readonly expression: AstNode +} + +// TODO: +// the CallExpression idl Create signature doesn't include the trailing block at all. +// Need to clarify with the compiler people if they will provide create signature with a trailing block argument. +export class CallExpression extends Expression { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION) + super(peer) + this.expression = unpackNonNullableNode( + global.generatedEs2panda._CallExpressionCallee(global.context, this.peer)) + const tsTypeParameterInstantiation = unpackNode(global.generatedEs2panda._CallExpressionTypeParams(global.context, this.peer)) + this.typeArguments = tsTypeParameterInstantiation ? + unpackNodeArray(global.generatedEs2panda._TSTypeParameterInstantiationParamsConst(global.context, tsTypeParameterInstantiation.peer)) : undefined + this.arguments = unpackNodeArray( + global.generatedEs2panda._CallExpressionArguments(global.context, this.peer)) + this.trailingBlock = unpackNode( + global.generatedEs2panda._CallExpressionTrailingBlockConst(global.context, this.peer)) + } + + static create( + expression: AstNode, + typeArguments: readonly TypeNode[] | undefined, + args: readonly AstNode[] | undefined, + trailingBlock: AstNode | undefined = undefined + ): CallExpression { + const peer = global.generatedEs2panda._CreateCallExpression( + global.context, + passNode(expression), + passNodeArray(args), + args?.length ?? 0, + typeArguments ? passNode(TSTypeParameterInstantiation.createTSTypeParameterInstantiation(typeArguments)) : nullptr, + false, + false + ) + const call = new CallExpression(peer) + if (trailingBlock) { + global.generatedEs2panda._CallExpressionSetTrailingBlock( + global.context, peer, trailingBlock?.peer + ) + } + return call + } + + static update( + node: CallExpression, + expression: AstNode, + typeArguments: readonly TypeNode[] | undefined, + args: readonly AstNode[] | undefined, + trailingBlock: AstNode | undefined = undefined + ): CallExpression { + const peer = global.es2panda._UpdateCallExpression( + global.context, + node.peer, + passNode(expression), + passNodeArray(args), + args?.length ?? 0, + typeArguments ? passNode(TSTypeParameterInstantiation.createTSTypeParameterInstantiation(typeArguments)) : nullptr, + false, + false + ) + const call = new CallExpression(peer) + if (trailingBlock) { + global.generatedEs2panda._CallExpressionSetTrailingBlock( + global.context, peer, trailingBlock?.peer + ) + } + return call + } + + readonly expression: AstNode // Expression + readonly typeArguments: readonly TypeNode[] | undefined + readonly arguments: readonly Expression[] + readonly trailingBlock: AstNode|undefined // BlockStatement +} + +export class AssignmentExpression extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ASSIGNMENT_EXPRESSION) + super(peer) + } + + static create( + left: AstNode, + assignmentOperator: Es2pandaTokenType, + right: AstNode + ): AssignmentExpression { + return new AssignmentExpression( + global.generatedEs2panda._CreateAssignmentExpression( + global.context, + passNode(left), + passNode(right), + assignmentOperator + ) + ) + } + + static update( + node: AssignmentExpression, + left: AstNode, + assignmentOperator: Es2pandaTokenType, + right: AstNode + ): AssignmentExpression { + return new AssignmentExpression( + global.generatedEs2panda._UpdateAssignmentExpression( + global.context, + node.peer, + passNode(left), + passNode(right), + assignmentOperator + ) + ) + } +} + +export class TSUnionType extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE) + super(peer) + this.types = unpackNodeArray(global.generatedEs2panda._TSUnionTypeTypesConst(global.context, this.peer)) + } + + static create( + node: undefined | TSUnionType, + types: AstNode[], + ): TSUnionType { + return new TSUnionType( + updatePeerByNode( + global.generatedEs2panda._CreateTSUnionType( + global.context, + passNodeArray(types), + types.length + ), + node + ) + ) + } + + readonly types: readonly AstNode[] +} + +export class NumberLiteral extends Literal { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL) + super(peer) + this.value = 0.0 + } + + static create( + value: number, + ): NumberLiteral { + return new NumberLiteral( + global.es2panda._CreateNumberLiteral( + global.context, + value + ) + ) + } + + protected override dumpMessage(): string { + return ` ` + } + + readonly value: number = 0.0 +} + +// export class ScriptFunction extends AstNode { +// constructor(peer: KPtr) { +// assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION) +// super(peer) +// this.parameters = unpackNodeArray(global.generatedEs2panda._ScriptFunctionParams(global.context, this.peer)) +// this.typeParamsDecl = unpackNode(global.generatedEs2panda._ScriptFunctionTypeParams(global.context, this.peer)) +// this.returnTypeAnnotation = unpackNode(global.generatedEs2panda._ScriptFunctionReturnTypeAnnotation(global.context, this.peer)) +// this.body = unpackNode(global.generatedEs2panda._ScriptFunctionBody(global.context, this.peer)) +// // this.signature = unpackNode(global.generatedEs2panda._ScriptFunctionSignature(global.context, this.peer)) +// // this.declare = global.generatedEs2panda._ScriptFunctionDeclareConst(global.context, this.peer) +// this.ident = unpackNode(global.generatedEs2panda._ScriptFunctionId(global.context, this.peer)) + +// this.scriptFunctionFlags = this._correctScriptFunctionFlags() +// } + +// static create( +// body: AstNode | undefined, +// functionFlags: Es2pandaScriptFunctionFlags, +// modifierFlags: Es2pandaModifierFlags, +// declare: boolean, +// ident: Identifier | undefined, +// parameters: ETSParameterExpression[]|undefined, +// typeParamsDecl: TSTypeParameterDeclaration|undefined, +// returnTypeAnnotation: TypeNode|undefined, +// annotations?: AnnotationUsage[], +// ): ScriptFunction { +// const peer = global.generatedEs2panda._CreateScriptFunction( +// global.context, +// passNode(body), +// FunctionSignature.createFunctionSignature( +// typeParamsDecl, +// parameters ?? [], +// returnTypeAnnotation, +// false +// ).peer, +// functionFlags, +// modifierFlags +// ) +// if (ident !== undefined) { +// global.generatedEs2panda._ScriptFunctionSetIdent(global.context, peer, ident.peer) +// } +// const res = new ScriptFunction(peer) +// if (annotations) { +// res.annotations = annotations +// } +// return res +// } + +// setIdent(id: Identifier): ScriptFunction { +// assertValidPeer(id.peer, Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER); +// global.generatedEs2panda._ScriptFunctionSetIdent(global.context, this.peer, id.peer); +// return this; +// } + +// protected override dumpMessage(): string { +// const scriptFunctionFlags = global.generatedEs2panda._ScriptFunctionFlagsConst(global.context, this.peer) +// return ` ` +// } + +// private _correctScriptFunctionFlags(): KInt { +// let flags: KInt = global.generatedEs2panda._ScriptFunctionFlagsConst(global.context, this.peer) +// if (this._hasReturn()) { +// flags |= Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_HAS_RETURN +// global.generatedEs2panda._ScriptFunctionAddFlag(global.context, this.peer, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_HAS_RETURN) +// } +// if (this._isAsync()) { +// flags |= Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC +// global.generatedEs2panda._ScriptFunctionAddFlag(global.context, this.peer, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC) +// } +// return flags +// } + +// private _hasReturn(): boolean { +// if (this.body === undefined) { +// return false +// } +// let hasReturn: boolean = false +// // TODO: goes through whole subtree, optimizable (unnecessary now) +// this.body.getSubtree().forEach( +// (node: AstNode) => { +// hasReturn = hasReturn || nodeType(node) === Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT +// } +// ) +// return hasReturn +// } + +// private _isAsync(): boolean { +// return (this.modifiers & Es2pandaModifierFlags.MODIFIER_FLAGS_ASYNC) !== 0 +// } + +// readonly parameters: ETSParameterExpression[] +// readonly typeParamsDecl?: TSTypeParameterDeclaration +// readonly returnTypeAnnotation: TypeNode | undefined +// readonly body?: BlockStatement +// // readonly signature: FunctionSignature +// readonly scriptFunctionFlags: KInt +// readonly ident?: Identifier + +// get annotations(): AnnotationUsage[] { +// return unpackNodeArray(global.es2panda._ScriptFunctionAnnotations( +// global.context, +// this.peer, +// nullptr +// )) +// } + +// set annotations(newAnnotations: AnnotationUsage[]) { +// global.es2panda._ScriptFunctionSetAnnotations( +// global.context, +// this.peer, +// passNodeArray(newAnnotations), +// newAnnotations.length +// ); +// } +// } + +export class ArrowFunctionExpression extends Expression { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION) + super(peer) + this.scriptFunction = unpackNonNullableNode(global.generatedEs2panda._ArrowFunctionExpressionFunction(global.context, this.peer)) + } + + static create( + func: ScriptFunction, + ): ArrowFunctionExpression { + return new ArrowFunctionExpression( + global.generatedEs2panda._CreateArrowFunctionExpression( + global.context, + passNode(func) + ) + ) + } + + static update( + node: ArrowFunctionExpression, + func: ScriptFunction, + ): ArrowFunctionExpression { + return new ArrowFunctionExpression( + global.generatedEs2panda._UpdateArrowFunctionExpression( + global.context, + node.peer, + passNode(func) + ) + ) + } + + get annotations(): AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._ArrowFunctionExpressionAnnotations( + global.context, + this.peer + )); + } + + setAnnotations(annotations: AnnotationUsage[]): this { + global.generatedEs2panda._ArrowFunctionExpressionSetAnnotations( + global.context, + this.peer, + passNodeArray(annotations), + annotations.length + ); + + return this; + } + + readonly scriptFunction: ScriptFunction +} + +export class FunctionDeclaration extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION) + super(peer) + this.scriptFunction = unpackNonNullableNode(global.generatedEs2panda._FunctionDeclarationFunction(global.context, this.peer)) + this.parameters = unpackNodeArray(global.generatedEs2panda._ScriptFunctionParams(global.context, this.scriptFunction.peer)) + this.name = unpackNode(global.generatedEs2panda._ScriptFunctionId(global.context, this.scriptFunction.peer)) + this.body = unpackNode(global.generatedEs2panda._ScriptFunctionBody(global.context, this.scriptFunction.peer)) + this.typeParamsDecl = unpackNode(global.generatedEs2panda._ScriptFunctionTypeParams(global.context, this.scriptFunction.peer)) + this.returnType = unpackNode(global.generatedEs2panda._ScriptFunctionReturnTypeAnnotation(global.context, this.scriptFunction.peer)) + this.isAnon = global.generatedEs2panda._FunctionDeclarationIsAnonymousConst(global.context, this.peer) + } + + static create( + scriptFunction: ScriptFunction, + isAnon: boolean, + annotations?: AnnotationUsage[] + ): FunctionDeclaration { + const res = new FunctionDeclaration( + global.es2panda._CreateFunctionDeclaration( + global.context, + scriptFunction.peer, + // TODO: support annotations + arrayOfNullptr, + 0, + isAnon + ) + ) + // TODO: maybe wrong + res.modifiers = scriptFunction.modifiers + if (annotations) { + res.annotations = annotations + } + return res + } + + static update( + node: FunctionDeclaration, + scriptFunction: ScriptFunction, + isAnon: boolean, + annotations?: AnnotationUsage[] + ): FunctionDeclaration { + const res = new FunctionDeclaration( + global.generatedEs2panda._UpdateFunctionDeclaration( + global.context, + node.peer, + scriptFunction.peer, + // TODO: support annotations + passNodeArray(annotations), + 0, + isAnon + ) + ) + if (annotations) { + res.annotations = annotations + } + return res + } + + get annotations(): AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._FunctionDeclarationAnnotationsConst(global.context, this.peer)) + } + + set annotations(newAnnotations: AnnotationUsage[]) { + global.generatedEs2panda._FunctionDeclarationSetAnnotations(global.context, this.peer, passNodeArray(newAnnotations), newAnnotations.length) + } + + readonly scriptFunction: ScriptFunction + readonly parameters: readonly AstNode[] + readonly name?: Identifier + readonly body?: BlockStatement + readonly typeParamsDecl?: TSTypeParameterDeclaration + readonly returnType?: AstNode + readonly isAnon: boolean +} + +export class FunctionExpression extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION) + super(peer) + this.scriptFunction = unpackNonNullableNode(global.generatedEs2panda._FunctionExpressionFunction(global.context, this.peer)) + } + + static create( + expression: ScriptFunction, + ): FunctionExpression { + return new FunctionExpression( + global.generatedEs2panda._CreateFunctionExpression( + global.context, + passNode(expression) + ) + ) + } + + static update( + node: FunctionExpression, + expression: ScriptFunction, + ): FunctionExpression { + return new FunctionExpression( + global.generatedEs2panda._UpdateFunctionExpression( + global.context, + node.peer, + passNode(expression) + ) + ) + } + + readonly scriptFunction: ScriptFunction +} + +export class ETSParameterExpression extends Expression { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION) + super(peer) + this.identifier = unpackNonNullableNode(global.generatedEs2panda._ETSParameterExpressionIdent(global.context, this.peer)) + } + + static create( + identifier: Identifier, + initializer: AstNode | undefined + ): ETSParameterExpression { + if (initializer !== undefined) { + return new ETSParameterExpression( + global.generatedEs2panda._CreateETSParameterExpression1( + global.context, + passNode(identifier), + passNode(initializer), + ) + ) + } + return new ETSParameterExpression( + global.generatedEs2panda._CreateETSParameterExpression( + global.context, + passNode(identifier), + false + ) + ) + } + + static update( + node: ETSParameterExpression, + identifier: Identifier, + initializer: AstNode | undefined + ): ETSParameterExpression { + if (initializer !== undefined) { + return new ETSParameterExpression( + global.generatedEs2panda._UpdateETSParameterExpression1( + global.context, + node.peer, + passNode(identifier), + passNode(initializer), + ) + ) + } + return new ETSParameterExpression( + global.generatedEs2panda._UpdateETSParameterExpression( + global.context, + node.peer, + passNode(identifier), + false + ) + ) + } + + get annotations(): AnnotationUsage[] { + return unpackNodeArray(global.es2panda._ETSParameterExpressionAnnotations( + global.context, + this.peer, + nullptr + )) + } + + set annotations(newAnnotations: AnnotationUsage[]) { + global.es2panda._ETSParameterExpressionSetAnnotations( + global.context, + this.peer, + passNodeArray(newAnnotations), + newAnnotations.length + ); + } + + get type(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._ETSParameterExpressionTypeAnnotation(global.context, this.peer)) + } + + set type(t: AstNode | undefined) { + if (t === undefined) + return + global.generatedEs2panda._ETSParameterExpressionSetTypeAnnotation(global.context, this.peer, t.peer) + } + + get optional(): Boolean { + return global.generatedEs2panda._ETSParameterExpressionIsOptionalConst(global.context, this.peer) + } + + setOptional(value: boolean): this { + global.generatedEs2panda._ETSParameterExpressionSetOptional(global.context, this.peer, value) + return this + } + + identifier: Identifier +} + +export class IfStatement extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT) + super(peer) + this.test = unpackNonNullableNode(global.generatedEs2panda._IfStatementTest(global.context, this.peer)) + this.consequent = unpackNonNullableNode(global.generatedEs2panda._IfStatementConsequent(global.context, this.peer)) + this.alternate = unpackNode(global.generatedEs2panda._IfStatementAlternate(global.context, this.peer)) + } + + static create( + test: AstNode, + consequent: AstNode, + alternate?: AstNode + ): IfStatement { + return new IfStatement( + global.generatedEs2panda._CreateIfStatement( + global.context, + passNode(test), + passNode(consequent), + passNode(alternate) + ) + ) + } + + static update( + node: IfStatement, + test: AstNode, + consequent: AstNode, + alternate?: AstNode + ): IfStatement { + return new IfStatement( + global.generatedEs2panda._UpdateIfStatement( + global.context, + node.peer, + passNode(test), + passNode(consequent), + passNode(alternate) + ) + ) + } + + test: AstNode + consequent: AstNode + alternate: AstNode | undefined +} + +export class StructDeclaration extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION) + super(peer) + // TODO: is struct definition the same as struct definition? + this.definition = unpackNonNullableNode(global.generatedEs2panda._ClassDeclarationDefinition(global.context, this.peer)) + } + + static create( + definition: ClassDefinition, + ): StructDeclaration { + return new StructDeclaration( + global.generatedEs2panda._CreateETSStructDeclaration( + global.context, + passNode(definition) + ) + ) + } + + static update( + node: StructDeclaration, + definition: ClassDefinition, + ): StructDeclaration { + return new StructDeclaration( + global.generatedEs2panda._UpdateETSStructDeclaration( + global.context, + node.peer, + passNode(definition) + ) + ) + } + + readonly definition: ClassDefinition +} + +export class MethodDefinition extends AstNode { + constructor(peer: KPtr, key?: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION) + super(peer) + this.kind = global.generatedEs2panda._MethodDefinitionKindConst(global.context, this.peer); + this.scriptFunction = unpackNonNullableNode(global.generatedEs2panda._MethodDefinitionFunction(global.context, this.peer)) + assertValidPeer(this.scriptFunction.peer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION); + + // Somehow the scriptFunction cannot attach method's key to its ident after checker + if (key) { + assertValidPeer(key, Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER); + const _name = unpackNonNullableNode(key); + this.scriptFunction = this.scriptFunction.setIdent(_name as Identifier); + } + + this.name = unpackNonNullableNode(global.generatedEs2panda._ScriptFunctionId(global.context, this.scriptFunction.peer)) + this.kind = global.generatedEs2panda._MethodDefinitionKindConst(global.context, this.peer) + } + + static create( + kind: Es2pandaMethodDefinitionKind, + key: AstNode, + value: AstNode, + modifiers: KInt, + isComputed: boolean + ): MethodDefinition { + return new MethodDefinition( + global.generatedEs2panda._CreateMethodDefinition( + global.context, + kind, + passNode(key), + passNode(value), + modifiers, + isComputed + ), + key.peer + ) + } + + static update( + node: MethodDefinition, + kind: Es2pandaMethodDefinitionKind, + key: AstNode, + value: AstNode, + modifiers: KInt, + isComputed: boolean + ): MethodDefinition { + return new MethodDefinition( + global.generatedEs2panda._UpdateMethodDefinition( + global.context, + node.peer, + kind, + passNode(key), + passNode(value), + modifiers, + isComputed + ), + key.peer + ) + } + + // TODO: does not work + isConstructor(): boolean { + return global.generatedEs2panda._MethodDefinitionIsConstructorConst(global.context, this.peer); + } + + get overloads(): readonly MethodDefinition[] { + return unpackNodeArray(global.generatedEs2panda._MethodDefinitionOverloadsConst(global.context, this.peer)) + } + + setOverloads(overloads: readonly MethodDefinition[]): this { + global.generatedEs2panda._MethodDefinitionSetOverloads(global.context, this.peer, passNodeArray(overloads), overloads.length) + return this + } + + readonly kind: Es2pandaMethodDefinitionKind; + readonly scriptFunction: ScriptFunction + readonly name: Identifier +} + +export class VariableDeclaration extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION) + super(peer) + this.declarationKind = global.generatedEs2panda._VariableDeclarationKindConst(global.context, this.peer) + this.declarators = unpackNodeArray(global.generatedEs2panda._VariableDeclarationDeclaratorsConst(global.context, this.peer)) + } + + static create( + modifiers: KInt, + kind: Es2pandaVariableDeclarationKind, + declarators: readonly VariableDeclarator[] + ): VariableDeclaration { + const peer = global.generatedEs2panda._CreateVariableDeclaration( + global.context, + kind, + passNodeArray(declarators), + declarators.length + ) + global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags) + global.generatedEs2panda._AstNodeAddModifier(global.context, peer, modifiers) + return new VariableDeclaration(peer) + } + + static update( + node: VariableDeclaration, + modifiers: KInt, + kind: Es2pandaVariableDeclarationKind, + declarators: readonly VariableDeclarator[] + ): VariableDeclaration { + const peer = global.generatedEs2panda._UpdateVariableDeclaration( + global.context, + node.peer, + kind, + passNodeArray(declarators), + declarators.length + ) + global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags) + global.generatedEs2panda._AstNodeAddModifier(global.context, peer, modifiers) + return new VariableDeclaration(peer) + } + + readonly declarationKind: Es2pandaVariableDeclarationKind + readonly declarators: readonly VariableDeclarator[] +} + +export class VariableDeclarator extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR) + super(peer) + this.name = unpackNonNullableNode(global.generatedEs2panda._VariableDeclaratorId(global.context, this.peer)) + } + + static create( + flag: Es2pandaVariableDeclaratorFlag, + name: Identifier, + initializer: AstNode | undefined + ): VariableDeclarator { + const peer = global.generatedEs2panda._CreateVariableDeclarator( + global.context, + flag, + passNode(name) + ) + if (initializer !== undefined) { + global.generatedEs2panda._VariableDeclaratorSetInit(global.context, peer, initializer.peer) + } + return new VariableDeclarator(peer) + } + + static update( + node: VariableDeclarator, + flag: Es2pandaVariableDeclaratorFlag, + name: Identifier, + initializer: AstNode | undefined + ): VariableDeclarator { + const peer = global.generatedEs2panda._UpdateVariableDeclarator( + global.context, + node.peer, + flag, + passNode(name) + ) + if (initializer !== undefined) { + global.generatedEs2panda._VariableDeclaratorSetInit(global.context, peer, initializer.peer) + } + return new VariableDeclarator(peer) + } + + get initializer(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._VariableDeclaratorInit(global.context, this.peer)) + } + + readonly name: Identifier +} + +export class SuperExpression extends AstNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION) + super(peer) + this.id = unpackNode(global.generatedEs2panda._TSInterfaceDeclarationId(global.context, this.peer)); + } + + static create( + ): SuperExpression { + return new SuperExpression( + global.generatedEs2panda._CreateSuperExpression( + global.context, + ) + ) + } + + readonly id?: Identifier; +} + +export class ETSStringLiteralType extends TypeNode { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_STRING_LITERAL_TYPE) + super(peer) + } + + static create( + str: string, + ): ETSStringLiteralType { + return new ETSStringLiteralType( + global.es2panda._CreateETSStringLiteralType( + global.context, + passString(str) + ) + ) + } +} + +const pairs: [Es2pandaAstNodeType, { new(peer: KNativePointer): AstNode }][] = [ + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE, EtsScript], + [Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER, Identifier], + [Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL, NumberLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT, ExpressionStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION, FunctionDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION, ScriptFunction], + [Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, BlockStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, ETSParameterExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION, TSTypeParameterDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION, CallExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION, MemberExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT, IfStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, ArrowFunctionExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION, StructDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION, MethodDefinition], + [Es2pandaAstNodeType.AST_NODE_TYPE_ASSIGNMENT_EXPRESSION, AssignmentExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION, VariableDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR, VariableDeclarator], + [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION, FunctionExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, ETSTypeReference], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, ETSTypeReferencePart], + [Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, ObjectExpression] +] +pairs.forEach(([nodeType, astNode]) => + nodeByType.set(nodeType, astNode) +) \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/utilities/nativePtrDecoder.ts b/koala-wrapper/src/arkts-api/utilities/nativePtrDecoder.ts new file mode 100644 index 000000000..809b13e72 --- /dev/null +++ b/koala-wrapper/src/arkts-api/utilities/nativePtrDecoder.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { int32 } from "@koalaui/common" +import { + Access, + ArrayDecoder, + CallbackRegistry, + NativeStringBase, + nullptr, + pointer, + providePlatformDefinedData, + withByteArray +} from "@koalaui/interop" +import { global } from "../static/global" + +class NativeString extends NativeStringBase { + constructor(ptr: pointer) { + super(ptr) + } + protected bytesLength(): int32 { + return global.interop._StringLength(this.ptr) + } + protected getData(data: Uint8Array): void { + withByteArray(data, Access.WRITE, (dataPtr: pointer) => { + global.interop._StringData(this.ptr, dataPtr, data.length) + }) + } + close(): void { + global.interop._InvokeFinalizer(this.ptr, global.interop._GetStringFinalizer()) + this.ptr = nullptr + } +} + +providePlatformDefinedData({ + nativeString(ptr: pointer): NativeStringBase { + return new NativeString(ptr) + }, + nativeStringArrayDecoder(): ArrayDecoder { + throw new Error("Not yet implemented") + }, + callbackRegistry(): CallbackRegistry | undefined { + return undefined + } +}) + +export class NativePtrDecoder extends ArrayDecoder { + getArraySize(blob: pointer) { + return global.interop._GetPtrVectorSize(blob) + } + disposeArray(blob: pointer): void { + // TODO + } + getArrayElement(blob: pointer, index: int32): pointer { + return global.interop._GetPtrVectorElement(blob, index) + } +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/utilities/private.ts b/koala-wrapper/src/arkts-api/utilities/private.ts new file mode 100644 index 000000000..6fc2348d3 --- /dev/null +++ b/koala-wrapper/src/arkts-api/utilities/private.ts @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { global } from "../static/global" +import { isNumber, throwError } from "../../utils" +import { + KInt, + KNativePointer as KPtr, + KNativePointer, + nullptr, + withString, + withStringArray, + withStringResult +} from "@koalaui/interop" +import { NativePtrDecoder } from "./nativePtrDecoder" +import { Es2pandaModifierFlags, Es2pandaScriptFunctionFlags } from "../../generated/Es2pandaEnums" +import { classByPeer } from "../class-by-peer" +import type { AstNode } from "../peers/AstNode" +import { ArktsObject } from "../peers/ArktsObject" +import { Es2pandaAstNodeType } from "../../Es2pandaEnums" + +export const arrayOfNullptr = new BigUint64Array([nullptr]) + +export const allFlags = + Object.values(Es2pandaModifierFlags) + .filter(isNumber) + .reduce( + (prev, next) => (prev | next), + 0 + + ) + +export function assertValidPeer(peer: KPtr, expectedKind: Es2pandaAstNodeType): void { + if (peer === nullptr) { + throwError(`invalid peer`) + } + const peerType = global.generatedEs2panda._AstNodeTypeConst(global.context, peer) + if (peerType !== expectedKind) { + throwError(`expected: ${Es2pandaAstNodeType[expectedKind]}, got: ${Es2pandaAstNodeType[peerType]}`) + } +} + +export function acceptNativeObjectArrayResult(arrayObject: KNativePointer, factory: (instance: KNativePointer) => T): T[] { + return new NativePtrDecoder().decode(arrayObject).map(factory); +} + +export function unpackNonNullableNode(peer: KNativePointer): T { + if (peer === nullptr) { + throwError('peer is NULLPTR (maybe you should use unpackNode)') + } + return classByPeer(peer) as T +} + +export function unpackNode(peer: KNativePointer): T | undefined { + if (peer === nullptr) { + return undefined + } + return classByPeer(peer) as T +} + +export function passNode(node: ArktsObject | undefined): KNativePointer { + return node?.peer ?? nullptr +} + +// meaning unpackNonNullableNodeArray +export function unpackNodeArray(nodesPtr: KNativePointer): T[] { + if (nodesPtr === nullptr) { + throwError('nodesPtr is NULLPTR (maybe you should use unpackNodeArray)') + } + return (new NativePtrDecoder()) + .decode(nodesPtr) + .map((peer: KNativePointer) => unpackNonNullableNode(peer)) +} + +export function passNodeArray(nodes: readonly AstNode[] | undefined): BigUint64Array { + return new BigUint64Array( + nodes?.map(node => BigInt(node.peer)) ?? [] + ) +} + +export function unpackNonNullableObject(type: { new (peer: KNativePointer): T }, peer: KNativePointer): T { + if (peer === nullptr) { + throwError('peer is NULLPTR (maybe you should use unpackObject)') + } + return new type(peer) +} + +export function unpackObject(type: { new (peer: KNativePointer): T }, peer: KNativePointer): T | undefined { + if (peer === nullptr) { + return undefined + } + return new type(peer) +} + +export function unpackString(peer: KNativePointer): string { + return withStringResult(peer) ?? throwError(`failed to unpack (peer shouldn't be NULLPTR)`) +} + +export function passString(str: string | undefined): string { + if (str === undefined) { + return "" + } + return withString(str, (it: string) => it) +} + +export function passStringArray(strings: readonly string[]): string[] { + return withStringArray(strings, (it: string[]) => it) +} + +export function passNodeWithNewModifiers(node: T, modifiers: KInt): T { + return (unpackNonNullableNode(node.peer) as T).updateModifiers(modifiers) +} + +export function scriptFunctionHasBody(peer: KNativePointer): boolean { + const flags = global.generatedEs2panda._ScriptFunctionFlagsConst(global.context, peer) + return (flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL) === 0 + && (flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL_OVERLOAD) === 0 +} + +// TODO: remove this +// TODO: update scopes and other data +export function updatePeerByNode(peer: KNativePointer, original: T | undefined): KNativePointer { + if (peer === nullptr) { + throwError('updatePeerByNode called on NULLPTR') + } + if (original === undefined) { + return peer + } + global.generatedEs2panda._AstNodeSetOriginalNode(global.context, peer, original.peer) + global.generatedEs2panda._AstNodeSetParent(global.context, peer, global.generatedEs2panda._AstNodeParent(global.context, original.peer)) + global.es2panda._AstNodeUpdateChildren(global.context, peer) + global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags) + global.generatedEs2panda._AstNodeAddModifier(global.context, peer, original.modifiers) + global.es2panda._AstNodeUpdateChildren(global.context, peer) + return peer +} + +// TODO: update scopes and other data +export function updateNodeByNode(node: T, original: AstNode): T { + if (original.peer === nullptr) { + throwError('update called on NULLPTR') + } + global.generatedEs2panda._AstNodeSetOriginalNode(global.context, node.peer, original.peer) + global.generatedEs2panda._AstNodeSetParent(global.context, node.peer, global.generatedEs2panda._AstNodeParent(global.context, original.peer)) + global.es2panda._AstNodeUpdateChildren(global.context, node.peer) + return node +} + +export function nodeType(node: AstNode): Es2pandaAstNodeType { + return global.generatedEs2panda._AstNodeTypeConst(global.context, passNode(node)) +} diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts new file mode 100644 index 000000000..2ca2f213b --- /dev/null +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { global } from "../static/global" +import { isNumber, throwError, getEnumName } from "../../utils" +import { KNativePointer, KInt, nullptr, withStringResult } from "@koalaui/interop" +import { passNode, passString, unpackNodeArray, unpackNonNullableNode } from "./private" +import { isFunctionDeclaration, isMemberExpression } from "../factory/nodeTests" +import { Es2pandaContextState, Es2pandaModifierFlags } from "../../generated/Es2pandaEnums" +import type { AstNode } from "../peers/AstNode" +import { ClassDefinition, ClassProperty, ETSImportDeclaration, isClassDefinition, isScriptFunction, type AnnotationUsage } from "../../generated" + +export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { + console.log("[TS WRAPPER] PROCEED TO STATE: ", getEnumName(Es2pandaContextState, state)); + if (state <= global.es2panda._ContextState(global.context)) { + console.log("[TS WRAPPER] PROCEED TO STATE: SKIPPING"); + return + } + try { + global.es2panda._ProceedToState(global.context, state) + if (global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && !forceDtsEmit) { + const errorMessage = withStringResult(global.es2panda._ContextErrorMessage(global.context)) + if (errorMessage === undefined) { + throwError(`Could not get ContextErrorMessage`) + } + throwError( + [ + `Failed to proceed to ${Es2pandaContextState[state]}`, + errorMessage + ] + .join(`\n`) + ) + } + } catch (e) { + global.es2panda._DestroyContext(global.context) + throw e + } +} + +export function startChecker(): boolean { + return global.es2panda._CheckerStartChecker(global.context) +} + +export function recheckSubtree(node: AstNode): void { + global.es2panda._AstNodeRecheck(global.context, node.peer) +} + +export function rebindSubtree(node: AstNode): void { + global.es2panda._AstNodeRebind(global.context, node.peer) +} + +export function getDecl(node: AstNode): AstNode | undefined { + if (isMemberExpression(node)) { + return getDecl(node.property) + } + const decl = global.es2panda._DeclarationFromIdentifier(global.context, passNode(node)) + if (decl === nullptr) { + return undefined + } + return unpackNonNullableNode(decl) +} + +export function getAnnotations(node: AstNode): readonly AnnotationUsage[] { + if (!isFunctionDeclaration(node) && !isScriptFunction(node) && !isClassDefinition(node)) { + throwError('for now annotations allowed only for: functionDeclaration, scriptFunction, classDefinition') + } + return unpackNodeArray(global.es2panda._AnnotationAllowedAnnotations(global.context, node.peer, nullptr)) +} + +export function getOriginalNode(node: AstNode): AstNode { + if (node === undefined) { + // TODO: fix this + throwError('there is no arkts pair of ts node (unable to getOriginalNode)') + } + if (node.originalPeer === nullptr) { + return node + } + return unpackNonNullableNode(node.originalPeer) +} + +export function getFileName(): string { + return global.filePath +} + +export function classDefinitionSetFromStructModifier(node: ClassDefinition): void { + global.es2panda._ClassDefinitionSetFromStructModifier(global.context, node.peer); +} + +export function classDefinitionIsFromStructConst(node: ClassDefinition): boolean { + return global.es2panda._ClassDefinitionIsFromStructConst(global.context, node.peer); +} + +// TODO: It seems like Definition overrides AstNode modifiers +// with it's own modifiers which is completely unrelated set of flags. +// Use this function if you need +// the language level modifiers: public, declare, export, etc. +export function classDefinitionFlags(node: ClassDefinition): Es2pandaModifierFlags { + return global.generatedEs2panda._AstNodeModifiers(global.context, node.peer) +} + +// TODO: Import statements should be inserted to the statements +export function importDeclarationInsert(node: ETSImportDeclaration): void { + global.es2panda._InsertETSImportDeclarationAndParse(global.context, node.peer) +} + +export function hasModifierFlag(node: AstNode, flag: Es2pandaModifierFlags): boolean { + if (!node) return false; + + let modifiers; + if (isClassDefinition(node)) { + modifiers = classDefinitionFlags(node); + } else { + modifiers = node.modifiers + } + return (modifiers & flag) === flag; +} + +// TODO: ClassProperty's optional flag is set by AstNode's modifiers flags. +export function classPropertySetOptional(node: ClassProperty, value: boolean): ClassProperty { + if (value) { + node.modifiers |= Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL; + } else { + node.modifiers &= Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL; + } + return node; +} + +export function modifiersToString(modifiers: Es2pandaModifierFlags): string { + return Object.values(Es2pandaModifierFlags) + .filter(isNumber) + .map(it => { + console.log(it.valueOf(), Es2pandaModifierFlags[it], modifiers.valueOf() & it) + return ((modifiers.valueOf() & it) === it) ? Es2pandaModifierFlags[it] : "" + }).join(" ") +} +export function destroyConfig(config: KNativePointer): void { + global.es2panda._DestroyConfig(config); + global.resetConfig(); +} + +export function setAllParents(ast: AstNode) { + global.es2panda._AstNodeUpdateAll(global.context, ast.peer) +} + +export function generateTsDeclarationsFromContext(outputDeclEts: string, outputEts: string, exportAll: boolean): KInt { + return global.es2panda._GenerateTsDeclarationsFromContext(global.context, passString(outputDeclEts), passString(outputEts), exportAll) +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts new file mode 100644 index 000000000..6fe357673 --- /dev/null +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -0,0 +1,338 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { global } from "./static/global" +import { factory } from "./factory/nodeFactory" +import { + Es2pandaClassDefinitionModifiers, + Es2pandaImportKinds, + Es2pandaModifierFlags, + Es2pandaVariableDeclaratorFlag +} from "../generated/Es2pandaEnums" +import { AstNode } from "./peers/AstNode" +import { + isBlockStatement, + isConditionalExpression, + isTSInterfaceBody, + isTSInterfaceDeclaration, + isClassDeclaration, + isClassDefinition, + isTSAsExpression, + isETSImportDeclaration, + ImportSource, + isScriptFunction, + FunctionSignature, + Property, + isClassProperty, + isImportDeclaration +} from "../generated" +import { + isEtsScript, + isCallExpression, + isFunctionDeclaration, + isExpressionStatement, + isStructDeclaration, + isMethodDefinition, + // isScriptFunction, + isMemberExpression, + isIfStatement, + isVariableDeclaration, + isVariableDeclarator, + isArrowFunctionExpression +} from "./factory/nodeTests" +import { + classDefinitionFlags, + hasModifierFlag, + classPropertySetOptional + } from "./utilities/public" + +type Visitor = (node: AstNode) => AstNode + +export interface StructVariableMetadata { + name: string, + properties: string[], + modifiers: Es2pandaModifierFlags, + hasStateManagementType?: boolean +} + +export class StructInfo { + metadata: Record = {}; + initializeBody: AstNode[] = []; + updateBody: AstNode[] = []; + isReusable: boolean = false; + toRecordBody: Property[] = []; +} + +export class GlobalInfo { + private _structCollection: Set; + private static instance: GlobalInfo; + private _structMap: Map; + + private constructor() { + this._structCollection = new Set(); + this._structMap = new Map(); + } + + public static getInfoInstance(): GlobalInfo { + if (!this.instance) { + this.instance = new GlobalInfo(); + } + return this.instance; + } + + public add(str: string): void { + this._structCollection.add(str); + } + + public getStructCollection(): Set { + return this._structCollection; + } + + public getStructInfo(structName: string): StructInfo { + const structInfo = this._structMap.get(structName); + if (!structInfo) { + return new StructInfo(); + } + return structInfo; + } + + public setStructInfo(structName: string, info: StructInfo): void { + this._structMap.set(structName, info); + } +} + +// TODO: rethink (remove as) +function nodeVisitor(node: T, visitor: Visitor): T { + if (node === undefined) { + return node + } + return visitor(node) as T +} + +// TODO: rethink (remove as) +function nodesVisitor(nodes: TIn, visitor: Visitor): T[] | TIn { + if (nodes === undefined) { + return nodes + } + return nodes.map(node => visitor(node) as T) +} + +// TODO: apply this to all nodes that does not require updating +function visitWithoutUpdate( + node: T, + visitor: Visitor +): T { + if (isImportDeclaration(node)) { + nodesVisitor(node.specifiers, visitor); + } + return node; +} + +export function visitEachChild( + node: AstNode, + visitor: Visitor +): AstNode { + if (isEtsScript(node)) { + return factory.updateEtsScript( + node, + nodesVisitor(node.statements, visitor) + ); + } + if (isCallExpression(node)) { + return factory.updateCallExpression( + node, + nodeVisitor(node.expression, visitor), + nodesVisitor(node.typeArguments, visitor), + nodesVisitor(node.arguments, visitor), + nodeVisitor(node.trailingBlock, visitor) + ); + } + if (isFunctionDeclaration(node)) { + return factory.updateFunctionDeclaration( + node, + nodeVisitor(node.scriptFunction, visitor), + node.isAnon, + node.annotations, + ); + } + if (isBlockStatement(node)) { + return factory.updateBlock( + node, + nodesVisitor(node.statements, visitor), + ); + } + if (isExpressionStatement(node)) { + return factory.updateExpressionStatement( + node, + nodeVisitor(node.expression, visitor) + ); + } + if (isClassDeclaration(node)) { + return factory.updateClassDeclaration( + node, + nodeVisitor(node.definition, visitor) + ); + } + if (isStructDeclaration(node)) { + return factory.updateStructDeclaration( + node, + nodeVisitor(node.definition, visitor) + ); + } + if (isClassDefinition(node)) { + // TODO: fix + return factory.updateClassDefinition( + node, + node.ident, + node.typeParams, + node.superTypeParams, + node.implements, + undefined, + node.super, + nodesVisitor(node.body, visitor), + node.modifiers, + classDefinitionFlags(node) + ); + } + if (isMethodDefinition(node)) { + // TODO: fix + return factory.updateMethodDefinition( + node, + node.kind, + node.name, + factory.createFunctionExpression( + // TODO: maybe fix + nodeVisitor(node.scriptFunction, visitor) + ), + node.modifiers, + false + ); + } + if (isScriptFunction(node)) { + return factory.updateScriptFunction( + node, + nodeVisitor(node.body, visitor), + FunctionSignature.createFunctionSignature( + nodeVisitor(node.typeParams, visitor), + nodesVisitor(node.params, visitor), + nodeVisitor(node.returnTypeAnnotation, visitor), + node.hasReceiver + ), + node.flags, + node.modifiers + ); + } + if (isMemberExpression(node)) { + return factory.updateMemberExpression( + node, + nodeVisitor(node.object, visitor), + nodeVisitor(node.property, visitor), + node.kind, + node.computed, + node.optional + ); + } + if (isTSInterfaceDeclaration(node)) { + return factory.updateInterfaceDeclaration( + node, + nodesVisitor(node.extends, visitor), + nodeVisitor(node.id, visitor), + nodeVisitor(node.typeParams, visitor), + nodeVisitor(node.body, visitor), + node.isStatic, + // TODO: how do I get it? + true + ); + } + if (isTSInterfaceBody(node)) { + return factory.updateInterfaceBody( + node, + nodesVisitor(node.body, visitor) + ); + } + if (isIfStatement(node)) { + return factory.updateIfStatement( + node, + nodeVisitor(node.test, visitor), + nodeVisitor(node.consequent, visitor), + nodeVisitor(node.alternate, visitor), + ); + } + if (isConditionalExpression(node)) { + return factory.updateConditionalExpression( + node, + nodeVisitor(node.test, visitor), + nodeVisitor(node.consequent, visitor), + nodeVisitor(node.alternate, visitor), + ); + } + if (isVariableDeclaration(node)) { + return factory.updateVariableDeclaration( + node, + 0, + node.declarationKind, + nodesVisitor(node.declarators, visitor), + ); + } + if (isVariableDeclarator(node)) { + return factory.updateVariableDeclarator( + node, + global.generatedEs2panda._VariableDeclaratorFlag(global.context, node.peer), + nodeVisitor(node.name, visitor), + nodeVisitor(node.initializer, visitor), + ); + } + if (isArrowFunctionExpression(node)) { + return factory.updateArrowFunction( + node, + nodeVisitor(node.scriptFunction, visitor), + ); + } + if (isTSAsExpression(node)) { + return factory.updateTSAsExpression( + node, + nodeVisitor(node.expr, visitor), + nodeVisitor(node.typeAnnotation, visitor), + node.isConst + ); + } + if (isClassProperty(node)) { + return factory.updateClassProperty( + node, + node.key, + nodeVisitor(node.value, visitor), + node.typeAnnotation, + node.modifiers, + node.isComputed + ); + } + if (isClassProperty(node)) { + const _node = factory.updateClassProperty( + node, + node.key, + nodeVisitor(node.value, visitor), + node.typeAnnotation, + node.modifiers, + node.isComputed + ); + if (hasModifierFlag(node, Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL)) { + classPropertySetOptional(_node, true); + } + _node.setAnnotations(node.annotations); + return _node; + } + // TODO + return visitWithoutUpdate(node, visitor); +} diff --git a/koala-wrapper/src/es2panda.ts b/koala-wrapper/src/es2panda.ts new file mode 100644 index 000000000..9e0e14f4e --- /dev/null +++ b/koala-wrapper/src/es2panda.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from "node:fs" +import * as path from "node:path" +import { global } from "./arkts-api/static/global" +import { isNumber, throwError, withWarning, filterSource } from "./utils" +import { Es2pandaContextState } from "./generated/Es2pandaEnums" +import { AstNode, Config, Context, EtsScript, proceedToState } from "./arkts-api" + +import * as arkts from "./arkts-api" +export {arkts, global as arktsGlobal} diff --git a/koala-wrapper/src/generated/Es2pandaEnums.ts b/koala-wrapper/src/generated/Es2pandaEnums.ts new file mode 100644 index 000000000..cc682d5a3 --- /dev/null +++ b/koala-wrapper/src/generated/Es2pandaEnums.ts @@ -0,0 +1,1266 @@ +/* + * Copyright (c) 2022-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. + */ + +// RENAMED: es2panda_ContextState -> Es2pandaContextState +export enum Es2pandaContextState { + ES2PANDA_STATE_NEW = 0, + ES2PANDA_STATE_PARSED = 1, + ES2PANDA_STATE_SCOPE_INITED = 2, + ES2PANDA_STATE_BOUND = 3, + ES2PANDA_STATE_CHECKED = 4, + ES2PANDA_STATE_LOWERED = 5, + ES2PANDA_STATE_ASM_GENERATED = 6, + ES2PANDA_STATE_BIN_GENERATED = 7, + ES2PANDA_STATE_ERROR = 8 +} +// export enum Es2pandaAstNodeType { +// AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION = 0, +// AST_NODE_TYPE_ANNOTATION_DECLARATION = 1, +// AST_NODE_TYPE_ANNOTATION_USAGE = 2, +// AST_NODE_TYPE_ASSERT_STATEMENT = 3, +// AST_NODE_TYPE_AWAIT_EXPRESSION = 4, +// AST_NODE_TYPE_BIGINT_LITERAL = 5, +// AST_NODE_TYPE_BINARY_EXPRESSION = 6, +// AST_NODE_TYPE_BLOCK_STATEMENT = 7, +// AST_NODE_TYPE_BOOLEAN_LITERAL = 8, +// AST_NODE_TYPE_BREAK_STATEMENT = 9, +// AST_NODE_TYPE_CALL_EXPRESSION = 10, +// AST_NODE_TYPE_CATCH_CLAUSE = 11, +// AST_NODE_TYPE_CHAIN_EXPRESSION = 12, +// AST_NODE_TYPE_CHAR_LITERAL = 13, +// AST_NODE_TYPE_CLASS_DEFINITION = 14, +// AST_NODE_TYPE_CLASS_DECLARATION = 15, +// AST_NODE_TYPE_CLASS_EXPRESSION = 16, +// AST_NODE_TYPE_CLASS_PROPERTY = 17, +// AST_NODE_TYPE_CLASS_STATIC_BLOCK = 18, +// AST_NODE_TYPE_CONDITIONAL_EXPRESSION = 19, +// AST_NODE_TYPE_CONTINUE_STATEMENT = 20, +// AST_NODE_TYPE_DEBUGGER_STATEMENT = 21, +// AST_NODE_TYPE_DECORATOR = 22, +// AST_NODE_TYPE_DIRECT_EVAL = 23, +// AST_NODE_TYPE_DO_WHILE_STATEMENT = 24, +// AST_NODE_TYPE_EMPTY_STATEMENT = 25, +// AST_NODE_TYPE_EXPORT_ALL_DECLARATION = 26, +// AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION = 27, +// AST_NODE_TYPE_EXPORT_NAMED_DECLARATION = 28, +// AST_NODE_TYPE_EXPORT_SPECIFIER = 29, +// AST_NODE_TYPE_EXPRESSION_STATEMENT = 30, +// AST_NODE_TYPE_FOR_IN_STATEMENT = 31, +// AST_NODE_TYPE_FOR_OF_STATEMENT = 32, +// AST_NODE_TYPE_FOR_UPDATE_STATEMENT = 33, +// AST_NODE_TYPE_FUNCTION_DECLARATION = 34, +// AST_NODE_TYPE_FUNCTION_EXPRESSION = 35, +// AST_NODE_TYPE_IDENTIFIER = 36, +// AST_NODE_TYPE_DUMMYNODE = 37, +// AST_NODE_TYPE_IF_STATEMENT = 38, +// AST_NODE_TYPE_IMPORT_DECLARATION = 39, +// AST_NODE_TYPE_IMPORT_EXPRESSION = 40, +// AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER = 41, +// AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER = 42, +// AST_NODE_TYPE_IMPORT_SPECIFIER = 43, +// AST_NODE_TYPE_LABELLED_STATEMENT = 44, +// AST_NODE_TYPE_MEMBER_EXPRESSION = 45, +// AST_NODE_TYPE_META_PROPERTY_EXPRESSION = 46, +// AST_NODE_TYPE_METHOD_DEFINITION = 47, +// AST_NODE_TYPE_NAMED_TYPE = 48, +// AST_NODE_TYPE_NAMESPACE_DECLARATION = 49, +// AST_NODE_TYPE_NAMESPACE_DEFINITION = 50, +// AST_NODE_TYPE_NEW_EXPRESSION = 51, +// AST_NODE_TYPE_NULL_LITERAL = 52, +// AST_NODE_TYPE_UNDEFINED_LITERAL = 53, +// AST_NODE_TYPE_NUMBER_LITERAL = 54, +// AST_NODE_TYPE_OMITTED_EXPRESSION = 55, +// AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION = 56, +// AST_NODE_TYPE_PROPERTY = 57, +// AST_NODE_TYPE_REGEXP_LITERAL = 58, +// AST_NODE_TYPE_REEXPORT_STATEMENT = 59, +// AST_NODE_TYPE_RETURN_STATEMENT = 60, +// AST_NODE_TYPE_SCRIPT_FUNCTION = 61, +// AST_NODE_TYPE_SEQUENCE_EXPRESSION = 62, +// AST_NODE_TYPE_STRING_LITERAL = 63, +// AST_NODE_TYPE_ETS_NULL_TYPE = 64, +// AST_NODE_TYPE_ETS_UNDEFINED_TYPE = 65, +// AST_NODE_TYPE_ETS_NEVER_TYPE = 66, +// AST_NODE_TYPE_ETS_STRING_LITERAL_TYPE = 67, +// AST_NODE_TYPE_ETS_FUNCTION_TYPE = 68, +// AST_NODE_TYPE_ETS_WILDCARD_TYPE = 69, +// AST_NODE_TYPE_ETS_PRIMITIVE_TYPE = 70, +// AST_NODE_TYPE_ETS_PACKAGE_DECLARATION = 71, +// AST_NODE_TYPE_ETS_CLASS_LITERAL = 72, +// AST_NODE_TYPE_ETS_TYPE_REFERENCE = 73, +// AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART = 74, +// AST_NODE_TYPE_ETS_UNION_TYPE = 75, +// AST_NODE_TYPE_ETS_LAUNCH_EXPRESSION = 76, +// AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION = 77, +// AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION = 78, +// AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION = 79, +// AST_NODE_TYPE_ETS_IMPORT_DECLARATION = 80, +// AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION = 81, +// AST_NODE_TYPE_ETS_TUPLE = 82, +// AST_NODE_TYPE_ETS_SCRIPT = 83, +// AST_NODE_TYPE_SUPER_EXPRESSION = 84, +// AST_NODE_TYPE_STRUCT_DECLARATION = 85, +// AST_NODE_TYPE_SWITCH_CASE_STATEMENT = 86, +// AST_NODE_TYPE_SWITCH_STATEMENT = 87, +// AST_NODE_TYPE_TS_ENUM_DECLARATION = 88, +// AST_NODE_TYPE_TS_ENUM_MEMBER = 89, +// AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE = 90, +// AST_NODE_TYPE_TS_NUMBER_KEYWORD = 91, +// AST_NODE_TYPE_TS_ANY_KEYWORD = 92, +// AST_NODE_TYPE_TS_STRING_KEYWORD = 93, +// AST_NODE_TYPE_TS_BOOLEAN_KEYWORD = 94, +// AST_NODE_TYPE_TS_VOID_KEYWORD = 95, +// AST_NODE_TYPE_TS_UNDEFINED_KEYWORD = 96, +// AST_NODE_TYPE_TS_UNKNOWN_KEYWORD = 97, +// AST_NODE_TYPE_TS_OBJECT_KEYWORD = 98, +// AST_NODE_TYPE_TS_BIGINT_KEYWORD = 99, +// AST_NODE_TYPE_TS_NEVER_KEYWORD = 100, +// AST_NODE_TYPE_TS_NON_NULL_EXPRESSION = 101, +// AST_NODE_TYPE_TS_NULL_KEYWORD = 102, +// AST_NODE_TYPE_TS_ARRAY_TYPE = 103, +// AST_NODE_TYPE_TS_UNION_TYPE = 104, +// AST_NODE_TYPE_TS_TYPE_LITERAL = 105, +// AST_NODE_TYPE_TS_PROPERTY_SIGNATURE = 106, +// AST_NODE_TYPE_TS_METHOD_SIGNATURE = 107, +// AST_NODE_TYPE_TS_SIGNATURE_DECLARATION = 108, +// AST_NODE_TYPE_TS_PARENT_TYPE = 109, +// AST_NODE_TYPE_TS_LITERAL_TYPE = 110, +// AST_NODE_TYPE_TS_INFER_TYPE = 111, +// AST_NODE_TYPE_TS_CONDITIONAL_TYPE = 112, +// AST_NODE_TYPE_TS_IMPORT_TYPE = 113, +// AST_NODE_TYPE_TS_INTERSECTION_TYPE = 114, +// AST_NODE_TYPE_TS_MAPPED_TYPE = 115, +// AST_NODE_TYPE_TS_MODULE_BLOCK = 116, +// AST_NODE_TYPE_TS_THIS_TYPE = 117, +// AST_NODE_TYPE_TS_TYPE_OPERATOR = 118, +// AST_NODE_TYPE_TS_TYPE_PARAMETER = 119, +// AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION = 120, +// AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION = 121, +// AST_NODE_TYPE_TS_TYPE_PREDICATE = 122, +// AST_NODE_TYPE_TS_PARAMETER_PROPERTY = 123, +// AST_NODE_TYPE_TS_MODULE_DECLARATION = 124, +// AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION = 125, +// AST_NODE_TYPE_TS_FUNCTION_TYPE = 126, +// AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE = 127, +// AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION = 128, +// AST_NODE_TYPE_TS_TYPE_REFERENCE = 129, +// AST_NODE_TYPE_TS_QUALIFIED_NAME = 130, +// AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE = 131, +// AST_NODE_TYPE_TS_INTERFACE_DECLARATION = 132, +// AST_NODE_TYPE_TS_INTERFACE_BODY = 133, +// AST_NODE_TYPE_TS_INTERFACE_HERITAGE = 134, +// AST_NODE_TYPE_TS_TUPLE_TYPE = 135, +// AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER = 136, +// AST_NODE_TYPE_TS_INDEX_SIGNATURE = 137, +// AST_NODE_TYPE_TS_TYPE_QUERY = 138, +// AST_NODE_TYPE_TS_AS_EXPRESSION = 139, +// AST_NODE_TYPE_TS_CLASS_IMPLEMENTS = 140, +// AST_NODE_TYPE_TS_TYPE_ASSERTION = 141, +// AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION = 142, +// AST_NODE_TYPE_TEMPLATE_ELEMENT = 143, +// AST_NODE_TYPE_TEMPLATE_LITERAL = 144, +// AST_NODE_TYPE_THIS_EXPRESSION = 145, +// AST_NODE_TYPE_TYPEOF_EXPRESSION = 146, +// AST_NODE_TYPE_THROW_STATEMENT = 147, +// AST_NODE_TYPE_TRY_STATEMENT = 148, +// AST_NODE_TYPE_UNARY_EXPRESSION = 149, +// AST_NODE_TYPE_UPDATE_EXPRESSION = 150, +// AST_NODE_TYPE_VARIABLE_DECLARATION = 151, +// AST_NODE_TYPE_VARIABLE_DECLARATOR = 152, +// AST_NODE_TYPE_WHILE_STATEMENT = 153, +// AST_NODE_TYPE_YIELD_EXPRESSION = 154, +// AST_NODE_TYPE_OPAQUE_TYPE_NODE = 155, +// AST_NODE_TYPE_BLOCK_EXPRESSION = 156, +// AST_NODE_TYPE_ERROR_TYPE_NODE = 157, +// AST_NODE_TYPE_ARRAY_EXPRESSION = 158, +// AST_NODE_TYPE_ARRAY_PATTERN = 159, +// AST_NODE_TYPE_ASSIGNMENT_EXPRESSION = 160, +// AST_NODE_TYPE_ASSIGNMENT_PATTERN = 161, +// AST_NODE_TYPE_OBJECT_EXPRESSION = 162, +// AST_NODE_TYPE_OBJECT_PATTERN = 163, +// AST_NODE_TYPE_SPREAD_ELEMENT = 164, +// AST_NODE_TYPE_REST_ELEMENT = 165 +// } +export enum Es2pandaScopeType { + SCOPE_TYPE_PARAM = 0, + SCOPE_TYPE_CATCH_PARAM = 1, + SCOPE_TYPE_FUNCTION_PARAM = 2, + SCOPE_TYPE_CATCH = 3, + SCOPE_TYPE_CLASS = 4, + SCOPE_TYPE_ANNOTATION = 5, + SCOPE_TYPE_ANNOTATIONPARAMSCOPE = 6, + SCOPE_TYPE_LOCAL = 7, + SCOPE_TYPE_LOCAL_WITH_ALIAS = 8, + SCOPE_TYPE_LOOP = 9, + SCOPE_TYPE_LOOP_DECL = 10, + SCOPE_TYPE_FUNCTION = 11, + SCOPE_TYPE_GLOBAL = 12, + SCOPE_TYPE_MODULE = 13 +} +export enum Es2pandaDeclType { + DECL_TYPE_NONE = 0, + DECL_TYPE_VAR = 1, + DECL_TYPE_LET = 2, + DECL_TYPE_CONST = 3, + DECL_TYPE_LABEL = 4, + DECL_TYPE_READONLY = 5, + DECL_TYPE_FUNC = 6, + DECL_TYPE_PARAM = 7, + DECL_TYPE_IMPORT = 8, + DECL_TYPE_DYNAMIC_IMPORT = 9, + DECL_TYPE_EXPORT = 10, + DECL_TYPE_ANNOTATIONDECL = 11, + DECL_TYPE_ANNOTATIONUSAGE = 12, + DECL_TYPE_TYPE_ALIAS = 13, + DECL_TYPE_NAMESPACE = 14, + DECL_TYPE_INTERFACE = 15, + DECL_TYPE_ENUM_LITERAL = 16, + DECL_TYPE_TYPE_PARAMETER = 17, + DECL_TYPE_PROPERTY = 18, + DECL_TYPE_CLASS = 19, + DECL_TYPE_METHOD = 20, + DECL_TYPE_ENUM = 21 +} +export enum Es2pandaResolveBindingOptions { + RESOLVE_BINDING_OPTIONS_BINDINGS = 0, + RESOLVE_BINDING_OPTIONS_INTERFACES = 1, + RESOLVE_BINDING_OPTIONS_VARIABLES = 2, + RESOLVE_BINDING_OPTIONS_METHODS = 4, + RESOLVE_BINDING_OPTIONS_DECLARATION = 8, + RESOLVE_BINDING_OPTIONS_STATIC_VARIABLES = 16, + RESOLVE_BINDING_OPTIONS_STATIC_METHODS = 32, + RESOLVE_BINDING_OPTIONS_STATIC_DECLARATION = 64, + RESOLVE_BINDING_OPTIONS_TYPE_ALIASES = 128, + RESOLVE_BINDING_OPTIONS_ALL = 256, + RESOLVE_BINDING_OPTIONS_ALL_NON_TYPE = 512, + RESOLVE_BINDING_OPTIONS_ALL_VARIABLES = 18, + RESOLVE_BINDING_OPTIONS_ALL_METHOD = 36, + RESOLVE_BINDING_OPTIONS_ALL_DECLARATION = 72, + RESOLVE_BINDING_OPTIONS_ALL_STATIC = 112, + RESOLVE_BINDING_OPTIONS_ALL_NON_STATIC = 14, + RESOLVE_BINDING_OPTIONS_LAST = 128 +} +export enum Es2pandaVariableKind { + VARIABLE_KIND_NONE = 0, + VARIABLE_KIND_VAR = 1, + VARIABLE_KIND_LEXICAL = 2, + VARIABLE_KIND_FUNCTION = 3, + VARIABLE_KIND_MODULE = 4 +} +export enum Es2pandaLetOrConstStatus { + LET_OR_CONST_STATUS_INITIALIZED = 0, + LET_OR_CONST_STATUS_UNINITIALIZED = 1 +} +export enum Es2pandaScopeFlags { + SCOPE_FLAGS_NONE = 0, + SCOPE_FLAGS_SET_LEXICAL_FUNCTION = 1, + SCOPE_FLAGS_USE_ARGS = 2, + SCOPE_FLAGS_USE_SUPER = 4, + SCOPE_FLAGS_INNER_ARROW = 8, + SCOPE_FLAGS_NO_REG_STORE = 16, + SCOPE_FLAGS_DECL_SCOPE = 32, + SCOPE_FLAGS_FIELD_SCOPE = 64, + SCOPE_FLAGS_METHOD_SCOPE = 128, + SCOPE_FLAGS_STATIC = 256, + SCOPE_FLAGS_TYPE_ALIAS = 512, + SCOPE_FLAGS_LOOP_SCOPE = 1024, + SCOPE_FLAGS_STATIC_DECL_SCOPE = 288, + SCOPE_FLAGS_STATIC_FIELD_SCOPE = 320, + SCOPE_FLAGS_STATIC_METHOD_SCOPE = 384 +} +export enum Es2pandaEnum { + ENUM_NODE_HAS_PARENT = 0, + ENUM_NODE_HAS_SOURCE_RANGE = 1, + ENUM_EVERY_CHILD_HAS_VALID_PARENT = 2, + ENUM_EVERY_CHILD_IN_PARENT_RANGE = 3, + ENUM_CHECK_STRUCT_DECLARATION = 4, + ENUM_VARIABLE_HAS_SCOPE = 5, + ENUM_NODE_HAS_TYPE = 6, + ENUM_NO_PRIMITIVE_TYPES = 7, + ENUM_IDENTIFIER_HAS_VARIABLE = 8, + ENUM_REFERENCE_TYPE_ANNOTATION_IS_NULL = 9, + ENUM_ARITHMETIC_OPERATION_VALID = 10, + ENUM_SEQUENCE_EXPRESSION_HAS_LAST_TYPE = 11, + ENUM_CHECK_INFINITE_LOOP = 12, + ENUM_FOR_LOOP_CORRECTLY_INITIALIZED = 13, + ENUM_VARIABLE_HAS_ENCLOSING_SCOPE = 14, + ENUM_MODIFIER_ACCESS_VALID = 15, + ENUM_VARIABLE_NAME_IDENTIFIER_NAME_SAME = 16, + ENUM_CHECK_ABSTRACT_METHOD = 17, + ENUM_GETTER_SETTER_VALIDATION = 18, + ENUM_CHECK_SCOPE_DECLARATION = 19, + ENUM_CHECK_CONST_PROPERTIES = 20, + ENUM_COUNT = 21, + ENUM_BASE_FIRST = 0, + ENUM_BASE_LAST = 3, + ENUM_AFTER_PLUGINS_AFTER_PARSE_FIRST = 4, + ENUM_AFTER_PLUGINS_AFTER_PARSE_LAST = 4, + ENUM_AFTER_SCOPES_INIT_PHASE_FIRST = 5, + ENUM_AFTER_SCOPES_INIT_PHASE_LAST = 5, + ENUM_AFTER_CHECKER_PHASE_FIRST = 6, + ENUM_AFTER_CHECKER_PHASE_LAST = 20, + ENUM_FIRST = 0, + ENUM_LAST = 20, + ENUM_INVALID = 21 +} +export enum Es2pandaRegExpFlags { + REG_EXP_FLAGS_EMPTY = 0, + REG_EXP_FLAGS_GLOBAL = 1, + REG_EXP_FLAGS_IGNORE_CASE = 2, + REG_EXP_FLAGS_MULTILINE = 4, + REG_EXP_FLAGS_DOTALL = 8, + REG_EXP_FLAGS_UNICODE = 16, + REG_EXP_FLAGS_STICKY = 32 +} +export enum Es2pandaId { + ID_AS = 0, + ID_JS = 1, + ID_TS = 2, + ID_ETS = 3, + ID_COUNT = 4 +} +export enum Es2pandaTokenType { + TOKEN_TYPE_EOS = 0, + TOKEN_TYPE_LITERAL_IDENT = 1, + TOKEN_TYPE_LITERAL_STRING = 2, + TOKEN_TYPE_LITERAL_CHAR = 3, + TOKEN_TYPE_LITERAL_NUMBER = 4, + TOKEN_TYPE_LITERAL_REGEXP = 5, + TOKEN_TYPE_PUNCTUATOR_BITWISE_AND = 6, + TOKEN_TYPE_PUNCTUATOR_BITWISE_OR = 7, + TOKEN_TYPE_PUNCTUATOR_MULTIPLY = 8, + TOKEN_TYPE_PUNCTUATOR_DIVIDE = 9, + TOKEN_TYPE_PUNCTUATOR_MINUS = 10, + TOKEN_TYPE_PUNCTUATOR_EXCLAMATION_MARK = 11, + TOKEN_TYPE_PUNCTUATOR_TILDE = 12, + TOKEN_TYPE_PUNCTUATOR_MINUS_MINUS = 13, + TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT = 14, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT = 15, + TOKEN_TYPE_PUNCTUATOR_LESS_THAN_EQUAL = 16, + TOKEN_TYPE_PUNCTUATOR_GREATER_THAN_EQUAL = 17, + TOKEN_TYPE_PUNCTUATOR_MOD = 18, + TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR = 19, + TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION = 20, + TOKEN_TYPE_PUNCTUATOR_MULTIPLY_EQUAL = 21, + TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION_EQUAL = 22, + TOKEN_TYPE_PUNCTUATOR_ARROW = 23, + TOKEN_TYPE_PUNCTUATOR_BACK_TICK = 24, + TOKEN_TYPE_PUNCTUATOR_HASH_MARK = 25, + TOKEN_TYPE_PUNCTUATOR_DIVIDE_EQUAL = 26, + TOKEN_TYPE_PUNCTUATOR_MOD_EQUAL = 27, + TOKEN_TYPE_PUNCTUATOR_MINUS_EQUAL = 28, + TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT_EQUAL = 29, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT_EQUAL = 30, + TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT = 31, + TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT_EQUAL = 32, + TOKEN_TYPE_PUNCTUATOR_BITWISE_AND_EQUAL = 33, + TOKEN_TYPE_PUNCTUATOR_BITWISE_OR_EQUAL = 34, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND_EQUAL = 35, + TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING = 36, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR_EQUAL = 37, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_NULLISH_EQUAL = 38, + TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR_EQUAL = 39, + TOKEN_TYPE_PUNCTUATOR_PLUS = 40, + TOKEN_TYPE_PUNCTUATOR_PLUS_PLUS = 41, + TOKEN_TYPE_PUNCTUATOR_PLUS_EQUAL = 42, + TOKEN_TYPE_PUNCTUATOR_LESS_THAN = 43, + TOKEN_TYPE_PUNCTUATOR_GREATER_THAN = 44, + TOKEN_TYPE_PUNCTUATOR_EQUAL = 45, + TOKEN_TYPE_PUNCTUATOR_NOT_EQUAL = 46, + TOKEN_TYPE_PUNCTUATOR_STRICT_EQUAL = 47, + TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL = 48, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND = 49, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR = 50, + TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION = 51, + TOKEN_TYPE_PUNCTUATOR_QUESTION_MARK = 52, + TOKEN_TYPE_PUNCTUATOR_QUESTION_DOT = 53, + TOKEN_TYPE_PUNCTUATOR_AT = 54, + TOKEN_TYPE_PUNCTUATOR_FORMAT = 55, + TOKEN_TYPE_PUNCTUATOR_RIGHT_PARENTHESIS = 56, + TOKEN_TYPE_PUNCTUATOR_LEFT_PARENTHESIS = 57, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SQUARE_BRACKET = 58, + TOKEN_TYPE_PUNCTUATOR_LEFT_SQUARE_BRACKET = 59, + TOKEN_TYPE_PUNCTUATOR_RIGHT_BRACE = 60, + TOKEN_TYPE_PUNCTUATOR_PERIOD = 61, + TOKEN_TYPE_PUNCTUATOR_PERIOD_PERIOD_PERIOD = 62, + TOKEN_TYPE_PUNCTUATOR_PERIOD_QUESTION = 63, + TOKEN_TYPE_PUNCTUATOR_LEFT_BRACE = 64, + TOKEN_TYPE_PUNCTUATOR_SEMI_COLON = 65, + TOKEN_TYPE_PUNCTUATOR_COLON = 66, + TOKEN_TYPE_PUNCTUATOR_COMMA = 67, + TOKEN_TYPE_KEYW_ABSTRACT = 68, + TOKEN_TYPE_KEYW_ANY = 69, + TOKEN_TYPE_KEYW_ANYREF = 70, + TOKEN_TYPE_KEYW_ARGUMENTS = 71, + TOKEN_TYPE_KEYW_AS = 72, + TOKEN_TYPE_KEYW_ASSERT = 73, + TOKEN_TYPE_KEYW_ASSERTS = 74, + TOKEN_TYPE_KEYW_ASYNC = 75, + TOKEN_TYPE_KEYW_AWAIT = 76, + TOKEN_TYPE_KEYW_BIGINT = 77, + TOKEN_TYPE_KEYW_BOOLEAN = 78, + TOKEN_TYPE_KEYW_BREAK = 79, + TOKEN_TYPE_KEYW_BYTE = 80, + TOKEN_TYPE_KEYW_CASE = 81, + TOKEN_TYPE_KEYW_CATCH = 82, + TOKEN_TYPE_KEYW_CHAR = 83, + TOKEN_TYPE_KEYW_CLASS = 84, + TOKEN_TYPE_KEYW_CONST = 85, + TOKEN_TYPE_KEYW_CONSTRUCTOR = 86, + TOKEN_TYPE_KEYW_CONTINUE = 87, + TOKEN_TYPE_KEYW_DATAREF = 88, + TOKEN_TYPE_KEYW_DEBUGGER = 89, + TOKEN_TYPE_KEYW_DECLARE = 90, + TOKEN_TYPE_KEYW_DEFAULT = 91, + TOKEN_TYPE_KEYW_DELETE = 92, + TOKEN_TYPE_KEYW_DO = 93, + TOKEN_TYPE_KEYW_DOUBLE = 94, + TOKEN_TYPE_KEYW_ELSE = 95, + TOKEN_TYPE_KEYW_ENUM = 96, + TOKEN_TYPE_KEYW_EQREF = 97, + TOKEN_TYPE_KEYW_EVAL = 98, + TOKEN_TYPE_KEYW_EXPORT = 99, + TOKEN_TYPE_KEYW_EXTENDS = 100, + TOKEN_TYPE_KEYW_EXTERNREF = 101, + TOKEN_TYPE_KEYW_F32 = 102, + TOKEN_TYPE_KEYW_F64 = 103, + TOKEN_TYPE_LITERAL_FALSE = 104, + TOKEN_TYPE_KEYW_FINALLY = 105, + TOKEN_TYPE_KEYW_FLOAT = 106, + TOKEN_TYPE_KEYW_FOR = 107, + TOKEN_TYPE_KEYW_FROM = 108, + TOKEN_TYPE_KEYW_FUNCREF = 109, + TOKEN_TYPE_KEYW_FUNCTION = 110, + TOKEN_TYPE_KEYW_GET = 111, + TOKEN_TYPE_KEYW_GLOBAL = 112, + TOKEN_TYPE_KEYW_I8 = 113, + TOKEN_TYPE_KEYW_I16 = 114, + TOKEN_TYPE_KEYW_I31REF = 115, + TOKEN_TYPE_KEYW_I32 = 116, + TOKEN_TYPE_KEYW_I64 = 117, + TOKEN_TYPE_KEYW_IF = 118, + TOKEN_TYPE_KEYW_IMPLEMENTS = 119, + TOKEN_TYPE_KEYW_IMPORT = 120, + TOKEN_TYPE_KEYW_IN = 121, + TOKEN_TYPE_KEYW_INFER = 122, + TOKEN_TYPE_KEYW_INSTANCEOF = 123, + TOKEN_TYPE_KEYW_INT = 124, + TOKEN_TYPE_KEYW_INTERFACE = 125, + TOKEN_TYPE_KEYW_IS = 126, + TOKEN_TYPE_KEYW_ISIZE = 127, + TOKEN_TYPE_KEYW_KEYOF = 128, + TOKEN_TYPE_KEYW_LET = 129, + TOKEN_TYPE_KEYW_LAUNCH = 130, + TOKEN_TYPE_KEYW_LONG = 131, + TOKEN_TYPE_KEYW_META = 132, + TOKEN_TYPE_KEYW_MODULE = 133, + TOKEN_TYPE_KEYW_NAMESPACE = 134, + TOKEN_TYPE_KEYW_NATIVE = 135, + TOKEN_TYPE_KEYW_NEVER = 136, + TOKEN_TYPE_KEYW_NEW = 137, + TOKEN_TYPE_LITERAL_NULL = 138, + TOKEN_TYPE_KEYW_NUMBER = 139, + TOKEN_TYPE_KEYW_OBJECT = 140, + TOKEN_TYPE_KEYW_OF = 141, + TOKEN_TYPE_KEYW_FINAL = 142, + TOKEN_TYPE_KEYW_OUT = 143, + TOKEN_TYPE_KEYW_OVERRIDE = 144, + TOKEN_TYPE_KEYW_PACKAGE = 145, + TOKEN_TYPE_KEYW_INTERNAL = 146, + TOKEN_TYPE_KEYW_PRIVATE = 147, + TOKEN_TYPE_KEYW_PROTECTED = 148, + TOKEN_TYPE_KEYW_PUBLIC = 149, + TOKEN_TYPE_KEYW_READONLY = 150, + TOKEN_TYPE_KEYW_RETHROWS = 151, + TOKEN_TYPE_KEYW_RETURN = 152, + TOKEN_TYPE_KEYW_REQUIRE = 153, + TOKEN_TYPE_KEYW_SET = 154, + TOKEN_TYPE_KEYW_SHORT = 155, + TOKEN_TYPE_KEYW_STATIC = 156, + TOKEN_TYPE_KEYW_STRING = 157, + TOKEN_TYPE_KEYW_STRUCT = 158, + TOKEN_TYPE_KEYW_SUPER = 159, + TOKEN_TYPE_KEYW_SWITCH = 160, + TOKEN_TYPE_KEYW_TARGET = 161, + TOKEN_TYPE_KEYW_THIS = 162, + TOKEN_TYPE_KEYW_THROW = 163, + TOKEN_TYPE_KEYW_THROWS = 164, + TOKEN_TYPE_LITERAL_TRUE = 165, + TOKEN_TYPE_KEYW_TRY = 166, + TOKEN_TYPE_KEYW_TYPE = 167, + TOKEN_TYPE_KEYW_TYPEOF = 168, + TOKEN_TYPE_KEYW_U8 = 169, + TOKEN_TYPE_KEYW_U16 = 170, + TOKEN_TYPE_KEYW_U32 = 171, + TOKEN_TYPE_KEYW_U64 = 172, + TOKEN_TYPE_KEYW_UNDEFINED = 173, + TOKEN_TYPE_KEYW_UNKNOWN = 174, + TOKEN_TYPE_KEYW_USIZE = 175, + TOKEN_TYPE_KEYW_V128 = 176, + TOKEN_TYPE_KEYW_VAR = 177, + TOKEN_TYPE_KEYW_VOID = 178, + TOKEN_TYPE_KEYW_WHILE = 179, + TOKEN_TYPE_KEYW_WITH = 180, + TOKEN_TYPE_KEYW_YIELD = 181, + TOKEN_TYPE_FIRST_PUNCTUATOR = 6, + TOKEN_TYPE_FIRST_KEYW = 68 +} +export enum Es2pandaAstNodeFlags { + AST_NODE_FLAGS_NO_OPTS = 0, + AST_NODE_FLAGS_CHECKCAST = 1, + AST_NODE_FLAGS_CONVERT_TO_STRING = 2, + AST_NODE_FLAGS_ALLOW_REQUIRED_INSTANTIATION = 4, + AST_NODE_FLAGS_HAS_EXPORT_ALIAS = 8, + AST_NODE_FLAGS_GENERATE_VALUE_OF = 16, + AST_NODE_FLAGS_GENERATE_GET_NAME = 32, + AST_NODE_FLAGS_RECHECK = 64 +} +export enum Es2pandaModifierFlags { + MODIFIER_FLAGS_NONE = 0, + MODIFIER_FLAGS_STATIC = 1, + MODIFIER_FLAGS_ASYNC = 2, + MODIFIER_FLAGS_PUBLIC = 4, + MODIFIER_FLAGS_PROTECTED = 8, + MODIFIER_FLAGS_PRIVATE = 16, + MODIFIER_FLAGS_DECLARE = 32, + MODIFIER_FLAGS_READONLY = 64, + MODIFIER_FLAGS_OPTIONAL = 128, + MODIFIER_FLAGS_DEFINITE = 256, + MODIFIER_FLAGS_ABSTRACT = 512, + MODIFIER_FLAGS_CONST = 1024, + MODIFIER_FLAGS_FINAL = 2048, + MODIFIER_FLAGS_NATIVE = 4096, + MODIFIER_FLAGS_OVERRIDE = 8192, + MODIFIER_FLAGS_CONSTRUCTOR = 16384, + MODIFIER_FLAGS_SYNCHRONIZED = 32768, + MODIFIER_FLAGS_FUNCTIONAL = 65536, + MODIFIER_FLAGS_IN = 131072, + MODIFIER_FLAGS_OUT = 262144, + MODIFIER_FLAGS_INTERNAL = 524288, + MODIFIER_FLAGS_EXPORT = 1048576, + MODIFIER_FLAGS_GETTER = 2097152, + MODIFIER_FLAGS_SETTER = 4194304, + MODIFIER_FLAGS_DEFAULT_EXPORT = 8388608, + MODIFIER_FLAGS_EXPORT_TYPE = 16777216, + MODIFIER_FLAGS_SUPER_OWNER = 33554432, + MODIFIER_FLAGS_ANNOTATION_DECLARATION = 67108864, + MODIFIER_FLAGS_ANNOTATION_USAGE = 134217728, + MODIFIER_FLAGS_READONLY_PARAMETER = 268435456, + MODIFIER_FLAGS_ACCESS = 524316, + MODIFIER_FLAGS_ALL = 524927, + MODIFIER_FLAGS_ALLOWED_IN_CTOR_PARAMETER = 524380, + MODIFIER_FLAGS_INTERNAL_PROTECTED = 524296, + MODIFIER_FLAGS_ACCESSOR_MODIFIERS = 2560, + MODIFIER_FLAGS_GETTER_SETTER = 6291456, + MODIFIER_FLAGS_EXPORTED = 26214400 +} +export enum Es2pandaPrivateFieldKind { + PRIVATE_FIELD_KIND_FIELD = 0, + PRIVATE_FIELD_KIND_METHOD = 1, + PRIVATE_FIELD_KIND_GET = 2, + PRIVATE_FIELD_KIND_SET = 3, + PRIVATE_FIELD_KIND_STATIC_FIELD = 4, + PRIVATE_FIELD_KIND_STATIC_METHOD = 5, + PRIVATE_FIELD_KIND_STATIC_GET = 6, + PRIVATE_FIELD_KIND_STATIC_SET = 7 +} +export enum Es2pandaScriptFunctionFlags { + SCRIPT_FUNCTION_FLAGS_NONE = 0, + SCRIPT_FUNCTION_FLAGS_GENERATOR = 1, + SCRIPT_FUNCTION_FLAGS_ASYNC = 2, + SCRIPT_FUNCTION_FLAGS_ARROW = 4, + SCRIPT_FUNCTION_FLAGS_EXPRESSION = 8, + SCRIPT_FUNCTION_FLAGS_OVERLOAD = 16, + SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR = 32, + SCRIPT_FUNCTION_FLAGS_METHOD = 64, + SCRIPT_FUNCTION_FLAGS_STATIC_BLOCK = 128, + SCRIPT_FUNCTION_FLAGS_HIDDEN = 256, + SCRIPT_FUNCTION_FLAGS_IMPLICIT_SUPER_CALL_NEEDED = 512, + SCRIPT_FUNCTION_FLAGS_ENUM = 1024, + SCRIPT_FUNCTION_FLAGS_EXTERNAL = 2048, + SCRIPT_FUNCTION_FLAGS_PROXY = 4096, + SCRIPT_FUNCTION_FLAGS_THROWS = 8192, + SCRIPT_FUNCTION_FLAGS_RETHROWS = 16384, + SCRIPT_FUNCTION_FLAGS_GETTER = 32768, + SCRIPT_FUNCTION_FLAGS_SETTER = 65536, + SCRIPT_FUNCTION_FLAGS_ENTRY_POINT = 131072, + SCRIPT_FUNCTION_FLAGS_INSTANCE_EXTENSION_METHOD = 262144, + SCRIPT_FUNCTION_FLAGS_HAS_RETURN = 524288, + SCRIPT_FUNCTION_FLAGS_ASYNC_IMPL = 1048576, + SCRIPT_FUNCTION_FLAGS_EXTERNAL_OVERLOAD = 2097152, + SCRIPT_FUNCTION_FLAGS_HAS_THROW = 4194304 +} +export enum Es2pandaTSOperatorType { + TS_OPERATOR_TYPE_READONLY = 0, + TS_OPERATOR_TYPE_KEYOF = 1, + TS_OPERATOR_TYPE_UNIQUE = 2 +} +export enum Es2pandaMappedOption { + MAPPED_OPTION_NO_OPTS = 0, + MAPPED_OPTION_PLUS = 1, + MAPPED_OPTION_MINUS = 2 +} +export enum Es2pandaBoxingUnboxingFlags { + BOXING_UNBOXING_FLAGS_NONE = 0, + BOXING_UNBOXING_FLAGS_BOX_TO_BOOLEAN = 1, + BOXING_UNBOXING_FLAGS_BOX_TO_BYTE = 2, + BOXING_UNBOXING_FLAGS_BOX_TO_SHORT = 4, + BOXING_UNBOXING_FLAGS_BOX_TO_CHAR = 8, + BOXING_UNBOXING_FLAGS_BOX_TO_INT = 16, + BOXING_UNBOXING_FLAGS_BOX_TO_LONG = 32, + BOXING_UNBOXING_FLAGS_BOX_TO_FLOAT = 64, + BOXING_UNBOXING_FLAGS_BOX_TO_DOUBLE = 128, + BOXING_UNBOXING_FLAGS_BOX_TO_ENUM = 256, + BOXING_UNBOXING_FLAGS_UNBOX_TO_BOOLEAN = 512, + BOXING_UNBOXING_FLAGS_UNBOX_TO_BYTE = 1024, + BOXING_UNBOXING_FLAGS_UNBOX_TO_SHORT = 2048, + BOXING_UNBOXING_FLAGS_UNBOX_TO_CHAR = 4096, + BOXING_UNBOXING_FLAGS_UNBOX_TO_INT = 8192, + BOXING_UNBOXING_FLAGS_UNBOX_TO_LONG = 16384, + BOXING_UNBOXING_FLAGS_UNBOX_TO_FLOAT = 32768, + BOXING_UNBOXING_FLAGS_UNBOX_TO_DOUBLE = 65536, + BOXING_UNBOXING_FLAGS_UNBOX_TO_ENUM = 131072, + BOXING_UNBOXING_FLAGS_BOXING_FLAG = 511, + BOXING_UNBOXING_FLAGS_UNBOXING_FLAG = 261632 +} +export enum Es2pandaClassDefinitionModifiers { + CLASS_DEFINITION_MODIFIERS_NONE = 0, + CLASS_DEFINITION_MODIFIERS_DECLARATION = 1, + CLASS_DEFINITION_MODIFIERS_ID_REQUIRED = 2, + CLASS_DEFINITION_MODIFIERS_GLOBAL = 4, + CLASS_DEFINITION_MODIFIERS_HAS_SUPER = 8, + CLASS_DEFINITION_MODIFIERS_SET_CTOR_ID = 16, + CLASS_DEFINITION_MODIFIERS_EXTERN = 32, + CLASS_DEFINITION_MODIFIERS_ANONYMOUS = 64, + CLASS_DEFINITION_MODIFIERS_GLOBAL_INITIALIZED = 128, + CLASS_DEFINITION_MODIFIERS_CLASS_DECL = 256, + CLASS_DEFINITION_MODIFIERS_INNER = 512, + CLASS_DEFINITION_MODIFIERS_FROM_EXTERNAL = 1024, + CLASS_DEFINITION_MODIFIERS_LOCAL = 2048, + CLASS_DEFINITION_MODIFIERS_CLASSDEFINITION_CHECKED = 4096, + CLASS_DEFINITION_MODIFIERS_NAMESPACE_TRANSFORMED = 8192, + CLASS_DEFINITION_MODIFIERS_DECLARATION_ID_REQUIRED = 3, + CLASS_DEFINITION_MODIFIERS_ETS_MODULE = 8196 +} +export enum Es2pandaOperandKind { + OPERAND_KIND_SRC_VREG = 0, + OPERAND_KIND_DST_VREG = 1, + OPERAND_KIND_SRC_DST_VREG = 2, + OPERAND_KIND_IMM = 3, + OPERAND_KIND_ID = 4, + OPERAND_KIND_STRING_ID = 5, + OPERAND_KIND_LABEL = 6 +} +export enum Es2pandaOperandType { + OPERAND_TYPE_REF = 0, + OPERAND_TYPE_B32 = 1, + OPERAND_TYPE_B64 = 2, + OPERAND_TYPE_ANY = 3, + OPERAND_TYPE_NONE = 4 +} +export enum Es2pandaTypeRelationFlag { + TYPE_RELATION_FLAG_NONE = 0, + TYPE_RELATION_FLAG_NARROWING = 1, + TYPE_RELATION_FLAG_WIDENING = 2, + TYPE_RELATION_FLAG_BOXING = 4, + TYPE_RELATION_FLAG_UNBOXING = 8, + TYPE_RELATION_FLAG_CAPTURE = 16, + TYPE_RELATION_FLAG_STRING = 32, + TYPE_RELATION_FLAG_VALUE_SET = 64, + TYPE_RELATION_FLAG_UNCHECKED = 128, + TYPE_RELATION_FLAG_NO_THROW = 256, + TYPE_RELATION_FLAG_SELF_REFERENCE = 512, + TYPE_RELATION_FLAG_NO_RETURN_TYPE_CHECK = 1024, + TYPE_RELATION_FLAG_DIRECT_RETURN = 2048, + TYPE_RELATION_FLAG_NO_WIDENING = 4096, + TYPE_RELATION_FLAG_NO_BOXING = 8192, + TYPE_RELATION_FLAG_NO_UNBOXING = 16384, + TYPE_RELATION_FLAG_ONLY_CHECK_WIDENING = 32768, + TYPE_RELATION_FLAG_ONLY_CHECK_BOXING_UNBOXING = 65536, + TYPE_RELATION_FLAG_IN_ASSIGNMENT_CONTEXT = 131072, + TYPE_RELATION_FLAG_IN_CASTING_CONTEXT = 262144, + TYPE_RELATION_FLAG_UNCHECKED_CAST = 524288, + TYPE_RELATION_FLAG_IGNORE_TYPE_PARAMETERS = 1048576, + TYPE_RELATION_FLAG_CHECK_PROXY = 2097152, + TYPE_RELATION_FLAG_NO_CHECK_TRAILING_LAMBDA = 4194304, + TYPE_RELATION_FLAG_NO_THROW_GENERIC_TYPEALIAS = 8388608, + TYPE_RELATION_FLAG_OVERRIDING_CONTEXT = 16777216, + TYPE_RELATION_FLAG_IGNORE_REST_PARAM = 33554432, + TYPE_RELATION_FLAG_STRING_TO_CHAR = 67108864, + TYPE_RELATION_FLAG_ASSIGNMENT_CONTEXT = 14, + TYPE_RELATION_FLAG_BRIDGE_CHECK = 17826816, + TYPE_RELATION_FLAG_CASTING_CONTEXT = 524303 +} +export enum Es2pandaRelationResult { + RELATION_RESULT_TRUE = 0, + RELATION_RESULT_FALSE = 1, + RELATION_RESULT_UNKNOWN = 2, + RELATION_RESULT_MAYBE = 3, + RELATION_RESULT_CACHE_MISS = 4, + RELATION_RESULT_ERROR = 5 +} +export enum Es2pandaRelationType { + RELATION_TYPE_COMPARABLE = 0, + RELATION_TYPE_ASSIGNABLE = 1, + RELATION_TYPE_IDENTICAL = 2, + RELATION_TYPE_UNCHECKED_CASTABLE = 3, + RELATION_TYPE_SUPERTYPE = 4 +} +export enum Es2pandaImportKinds { + IMPORT_KINDS_VALUE = 0, + IMPORT_KINDS_TYPE = 1 +} +export enum Es2pandaPropertyKind { + PROPERTY_KIND_INIT = 0, + PROPERTY_KIND_GET = 1, + PROPERTY_KIND_SET = 2, + PROPERTY_KIND_PROTO = 3 +} +export enum Es2pandaConstant { + CONSTANT_PROP_NULL = 0, + CONSTANT_PROP_UNDEFINED = 1, + CONSTANT_EMPTY_ARRAY = 2 +} +export enum Es2pandaTSSignatureDeclarationKind { + TS_SIGNATURE_DECLARATION_KIND_CALL_SIGNATURE = 0, + TS_SIGNATURE_DECLARATION_KIND_CONSTRUCT_SIGNATURE = 1 +} +export enum Es2pandaTSIndexSignatureKind { + TS_INDEX_SIGNATURE_KIND_NUMBER = 0, + TS_INDEX_SIGNATURE_KIND_STRING = 1 +} +export enum Es2pandaEnumLiteralTypeKind { + ENUM_LITERAL_TYPE_KIND_NUMERIC = 0, + ENUM_LITERAL_TYPE_KIND_LITERAL = 1 +} +export enum Es2pandaIdentifierFlags { + IDENTIFIER_FLAGS_NONE = 0, + IDENTIFIER_FLAGS_OPTIONAL = 1, + IDENTIFIER_FLAGS_TDZ = 2, + IDENTIFIER_FLAGS_PRIVATE = 4, + IDENTIFIER_FLAGS_GET = 8, + IDENTIFIER_FLAGS_SET = 16, + IDENTIFIER_FLAGS_IGNORE_BOX = 32, + IDENTIFIER_FLAGS_ANNOTATIONDECL = 64, + IDENTIFIER_FLAGS_ANNOTATIONUSAGE = 128, + IDENTIFIER_FLAGS_ERROR_PLACEHOLDER = 256, + IDENTIFIER_FLAGS_IMPLICIT_THIS = 512 +} +export enum Es2pandaMemberExpressionKind { + MEMBER_EXPRESSION_KIND_NONE = 0, + MEMBER_EXPRESSION_KIND_ELEMENT_ACCESS = 1, + MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS = 2, + MEMBER_EXPRESSION_KIND_GETTER = 4, + MEMBER_EXPRESSION_KIND_SETTER = 8, + MEMBER_EXPRESSION_KIND_EXTENSION_ACCESSOR = 16 +} +export enum Es2pandaTSTupleKind { + TS_TUPLE_KIND_NONE = 0, + TS_TUPLE_KIND_NAMED = 1, + TS_TUPLE_KIND_DEFAULT = 2 +} +export enum Es2pandaMetaPropertyKind { + META_PROPERTY_KIND_NEW_TARGET = 0, + META_PROPERTY_KIND_IMPORT_META = 1 +} +export enum Es2pandaModuleFlag { + MODULE_FLAG_NONE = 0, + MODULE_FLAG_ETSSCRIPT = 1, + MODULE_FLAG_NAMESPACE = 2, + MODULE_FLAG_NAMESPACE_CHAIN_LAST_NODE = 4 +} +export enum Es2pandaElementFlags { + ELEMENT_FLAGS_NO_OPTS = 0, + ELEMENT_FLAGS_REQUIRED = 1, + ELEMENT_FLAGS_OPTIONAL = 2, + ELEMENT_FLAGS_REST = 4, + ELEMENT_FLAGS_VARIADIC = 8, + ELEMENT_FLAGS_FIXED = 3, + ELEMENT_FLAGS_VARIABLE = 12, + ELEMENT_FLAGS_NON_REQUIRED = 14, + ELEMENT_FLAGS_NON_REST = 11 +} +export enum Es2pandaSignatureFlags { + SIGNATURE_FLAGS_NO_OPTS = 0, + SIGNATURE_FLAGS_VIRTUAL = 1, + SIGNATURE_FLAGS_ABSTRACT = 2, + SIGNATURE_FLAGS_CALL = 4, + SIGNATURE_FLAGS_CONSTRUCT = 8, + SIGNATURE_FLAGS_PUBLIC = 16, + SIGNATURE_FLAGS_PROTECTED = 32, + SIGNATURE_FLAGS_PRIVATE = 64, + SIGNATURE_FLAGS_STATIC = 128, + SIGNATURE_FLAGS_FINAL = 256, + SIGNATURE_FLAGS_CONSTRUCTOR = 512, + SIGNATURE_FLAGS_TYPE = 1024, + SIGNATURE_FLAGS_PROXY = 2048, + SIGNATURE_FLAGS_INTERNAL = 4096, + SIGNATURE_FLAGS_NEED_RETURN_TYPE = 8192, + SIGNATURE_FLAGS_INFERRED_RETURN_TYPE = 16384, + SIGNATURE_FLAGS_THIS_RETURN_TYPE = 32768, + SIGNATURE_FLAGS_GETTER = 65536, + SIGNATURE_FLAGS_SETTER = 131072, + SIGNATURE_FLAGS_THROWS = 262144, + SIGNATURE_FLAGS_RETHROWS = 524288, + SIGNATURE_FLAGS_EXTENSION_FUNCTION_RETURN_THIS = 1048576, + SIGNATURE_FLAGS_INTERNAL_PROTECTED = 4128, + SIGNATURE_FLAGS_GETTER_OR_SETTER = 196608, + SIGNATURE_FLAGS_THROWING = 786432, + SIGNATURE_FLAGS_FUNCTIONAL_INTERFACE_SIGNATURE = 1047 +} +export enum Es2pandaPrimitiveType { + PRIMITIVE_TYPE_BYTE = 0, + PRIMITIVE_TYPE_INT = 1, + PRIMITIVE_TYPE_LONG = 2, + PRIMITIVE_TYPE_SHORT = 3, + PRIMITIVE_TYPE_FLOAT = 4, + PRIMITIVE_TYPE_DOUBLE = 5, + PRIMITIVE_TYPE_BOOLEAN = 6, + PRIMITIVE_TYPE_CHAR = 7, + PRIMITIVE_TYPE_VOID = 8 +} +export enum Es2pandaObjectFlags { + OBJECT_FLAGS_NO_OPTS = 0, + OBJECT_FLAGS_CHECK_EXCESS_PROPS = 1, + OBJECT_FLAGS_RESOLVED_MEMBERS = 2, + OBJECT_FLAGS_RESOLVED_BASE_TYPES = 4, + OBJECT_FLAGS_RESOLVED_DECLARED_MEMBERS = 8 +} +export enum Es2pandaObjectTypeKind { + OBJECT_TYPE_KIND_LITERAL = 0, + OBJECT_TYPE_KIND_CLASS = 1, + OBJECT_TYPE_KIND_INTERFACE = 2, + OBJECT_TYPE_KIND_TUPLE = 3, + OBJECT_TYPE_KIND_FUNCTION = 4 +} +export enum Es2pandaVariableDeclaratorFlag { + VARIABLE_DECLARATOR_FLAG_LET = 0, + VARIABLE_DECLARATOR_FLAG_CONST = 1, + VARIABLE_DECLARATOR_FLAG_VAR = 2, + VARIABLE_DECLARATOR_FLAG_UNKNOWN = 3 +} +export enum Es2pandaTypeFacts { + TYPE_FACTS_NONE = 0, + TYPE_FACTS_TYPEOF_EQ_STRING = 1, + TYPE_FACTS_TYPEOF_EQ_NUMBER = 2, + TYPE_FACTS_TYPEOF_EQ_BIGINT = 4, + TYPE_FACTS_TYPEOF_EQ_BOOLEAN = 8, + TYPE_FACTS_TYPEOF_EQ_SYMBOL = 16, + TYPE_FACTS_TYPEOF_EQ_OBJECT = 32, + TYPE_FACTS_TYPEOF_EQ_FUNCTION = 64, + TYPE_FACTS_TYPEOF_EQ_HOST_OBJECT = 128, + TYPE_FACTS_TYPEOF_NE_STRING = 256, + TYPE_FACTS_TYPEOF_NE_NUMBER = 512, + TYPE_FACTS_TYPEOF_NE_BIGINT = 1024, + TYPE_FACTS_TYPEOF_NE_BOOLEAN = 2048, + TYPE_FACTS_TYPEOF_NE_SYMBOL = 4096, + TYPE_FACTS_TYPEOF_NE_OBJECT = 8192, + TYPE_FACTS_TYPEOF_NE_FUNCTION = 16384, + TYPE_FACTS_TYPEOF_NE_HOST_OBJECT = 32768, + TYPE_FACTS_EQ_UNDEFINED = 65536, + TYPE_FACTS_EQ_NULL = 131072, + TYPE_FACTS_EQ_UNDEFINED_OR_NULL = 262144, + TYPE_FACTS_NE_UNDEFINED = 524288, + TYPE_FACTS_NE_NULL = 1048576, + TYPE_FACTS_NE_UNDEFINED_OR_NULL = 2097152, + TYPE_FACTS_TRUTHY = 4194304, + TYPE_FACTS_FALSY = 8388608, + TYPE_FACTS_ALL = 16777216, + TYPE_FACTS_LAST = 8388608, + TYPE_FACTS_BASE_NUMBER_STRICT_FACTS = 3734786, + TYPE_FACTS_BASE_NUMBER_FACTS = 12582146, + TYPE_FACTS_NUMBER_FACTS = 16776450, + TYPE_FACTS_ZERO_NUMBER_STRICT_FACTS = 12123394, + TYPE_FACTS_ZERO_NUMBER_FACTS = 12582146, + TYPE_FACTS_NON_ZERO_NUMBER_FACTS = 16776450, + TYPE_FACTS_BASE_STRING_STRICT_FACTS = 3735041, + TYPE_FACTS_BASE_STRING_FACTS = 12582401, + TYPE_FACTS_STRING_FACTS = 16776705, + TYPE_FACTS_EMPTY_STRING_STRICT_FACTS = 16317953, + TYPE_FACTS_EMPTY_STRING_FACTS = 12582401, + TYPE_FACTS_NON_EMPTY_STRING_FACTS = 16776705, + TYPE_FACTS_BASE_BIGINT_STRICT_FACTS = 3734276, + TYPE_FACTS_BASE_BIGINT_FACTS = 12581636, + TYPE_FACTS_BIGINT_FACTS = 16775940, + TYPE_FACTS_ZERO_BIGINT_STRICT_FACTS = 12122884, + TYPE_FACTS_ZERO_BIGINT_FACTS = 12581636, + TYPE_FACTS_NON_ZERO_BIGINT_FACTS = 16775940, + TYPE_FACTS_BASE_BOOLEAN_STRICT_FACTS = 3733256, + TYPE_FACTS_BASE_BOOLEAN_FACTS = 12580616, + TYPE_FACTS_BOOLEAN_FACTS = 16774920, + TYPE_FACTS_FALSE_STRICT_FACTS = 12121864, + TYPE_FACTS_FALSE_FACTS = 12580616, + TYPE_FACTS_TRUE_STRICT_FACTS = 7927560, + TYPE_FACTS_TRUE_FACTS = 16774920, + TYPE_FACTS_OBJECT_STRICT_FACTS = 7888800, + TYPE_FACTS_OBJECT_FACTS = 16736160, + TYPE_FACTS_EMPTY_OBJECT_FACTS = 16777216, + TYPE_FACTS_FUNCTION_STRICT_FACTS = 7880640, + TYPE_FACTS_FUNCTION_FACTS = 16728000, + TYPE_FACTS_UNDEFINED_FACTS = 9830144, + TYPE_FACTS_NULL_FACTS = 9363232 +} +export enum Es2pandaGlobalTypeId { + GLOBAL_TYPE_ID_NUMBER = 0, + GLOBAL_TYPE_ID_ANY = 1, + GLOBAL_TYPE_ID_STRING = 2, + GLOBAL_TYPE_ID_BOOLEAN = 3, + GLOBAL_TYPE_ID_VOID = 4, + GLOBAL_TYPE_ID_NULL_ID = 5, + GLOBAL_TYPE_ID_UNDEFINED = 6, + GLOBAL_TYPE_ID_UNKNOWN = 7, + GLOBAL_TYPE_ID_NEVER = 8, + GLOBAL_TYPE_ID_NON_PRIMITIVE = 9, + GLOBAL_TYPE_ID_BIGINT = 10, + GLOBAL_TYPE_ID_FALSE_ID = 11, + GLOBAL_TYPE_ID_TRUE_ID = 12, + GLOBAL_TYPE_ID_NUMBER_OR_BIGINT = 13, + GLOBAL_TYPE_ID_STRING_OR_NUMBER = 14, + GLOBAL_TYPE_ID_ZERO = 15, + GLOBAL_TYPE_ID_EMPTY_STRING = 16, + GLOBAL_TYPE_ID_ZERO_BIGINT = 17, + GLOBAL_TYPE_ID_PRIMITIVE = 18, + GLOBAL_TYPE_ID_EMPTY_TUPLE = 19, + GLOBAL_TYPE_ID_EMPTY_OBJECT = 20, + GLOBAL_TYPE_ID_RESOLVING_RETURN_TYPE = 21, + GLOBAL_TYPE_ID_ERROR_TYPE = 22, + GLOBAL_TYPE_ID_BYTE = 23, + GLOBAL_TYPE_ID_SHORT = 24, + GLOBAL_TYPE_ID_INT = 25, + GLOBAL_TYPE_ID_LONG = 26, + GLOBAL_TYPE_ID_FLOAT = 27, + GLOBAL_TYPE_ID_DOUBLE = 28, + GLOBAL_TYPE_ID_CHAR = 29, + GLOBAL_TYPE_ID_ETS_BOOLEAN = 30, + GLOBAL_TYPE_ID_ETS_STRING = 31, + GLOBAL_TYPE_ID_ETS_VOID = 32, + GLOBAL_TYPE_ID_ETS_OBJECT_BUILTIN = 33, + GLOBAL_TYPE_ID_ETS_NULL = 34, + GLOBAL_TYPE_ID_ETS_UNDEFINED = 35, + GLOBAL_TYPE_ID_ETS_NULLISH_TYPE = 36, + GLOBAL_TYPE_ID_ETS_NEVER = 37, + GLOBAL_TYPE_ID_ETS_NULLISH_OBJECT = 38, + GLOBAL_TYPE_ID_ETS_WILDCARD = 39, + GLOBAL_TYPE_ID_ETS_BOOLEAN_BUILTIN = 40, + GLOBAL_TYPE_ID_ETS_BYTE_BUILTIN = 41, + GLOBAL_TYPE_ID_ETS_CHAR_BUILTIN = 42, + GLOBAL_TYPE_ID_ETS_COMPARABLE_BUILTIN = 43, + GLOBAL_TYPE_ID_ETS_CONSOLE_BUILTIN = 44, + GLOBAL_TYPE_ID_ETS_DATE_BUILTIN = 45, + GLOBAL_TYPE_ID_ETS_DOUBLE_BUILTIN = 46, + GLOBAL_TYPE_ID_ETS_EXCEPTION_BUILTIN = 47, + GLOBAL_TYPE_ID_ETS_FLOAT_BUILTIN = 48, + GLOBAL_TYPE_ID_ETS_FLOATING_BUILTIN = 49, + GLOBAL_TYPE_ID_ETS_INT_BUILTIN = 50, + GLOBAL_TYPE_ID_ETS_INTEGRAL_BUILTIN = 51, + GLOBAL_TYPE_ID_ETS_LONG_BUILTIN = 52, + GLOBAL_TYPE_ID_ETS_MAP_BUILTIN = 53, + GLOBAL_TYPE_ID_ETS_ERROR_BUILTIN = 54, + GLOBAL_TYPE_ID_ETS_RUNTIME_BUILTIN = 55, + GLOBAL_TYPE_ID_ETS_RUNTIME_LINKER_BUILTIN = 56, + GLOBAL_TYPE_ID_ETS_SET_BUILTIN = 57, + GLOBAL_TYPE_ID_ETS_SHORT_BUILTIN = 58, + GLOBAL_TYPE_ID_ETS_STACK_TRACE_ELEMENT_BUILTIN = 59, + GLOBAL_TYPE_ID_ETS_STACK_TRACE_BUILTIN = 60, + GLOBAL_TYPE_ID_ETS_ARRAY_INDEX_OUT_OF_BOUNDS_ERROR_BUILTIN = 61, + GLOBAL_TYPE_ID_ETS_ARITHMETIC_ERROR_BUILTIN = 62, + GLOBAL_TYPE_ID_ETS_CLASS_CAST_ERROR_BUILTIN = 63, + GLOBAL_TYPE_ID_ETS_ASSERTION_ERROR_BUILTIN = 64, + GLOBAL_TYPE_ID_ETS_DIVIDE_BY_ZERO_ERROR_BUILTIN = 65, + GLOBAL_TYPE_ID_ETS_NULL_POINTER_ERROR_BUILTIN = 66, + GLOBAL_TYPE_ID_ETS_UNCAUGHT_EXCEPTION_ERROR_BUILTIN = 67, + GLOBAL_TYPE_ID_ETS_STRING_BUILTIN = 68, + GLOBAL_TYPE_ID_ETS_STRING_BUILDER_BUILTIN = 69, + GLOBAL_TYPE_ID_ETS_TYPE_BUILTIN = 70, + GLOBAL_TYPE_ID_ETS_TYPES_BUILTIN = 71, + GLOBAL_TYPE_ID_ETS_PROMISE_BUILTIN = 72, + GLOBAL_TYPE_ID_ETS_REGEXP_BUILTIN = 73, + GLOBAL_TYPE_ID_ETS_ARRAY_BUILTIN = 74, + GLOBAL_TYPE_ID_ETS_INTEROP_JSRUNTIME_BUILTIN = 75, + GLOBAL_TYPE_ID_ETS_INTEROP_JSVALUE_BUILTIN = 76, + GLOBAL_TYPE_ID_ETS_BOX_BUILTIN = 77, + GLOBAL_TYPE_ID_ETS_BOOLEAN_BOX_BUILTIN = 78, + GLOBAL_TYPE_ID_ETS_BYTE_BOX_BUILTIN = 79, + GLOBAL_TYPE_ID_ETS_CHAR_BOX_BUILTIN = 80, + GLOBAL_TYPE_ID_ETS_SHORT_BOX_BUILTIN = 81, + GLOBAL_TYPE_ID_ETS_INT_BOX_BUILTIN = 82, + GLOBAL_TYPE_ID_ETS_LONG_BOX_BUILTIN = 83, + GLOBAL_TYPE_ID_ETS_FLOAT_BOX_BUILTIN = 84, + GLOBAL_TYPE_ID_ETS_DOUBLE_BOX_BUILTIN = 85, + GLOBAL_TYPE_ID_ETS_BIG_INT_BUILTIN = 86, + GLOBAL_TYPE_ID_ETS_BIG_INT = 87, + GLOBAL_TYPE_ID_ETS_FUNCTION0_CLASS = 88, + GLOBAL_TYPE_ID_ETS_FUNCTION1_CLASS = 89, + GLOBAL_TYPE_ID_ETS_FUNCTION2_CLASS = 90, + GLOBAL_TYPE_ID_ETS_FUNCTION3_CLASS = 91, + GLOBAL_TYPE_ID_ETS_FUNCTION4_CLASS = 92, + GLOBAL_TYPE_ID_ETS_FUNCTION5_CLASS = 93, + GLOBAL_TYPE_ID_ETS_FUNCTION6_CLASS = 94, + GLOBAL_TYPE_ID_ETS_FUNCTION7_CLASS = 95, + GLOBAL_TYPE_ID_ETS_FUNCTION8_CLASS = 96, + GLOBAL_TYPE_ID_ETS_FUNCTION9_CLASS = 97, + GLOBAL_TYPE_ID_ETS_FUNCTION10_CLASS = 98, + GLOBAL_TYPE_ID_ETS_FUNCTION11_CLASS = 99, + GLOBAL_TYPE_ID_ETS_FUNCTION12_CLASS = 100, + GLOBAL_TYPE_ID_ETS_FUNCTION13_CLASS = 101, + GLOBAL_TYPE_ID_ETS_FUNCTION14_CLASS = 102, + GLOBAL_TYPE_ID_ETS_FUNCTION15_CLASS = 103, + GLOBAL_TYPE_ID_ETS_FUNCTION16_CLASS = 104, + GLOBAL_TYPE_ID_ETS_FUNCTIONN_CLASS = 105, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION0_CLASS = 106, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION1_CLASS = 107, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION2_CLASS = 108, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION3_CLASS = 109, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION4_CLASS = 110, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION5_CLASS = 111, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION6_CLASS = 112, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION7_CLASS = 113, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION8_CLASS = 114, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION9_CLASS = 115, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION10_CLASS = 116, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION11_CLASS = 117, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION12_CLASS = 118, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION13_CLASS = 119, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION14_CLASS = 120, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION15_CLASS = 121, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTION16_CLASS = 122, + GLOBAL_TYPE_ID_ETS_THROWING_FUNCTIONN_CLASS = 123, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION0_CLASS = 124, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION1_CLASS = 125, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION2_CLASS = 126, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION3_CLASS = 127, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION4_CLASS = 128, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION5_CLASS = 129, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION6_CLASS = 130, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION7_CLASS = 131, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION8_CLASS = 132, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION9_CLASS = 133, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION10_CLASS = 134, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION11_CLASS = 135, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION12_CLASS = 136, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION13_CLASS = 137, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION14_CLASS = 138, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION15_CLASS = 139, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTION16_CLASS = 140, + GLOBAL_TYPE_ID_ETS_RETHROWING_FUNCTIONN_CLASS = 141, + GLOBAL_TYPE_ID_TYPE_ERROR = 142, + GLOBAL_TYPE_ID_COUNT = 143 +} +export enum Es2pandaMethodDefinitionKind { + METHOD_DEFINITION_KIND_NONE = 0, + METHOD_DEFINITION_KIND_CONSTRUCTOR = 1, + METHOD_DEFINITION_KIND_METHOD = 2, + METHOD_DEFINITION_KIND_EXTENSION_METHOD = 3, + METHOD_DEFINITION_KIND_GET = 4, + METHOD_DEFINITION_KIND_SET = 5, + METHOD_DEFINITION_KIND_EXTENSION_GET = 6, + METHOD_DEFINITION_KIND_EXTENSION_SET = 7 +} +export enum Es2pandaETSObjectFlags { + ETS_OBJECT_FLAGS_NO_OPTS = 0, + ETS_OBJECT_FLAGS_CLASS = 1, + ETS_OBJECT_FLAGS_INTERFACE = 2, + ETS_OBJECT_FLAGS_INSTANCE = 4, + ETS_OBJECT_FLAGS_ABSTRACT = 8, + ETS_OBJECT_FLAGS_GLOBAL = 16, + ETS_OBJECT_FLAGS_ENUM = 32, + ETS_OBJECT_FLAGS_FUNCTIONAL = 64, + ETS_OBJECT_FLAGS_RESOLVED_INTERFACES = 128, + ETS_OBJECT_FLAGS_RESOLVED_SUPER = 256, + ETS_OBJECT_FLAGS_RESOLVED_TYPE_PARAMS = 512, + ETS_OBJECT_FLAGS_CHECKED_COMPATIBLE_ABSTRACTS = 1024, + ETS_OBJECT_FLAGS_STRING = 2048, + ETS_OBJECT_FLAGS_INCOMPLETE_INSTANTIATION = 4096, + ETS_OBJECT_FLAGS_INNER = 8192, + ETS_OBJECT_FLAGS_DYNAMIC = 16384, + ETS_OBJECT_FLAGS_ASYNC_FUNC_RETURN_TYPE = 32768, + ETS_OBJECT_FLAGS_CHECKED_INVOKE_LEGITIMACY = 65536, + ETS_OBJECT_FLAGS_REQUIRED = 131072, + ETS_OBJECT_FLAGS_READONLY = 262144, + ETS_OBJECT_FLAGS_BUILTIN_BIGINT = 524288, + ETS_OBJECT_FLAGS_BUILTIN_STRING = 1048576, + ETS_OBJECT_FLAGS_BUILTIN_BOOLEAN = 2097152, + ETS_OBJECT_FLAGS_BUILTIN_BYTE = 4194304, + ETS_OBJECT_FLAGS_BUILTIN_CHAR = 8388608, + ETS_OBJECT_FLAGS_BUILTIN_SHORT = 16777216, + ETS_OBJECT_FLAGS_BUILTIN_INT = 33554432, + ETS_OBJECT_FLAGS_BUILTIN_LONG = 67108864, + ETS_OBJECT_FLAGS_BUILTIN_FLOAT = 134217728, + ETS_OBJECT_FLAGS_BUILTIN_DOUBLE = 268435456, + ETS_OBJECT_FLAGS_BOXED_ENUM = 536870912, + ETS_OBJECT_FLAGS_EXTENSION_FUNCTION = 1073741824, + ETS_OBJECT_FLAGS_BUILTIN_NUMERIC = 524288000, + ETS_OBJECT_FLAGS_VALUE_TYPED = 535300096, + ETS_OBJECT_FLAGS_UNBOXABLE_TYPE = 1071644672, + ETS_OBJECT_FLAGS_BUILTIN_TYPE = 1073217536, + ETS_OBJECT_FLAGS_GLOBAL_CLASS = 17, + ETS_OBJECT_FLAGS_FUNCTIONAL_INTERFACE = 74, + ETS_OBJECT_FLAGS_RESOLVED_HEADER = 896 +} +export enum Es2pandaPropertySearchFlags { + PROPERTY_SEARCH_FLAGS_NO_OPTS = 0, + PROPERTY_SEARCH_FLAGS_SEARCH_INSTANCE_METHOD = 1, + PROPERTY_SEARCH_FLAGS_SEARCH_INSTANCE_FIELD = 2, + PROPERTY_SEARCH_FLAGS_SEARCH_INSTANCE_DECL = 4, + PROPERTY_SEARCH_FLAGS_SEARCH_STATIC_METHOD = 8, + PROPERTY_SEARCH_FLAGS_SEARCH_STATIC_FIELD = 16, + PROPERTY_SEARCH_FLAGS_SEARCH_STATIC_DECL = 32, + PROPERTY_SEARCH_FLAGS_SEARCH_IN_BASE = 64, + PROPERTY_SEARCH_FLAGS_SEARCH_IN_INTERFACES = 128, + PROPERTY_SEARCH_FLAGS_IGNORE_ABSTRACT = 256, + PROPERTY_SEARCH_FLAGS_ALLOW_FUNCTIONAL_INTERFACE = 512, + PROPERTY_SEARCH_FLAGS_DISALLOW_SYNTHETIC_METHOD_CREATION = 1024, + PROPERTY_SEARCH_FLAGS_IS_FUNCTIONAL = 2048, + PROPERTY_SEARCH_FLAGS_IS_SETTER = 4096, + PROPERTY_SEARCH_FLAGS_IS_GETTER = 8192, + PROPERTY_SEARCH_FLAGS_SEARCH_INSTANCE = 7, + PROPERTY_SEARCH_FLAGS_SEARCH_STATIC = 56, + PROPERTY_SEARCH_FLAGS_SEARCH_METHOD = 9, + PROPERTY_SEARCH_FLAGS_SEARCH_FIELD = 18, + PROPERTY_SEARCH_FLAGS_SEARCH_DECL = 36, + PROPERTY_SEARCH_FLAGS_SEARCH_ALL = 63 +} +export enum Es2pandaPropertyType { + PROPERTY_TYPE_INSTANCE_METHOD = 0, + PROPERTY_TYPE_INSTANCE_FIELD = 1, + PROPERTY_TYPE_INSTANCE_DECL = 2, + PROPERTY_TYPE_STATIC_METHOD = 3, + PROPERTY_TYPE_STATIC_FIELD = 4, + PROPERTY_TYPE_STATIC_DECL = 5, + PROPERTY_TYPE_COUNT = 6 +} +export enum Es2pandaVariableDeclarationKind { + VARIABLE_DECLARATION_KIND_CONST = 0, + VARIABLE_DECLARATION_KIND_LET = 1, + VARIABLE_DECLARATION_KIND_VAR = 2 +} +export enum Es2pandaAccessibilityOption { + ACCESSIBILITY_OPTION_NO_OPTS = 0, + ACCESSIBILITY_OPTION_PUBLIC = 1, + ACCESSIBILITY_OPTION_PRIVATE = 2, + ACCESSIBILITY_OPTION_PROTECTED = 3 +} +export enum Es2pandaRecordTableFlags { + RECORD_TABLE_FLAGS_NONE = 0, + RECORD_TABLE_FLAGS_EXTERNAL = 1 +} +export enum Es2pandaCheckerStatus { + CHECKER_STATUS_NO_OPTS = 0, + CHECKER_STATUS_FORCE_TUPLE = 1, + CHECKER_STATUS_IN_CONST_CONTEXT = 2, + CHECKER_STATUS_KEEP_LITERAL_TYPE = 4, + CHECKER_STATUS_IN_PARAMETER = 8, + CHECKER_STATUS_IN_CLASS = 16, + CHECKER_STATUS_IN_INTERFACE = 32, + CHECKER_STATUS_IN_ABSTRACT = 64, + CHECKER_STATUS_IN_STATIC_CONTEXT = 128, + CHECKER_STATUS_IN_CONSTRUCTOR = 256, + CHECKER_STATUS_IN_STATIC_BLOCK = 512, + CHECKER_STATUS_INNER_CLASS = 1024, + CHECKER_STATUS_IN_ENUM = 2048, + CHECKER_STATUS_BUILTINS_INITIALIZED = 4096, + CHECKER_STATUS_IN_LAMBDA = 8192, + CHECKER_STATUS_IGNORE_VISIBILITY = 16384, + CHECKER_STATUS_IN_EXTENSION_METHOD = 32768, + CHECKER_STATUS_IN_LOCAL_CLASS = 65536, + CHECKER_STATUS_IN_INSTANCEOF_CONTEXT = 131072, + CHECKER_STATUS_IN_TEST_EXPRESSION = 262144, + CHECKER_STATUS_IN_LOOP = 524288, + CHECKER_STATUS_MEET_RETURN = 1048576, + CHECKER_STATUS_MEET_BREAK = 2097152, + CHECKER_STATUS_MEET_CONTINUE = 4194304, + CHECKER_STATUS_MEET_THROW = 8388608, + CHECKER_STATUS_IN_EXTERNAL = 16777216, + CHECKER_STATUS_IN_BRIDGE_TEST = 33554432, + CHECKER_STATUS_IN_GETTER = 67108864, + CHECKER_STATUS_IN_SETTER = 134217728, + CHECKER_STATUS_IN_EXTENSION_ACCESSOR_CHECK = 268435456 +} +export enum Es2pandaOverrideErrorCode { + OVERRIDE_ERROR_CODE_NO_ERROR = 0, + OVERRIDE_ERROR_CODE_OVERRIDDEN_FINAL = 1, + OVERRIDE_ERROR_CODE_INCOMPATIBLE_RETURN = 2, + OVERRIDE_ERROR_CODE_INCOMPATIBLE_TYPEPARAM = 3, + OVERRIDE_ERROR_CODE_OVERRIDDEN_WEAKER = 4 +} +export enum Es2pandaResolvedKind { + RESOLVED_KIND_PROPERTY = 0, + RESOLVED_KIND_EXTENSION_FUNCTION = 1, + RESOLVED_KIND_EXTENSION_ACCESSOR = 2 +} +export enum Es2pandaLexicalScopeType { + LEXICAL_SCOPE_TYPE_BLOCK = 0, + LEXICAL_SCOPE_TYPE_STRICT_BLOCK = 1, + LEXICAL_SCOPE_TYPE_CATCH = 2, + LEXICAL_SCOPE_TYPE_FUNCTION_PARAM = 3, + LEXICAL_SCOPE_TYPE_TS_TYPE_LITERAL = 4 +} +export enum Es2pandaVariableParsingFlags { + VARIABLE_PARSING_FLAGS_NO_OPTS = 0, + VARIABLE_PARSING_FLAGS_NO_SKIP_VAR_KIND = 1, + VARIABLE_PARSING_FLAGS_ACCEPT_CONST_NO_INIT = 2, + VARIABLE_PARSING_FLAGS_DISALLOW_INIT = 4, + VARIABLE_PARSING_FLAGS_VAR = 8, + VARIABLE_PARSING_FLAGS_LET = 16, + VARIABLE_PARSING_FLAGS_CONST = 32, + VARIABLE_PARSING_FLAGS_STOP_AT_IN = 64, + VARIABLE_PARSING_FLAGS_IN_FOR = 128, + VARIABLE_PARSING_FLAGS_FOR_OF = 256 +} +export enum Es2pandaExpressionParseFlags { + EXPRESSION_PARSE_FLAGS_NO_OPTS = 0, + EXPRESSION_PARSE_FLAGS_ACCEPT_COMMA = 1, + EXPRESSION_PARSE_FLAGS_ACCEPT_REST = 2, + EXPRESSION_PARSE_FLAGS_EXP_DISALLOW_AS = 4, + EXPRESSION_PARSE_FLAGS_DISALLOW_ASSIGNMENT = 8, + EXPRESSION_PARSE_FLAGS_DISALLOW_YIELD = 16, + EXPRESSION_PARSE_FLAGS_STOP_AT_IN = 32, + EXPRESSION_PARSE_FLAGS_MUST_BE_PATTERN = 64, + EXPRESSION_PARSE_FLAGS_POTENTIALLY_IN_PATTERN = 128, + EXPRESSION_PARSE_FLAGS_OBJECT_PATTERN = 256, + EXPRESSION_PARSE_FLAGS_IN_REST = 512, + EXPRESSION_PARSE_FLAGS_IMPORT = 1024, + EXPRESSION_PARSE_FLAGS_POTENTIAL_CLASS_LITERAL = 2048, + EXPRESSION_PARSE_FLAGS_IN_FOR = 4096, + EXPRESSION_PARSE_FLAGS_INSTANCEOF = 8192, + EXPRESSION_PARSE_FLAGS_POTENTIAL_NEW_ARRAY = 16384 +} +export enum Es2pandaStatementParsingFlags { + STATEMENT_PARSING_FLAGS_NONE = 0, + STATEMENT_PARSING_FLAGS_ALLOW_LEXICAL = 1, + STATEMENT_PARSING_FLAGS_GLOBAL = 2, + STATEMENT_PARSING_FLAGS_IF_ELSE = 4, + STATEMENT_PARSING_FLAGS_LABELLED = 8, + STATEMENT_PARSING_FLAGS_STMT_LEXICAL_SCOPE_NEEDED = 12, + STATEMENT_PARSING_FLAGS_STMT_GLOBAL_LEXICAL = 3 +} +export enum Es2pandaForStatementKind { + FOR_STATEMENT_KIND_UPDATE = 0, + FOR_STATEMENT_KIND_IN = 1, + FOR_STATEMENT_KIND_OF = 2 +} +export enum Es2pandaCompilationMode { + COMPILATION_MODE_GEN_STD_LIB = 0, + COMPILATION_MODE_PROJECT = 1, + COMPILATION_MODE_SINGLE_FILE = 2 +} +export enum Es2pandaCheckDecision { + CHECK_DECISION_CORRECT = 0, + CHECK_DECISION_INCORRECT = 1 +} +export enum Es2pandaCheckAction { + CHECK_ACTION_CONTINUE = 0, + CHECK_ACTION_SKIP_SUBTREE = 1 +} diff --git a/koala-wrapper/src/generated/Es2pandaNativeModule.ts b/koala-wrapper/src/generated/Es2pandaNativeModule.ts new file mode 100644 index 000000000..51040c02b --- /dev/null +++ b/koala-wrapper/src/generated/Es2pandaNativeModule.ts @@ -0,0 +1,3715 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + KNativePointer, + KStringPtr, + KUInt, + KInt, + KBoolean, + KDouble, + KFloat, + KLong +} from "@koalaui/interop" + +// TODO: this type should be in interop +export type KNativePointerArray = BigUint64Array + +export class Es2pandaNativeModule { + _CreateLabelledStatement(context: KNativePointer, ident: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'CreateLabelledStatement was not overloaded by native module initialization") + } + _UpdateLabelledStatement(context: KNativePointer, original: KNativePointer, ident: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'UpdateLabelledStatement was not overloaded by native module initialization") + } + _LabelledStatementBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'LabelledStatementBodyConst was not overloaded by native module initialization") + } + _LabelledStatementIdentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'LabelledStatementIdentConst was not overloaded by native module initialization") + } + _LabelledStatementIdent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'LabelledStatementIdent was not overloaded by native module initialization") + } + _LabelledStatementGetReferencedStatementConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'LabelledStatementGetReferencedStatementConst was not overloaded by native module initialization") + } + _CreateThrowStatement(context: KNativePointer, argument: KNativePointer): KNativePointer { + throw new Error("'CreateThrowStatement was not overloaded by native module initialization") + } + _UpdateThrowStatement(context: KNativePointer, original: KNativePointer, argument: KNativePointer): KNativePointer { + throw new Error("'UpdateThrowStatement was not overloaded by native module initialization") + } + _ThrowStatementArgumentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ThrowStatementArgumentConst was not overloaded by native module initialization") + } + _CreateClassProperty(context: KNativePointer, key: KNativePointer, value: KNativePointer, typeAnnotation: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer { + throw new Error("'CreateClassProperty was not overloaded by native module initialization") + } + _UpdateClassProperty(context: KNativePointer, original: KNativePointer, key: KNativePointer, value: KNativePointer, typeAnnotation: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer { + throw new Error("'UpdateClassProperty was not overloaded by native module initialization") + } + _ClassPropertyTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassPropertyTypeAnnotationConst was not overloaded by native module initialization") + } + _ClassPropertySetTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'ClassPropertySetTypeAnnotation was not overloaded by native module initialization") + } + _ClassPropertyAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassPropertyAnnotations was not overloaded by native module initialization") + } + _ClassPropertyAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassPropertyAnnotationsConst was not overloaded by native module initialization") + } + _ClassPropertySetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'ClassPropertySetAnnotations was not overloaded by native module initialization") + } + _CreateTSVoidKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSVoidKeyword was not overloaded by native module initialization") + } + _UpdateTSVoidKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSVoidKeyword was not overloaded by native module initialization") + } + _CreateETSFunctionTypeIr(context: KNativePointer, signature: KNativePointer, funcFlags: KInt): KNativePointer { + throw new Error("'CreateETSFunctionTypeIr was not overloaded by native module initialization") + } + _UpdateETSFunctionTypeIr(context: KNativePointer, original: KNativePointer, signature: KNativePointer, funcFlags: KInt): KNativePointer { + throw new Error("'UpdateETSFunctionTypeIr was not overloaded by native module initialization") + } + _ETSFunctionTypeIrTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSFunctionTypeIrTypeParamsConst was not overloaded by native module initialization") + } + _ETSFunctionTypeIrTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSFunctionTypeIrTypeParams was not overloaded by native module initialization") + } + _ETSFunctionTypeIrParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSFunctionTypeIrParamsConst was not overloaded by native module initialization") + } + _ETSFunctionTypeIrReturnTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSFunctionTypeIrReturnTypeConst was not overloaded by native module initialization") + } + _ETSFunctionTypeIrReturnType(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSFunctionTypeIrReturnType was not overloaded by native module initialization") + } + _ETSFunctionTypeIrFunctionalInterface(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSFunctionTypeIrFunctionalInterface was not overloaded by native module initialization") + } + _ETSFunctionTypeIrFunctionalInterfaceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSFunctionTypeIrFunctionalInterfaceConst was not overloaded by native module initialization") + } + _ETSFunctionTypeIrSetFunctionalInterface(context: KNativePointer, receiver: KNativePointer, functionalInterface: KNativePointer): void { + throw new Error("'ETSFunctionTypeIrSetFunctionalInterface was not overloaded by native module initialization") + } + _ETSFunctionTypeIrFlags(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'ETSFunctionTypeIrFlags was not overloaded by native module initialization") + } + _ETSFunctionTypeIrIsThrowingConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSFunctionTypeIrIsThrowingConst was not overloaded by native module initialization") + } + _ETSFunctionTypeIrIsRethrowingConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSFunctionTypeIrIsRethrowingConst was not overloaded by native module initialization") + } + _ETSFunctionTypeIrIsExtensionFunctionConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSFunctionTypeIrIsExtensionFunctionConst was not overloaded by native module initialization") + } + _CreateTSTypeOperator(context: KNativePointer, type: KNativePointer, operatorType: KInt): KNativePointer { + throw new Error("'CreateTSTypeOperator was not overloaded by native module initialization") + } + _UpdateTSTypeOperator(context: KNativePointer, original: KNativePointer, type: KNativePointer, operatorType: KInt): KNativePointer { + throw new Error("'UpdateTSTypeOperator was not overloaded by native module initialization") + } + _TSTypeOperatorTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeOperatorTypeConst was not overloaded by native module initialization") + } + _TSTypeOperatorIsReadonlyConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSTypeOperatorIsReadonlyConst was not overloaded by native module initialization") + } + _TSTypeOperatorIsKeyofConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSTypeOperatorIsKeyofConst was not overloaded by native module initialization") + } + _TSTypeOperatorIsUniqueConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSTypeOperatorIsUniqueConst was not overloaded by native module initialization") + } + _CreateIfStatement(context: KNativePointer, test: KNativePointer, consequent: KNativePointer, alternate: KNativePointer): KNativePointer { + throw new Error("'CreateIfStatement was not overloaded by native module initialization") + } + _UpdateIfStatement(context: KNativePointer, original: KNativePointer, test: KNativePointer, consequent: KNativePointer, alternate: KNativePointer): KNativePointer { + throw new Error("'UpdateIfStatement was not overloaded by native module initialization") + } + _IfStatementTestConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IfStatementTestConst was not overloaded by native module initialization") + } + _IfStatementTest(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IfStatementTest was not overloaded by native module initialization") + } + _IfStatementConsequentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IfStatementConsequentConst was not overloaded by native module initialization") + } + _IfStatementConsequent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IfStatementConsequent was not overloaded by native module initialization") + } + _IfStatementAlternate(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IfStatementAlternate was not overloaded by native module initialization") + } + _IfStatementAlternateConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IfStatementAlternateConst was not overloaded by native module initialization") + } + _CreateTSConstructorType(context: KNativePointer, signature: KNativePointer, abstract: KBoolean): KNativePointer { + throw new Error("'CreateTSConstructorType was not overloaded by native module initialization") + } + _UpdateTSConstructorType(context: KNativePointer, original: KNativePointer, signature: KNativePointer, abstract: KBoolean): KNativePointer { + throw new Error("'UpdateTSConstructorType was not overloaded by native module initialization") + } + _TSConstructorTypeTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConstructorTypeTypeParamsConst was not overloaded by native module initialization") + } + _TSConstructorTypeTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConstructorTypeTypeParams was not overloaded by native module initialization") + } + _TSConstructorTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConstructorTypeParamsConst was not overloaded by native module initialization") + } + _TSConstructorTypeReturnTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConstructorTypeReturnTypeConst was not overloaded by native module initialization") + } + _TSConstructorTypeReturnType(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConstructorTypeReturnType was not overloaded by native module initialization") + } + _TSConstructorTypeAbstractConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSConstructorTypeAbstractConst was not overloaded by native module initialization") + } + _CreateDecorator(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateDecorator was not overloaded by native module initialization") + } + _UpdateDecorator(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateDecorator was not overloaded by native module initialization") + } + _DecoratorExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'DecoratorExprConst was not overloaded by native module initialization") + } + _CreateTSEnumDeclaration(context: KNativePointer, key: KNativePointer, members: BigUint64Array, membersSequenceLength: KUInt, isConst: KBoolean, isStatic: KBoolean, isDeclare: KBoolean): KNativePointer { + throw new Error("'CreateTSEnumDeclaration was not overloaded by native module initialization") + } + _UpdateTSEnumDeclaration(context: KNativePointer, original: KNativePointer, key: KNativePointer, members: BigUint64Array, membersSequenceLength: KUInt, isConst: KBoolean, isStatic: KBoolean, isDeclare: KBoolean): KNativePointer { + throw new Error("'UpdateTSEnumDeclaration was not overloaded by native module initialization") + } + _TSEnumDeclarationKeyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumDeclarationKeyConst was not overloaded by native module initialization") + } + _TSEnumDeclarationKey(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumDeclarationKey was not overloaded by native module initialization") + } + _TSEnumDeclarationMembersConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumDeclarationMembersConst was not overloaded by native module initialization") + } + _TSEnumDeclarationInternalNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'TSEnumDeclarationInternalNameConst was not overloaded by native module initialization") + } + _TSEnumDeclarationSetInternalName(context: KNativePointer, receiver: KNativePointer, internalName: KStringPtr): void { + throw new Error("'TSEnumDeclarationSetInternalName was not overloaded by native module initialization") + } + _TSEnumDeclarationBoxedClassConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumDeclarationBoxedClassConst was not overloaded by native module initialization") + } + _TSEnumDeclarationSetBoxedClass(context: KNativePointer, receiver: KNativePointer, wrapperClass: KNativePointer): void { + throw new Error("'TSEnumDeclarationSetBoxedClass was not overloaded by native module initialization") + } + _TSEnumDeclarationIsConstConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSEnumDeclarationIsConstConst was not overloaded by native module initialization") + } + _TSEnumDeclarationDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumDeclarationDecoratorsConst was not overloaded by native module initialization") + } + _CreateTSNeverKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSNeverKeyword was not overloaded by native module initialization") + } + _UpdateTSNeverKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSNeverKeyword was not overloaded by native module initialization") + } + _CreateImportDefaultSpecifier(context: KNativePointer, local: KNativePointer): KNativePointer { + throw new Error("'CreateImportDefaultSpecifier was not overloaded by native module initialization") + } + _UpdateImportDefaultSpecifier(context: KNativePointer, original: KNativePointer, local: KNativePointer): KNativePointer { + throw new Error("'UpdateImportDefaultSpecifier was not overloaded by native module initialization") + } + _ImportDefaultSpecifierLocalConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportDefaultSpecifierLocalConst was not overloaded by native module initialization") + } + _ImportDefaultSpecifierLocal(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportDefaultSpecifierLocal was not overloaded by native module initialization") + } + _CreateObjectExpression(context: KNativePointer, nodeType: KInt, properties: BigUint64Array, propertiesSequenceLength: KUInt, trailingComma: KBoolean): KNativePointer { + throw new Error("'CreateObjectExpression was not overloaded by native module initialization") + } + _UpdateObjectExpression(context: KNativePointer, original: KNativePointer, nodeType: KInt, properties: BigUint64Array, propertiesSequenceLength: KUInt, trailingComma: KBoolean): KNativePointer { + throw new Error("'UpdateObjectExpression was not overloaded by native module initialization") + } + _ObjectExpressionPropertiesConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ObjectExpressionPropertiesConst was not overloaded by native module initialization") + } + _ObjectExpressionIsDeclarationConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ObjectExpressionIsDeclarationConst was not overloaded by native module initialization") + } + _ObjectExpressionIsOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ObjectExpressionIsOptionalConst was not overloaded by native module initialization") + } + _ObjectExpressionDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ObjectExpressionDecoratorsConst was not overloaded by native module initialization") + } + _ObjectExpressionValidateExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ObjectExpressionValidateExpression was not overloaded by native module initialization") + } + _ObjectExpressionConvertibleToObjectPattern(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ObjectExpressionConvertibleToObjectPattern was not overloaded by native module initialization") + } + _ObjectExpressionSetDeclaration(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ObjectExpressionSetDeclaration was not overloaded by native module initialization") + } + _ObjectExpressionSetOptional(context: KNativePointer, receiver: KNativePointer, optional_arg: KBoolean): void { + throw new Error("'ObjectExpressionSetOptional was not overloaded by native module initialization") + } + _ObjectExpressionTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ObjectExpressionTypeAnnotationConst was not overloaded by native module initialization") + } + _ObjectExpressionSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'ObjectExpressionSetTsTypeAnnotation was not overloaded by native module initialization") + } + _CreateImportSpecifier(context: KNativePointer, imported: KNativePointer, local: KNativePointer): KNativePointer { + throw new Error("'CreateImportSpecifier was not overloaded by native module initialization") + } + _UpdateImportSpecifier(context: KNativePointer, original: KNativePointer, imported: KNativePointer, local: KNativePointer): KNativePointer { + throw new Error("'UpdateImportSpecifier was not overloaded by native module initialization") + } + _ImportSpecifierImported(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportSpecifierImported was not overloaded by native module initialization") + } + _ImportSpecifierImportedConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportSpecifierImportedConst was not overloaded by native module initialization") + } + _ImportSpecifierLocal(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportSpecifierLocal was not overloaded by native module initialization") + } + _ImportSpecifierLocalConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportSpecifierLocalConst was not overloaded by native module initialization") + } + _CreateConditionalExpression(context: KNativePointer, test: KNativePointer, consequent: KNativePointer, alternate: KNativePointer): KNativePointer { + throw new Error("'CreateConditionalExpression was not overloaded by native module initialization") + } + _UpdateConditionalExpression(context: KNativePointer, original: KNativePointer, test: KNativePointer, consequent: KNativePointer, alternate: KNativePointer): KNativePointer { + throw new Error("'UpdateConditionalExpression was not overloaded by native module initialization") + } + _ConditionalExpressionTestConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ConditionalExpressionTestConst was not overloaded by native module initialization") + } + _ConditionalExpressionTest(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ConditionalExpressionTest was not overloaded by native module initialization") + } + _ConditionalExpressionSetTest(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'ConditionalExpressionSetTest was not overloaded by native module initialization") + } + _ConditionalExpressionConsequentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ConditionalExpressionConsequentConst was not overloaded by native module initialization") + } + _ConditionalExpressionConsequent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ConditionalExpressionConsequent was not overloaded by native module initialization") + } + _ConditionalExpressionSetConsequent(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'ConditionalExpressionSetConsequent was not overloaded by native module initialization") + } + _ConditionalExpressionAlternateConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ConditionalExpressionAlternateConst was not overloaded by native module initialization") + } + _ConditionalExpressionAlternate(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ConditionalExpressionAlternate was not overloaded by native module initialization") + } + _ConditionalExpressionSetAlternate(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'ConditionalExpressionSetAlternate was not overloaded by native module initialization") + } + _CreateCallExpression(context: KNativePointer, callee: KNativePointer, _arguments: BigUint64Array, _argumentsSequenceLength: KUInt, typeParams: KNativePointer, optional_arg: KBoolean, trailingComma: KBoolean): KNativePointer { + throw new Error("'CreateCallExpression was not overloaded by native module initialization") + } + _CreateCallExpression1(context: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'CreateCallExpression1 was not overloaded by native module initialization") + } + _UpdateCallExpression1(context: KNativePointer, original: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'UpdateCallExpression1 was not overloaded by native module initialization") + } + _CallExpressionCalleeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CallExpressionCalleeConst was not overloaded by native module initialization") + } + _CallExpressionCallee(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CallExpressionCallee was not overloaded by native module initialization") + } + _CallExpressionSetCallee(context: KNativePointer, receiver: KNativePointer, callee: KNativePointer): void { + throw new Error("'CallExpressionSetCallee was not overloaded by native module initialization") + } + _CallExpressionTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CallExpressionTypeParamsConst was not overloaded by native module initialization") + } + _CallExpressionTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CallExpressionTypeParams was not overloaded by native module initialization") + } + _CallExpressionArgumentsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CallExpressionArgumentsConst was not overloaded by native module initialization") + } + _CallExpressionArguments(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CallExpressionArguments was not overloaded by native module initialization") + } + _CallExpressionHasTrailingCommaConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'CallExpressionHasTrailingCommaConst was not overloaded by native module initialization") + } + _CallExpressionSetTypeParams(context: KNativePointer, receiver: KNativePointer, typeParams: KNativePointer): void { + throw new Error("'CallExpressionSetTypeParams was not overloaded by native module initialization") + } + _CallExpressionSetTrailingBlock(context: KNativePointer, receiver: KNativePointer, block: KNativePointer): void { + throw new Error("'CallExpressionSetTrailingBlock was not overloaded by native module initialization") + } + _CallExpressionIsExtensionAccessorCall(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'CallExpressionIsExtensionAccessorCall was not overloaded by native module initialization") + } + _CallExpressionTrailingBlockConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CallExpressionTrailingBlockConst was not overloaded by native module initialization") + } + _CallExpressionSetIsTrailingBlockInNewLine(context: KNativePointer, receiver: KNativePointer, isNewLine: KBoolean): void { + throw new Error("'CallExpressionSetIsTrailingBlockInNewLine was not overloaded by native module initialization") + } + _CallExpressionIsTrailingBlockInNewLineConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'CallExpressionIsTrailingBlockInNewLineConst was not overloaded by native module initialization") + } + _CallExpressionIsETSConstructorCallConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'CallExpressionIsETSConstructorCallConst was not overloaded by native module initialization") + } + _CreateBigIntLiteral(context: KNativePointer, src: KStringPtr): KNativePointer { + throw new Error("'CreateBigIntLiteral was not overloaded by native module initialization") + } + _UpdateBigIntLiteral(context: KNativePointer, original: KNativePointer, src: KStringPtr): KNativePointer { + throw new Error("'UpdateBigIntLiteral was not overloaded by native module initialization") + } + _BigIntLiteralStrConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'BigIntLiteralStrConst was not overloaded by native module initialization") + } + _ClassElementId(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassElementId was not overloaded by native module initialization") + } + _ClassElementIdConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassElementIdConst was not overloaded by native module initialization") + } + _ClassElementKey(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassElementKey was not overloaded by native module initialization") + } + _ClassElementKeyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassElementKeyConst was not overloaded by native module initialization") + } + _ClassElementValue(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassElementValue was not overloaded by native module initialization") + } + _ClassElementSetValue(context: KNativePointer, receiver: KNativePointer, value: KNativePointer): void { + throw new Error("'ClassElementSetValue was not overloaded by native module initialization") + } + _ClassElementValueConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassElementValueConst was not overloaded by native module initialization") + } + _ClassElementIsPrivateElementConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassElementIsPrivateElementConst was not overloaded by native module initialization") + } + _ClassElementDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassElementDecoratorsConst was not overloaded by native module initialization") + } + _ClassElementIsComputedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassElementIsComputedConst was not overloaded by native module initialization") + } + _ClassElementAddDecorator(context: KNativePointer, receiver: KNativePointer, decorator: KNativePointer): void { + throw new Error("'ClassElementAddDecorator was not overloaded by native module initialization") + } + _ClassElementToPrivateFieldKindConst(context: KNativePointer, receiver: KNativePointer, isStatic: KBoolean): KInt { + throw new Error("'ClassElementToPrivateFieldKindConst was not overloaded by native module initialization") + } + _CreateTSImportType(context: KNativePointer, param: KNativePointer, typeParams: KNativePointer, qualifier: KNativePointer, isTypeof: KBoolean): KNativePointer { + throw new Error("'CreateTSImportType was not overloaded by native module initialization") + } + _UpdateTSImportType(context: KNativePointer, original: KNativePointer, param: KNativePointer, typeParams: KNativePointer, qualifier: KNativePointer, isTypeof: KBoolean): KNativePointer { + throw new Error("'UpdateTSImportType was not overloaded by native module initialization") + } + _TSImportTypeParamConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSImportTypeParamConst was not overloaded by native module initialization") + } + _TSImportTypeTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSImportTypeTypeParamsConst was not overloaded by native module initialization") + } + _TSImportTypeQualifierConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSImportTypeQualifierConst was not overloaded by native module initialization") + } + _TSImportTypeIsTypeofConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSImportTypeIsTypeofConst was not overloaded by native module initialization") + } + _CreateTaggedTemplateExpression(context: KNativePointer, tag: KNativePointer, quasi: KNativePointer, typeParams: KNativePointer): KNativePointer { + throw new Error("'CreateTaggedTemplateExpression was not overloaded by native module initialization") + } + _UpdateTaggedTemplateExpression(context: KNativePointer, original: KNativePointer, tag: KNativePointer, quasi: KNativePointer, typeParams: KNativePointer): KNativePointer { + throw new Error("'UpdateTaggedTemplateExpression was not overloaded by native module initialization") + } + _TaggedTemplateExpressionTagConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TaggedTemplateExpressionTagConst was not overloaded by native module initialization") + } + _TaggedTemplateExpressionQuasiConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TaggedTemplateExpressionQuasiConst was not overloaded by native module initialization") + } + _TaggedTemplateExpressionTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TaggedTemplateExpressionTypeParamsConst was not overloaded by native module initialization") + } + _CreateFunctionDeclaration(context: KNativePointer, func: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt, isAnonymous: KBoolean): KNativePointer { + throw new Error("'CreateFunctionDeclaration was not overloaded by native module initialization") + } + _UpdateFunctionDeclaration(context: KNativePointer, original: KNativePointer, func: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt, isAnonymous: KBoolean): KNativePointer { + throw new Error("'UpdateFunctionDeclaration was not overloaded by native module initialization") + } + _CreateFunctionDeclaration1(context: KNativePointer, func: KNativePointer, isAnonymous: KBoolean): KNativePointer { + throw new Error("'CreateFunctionDeclaration1 was not overloaded by native module initialization") + } + _UpdateFunctionDeclaration1(context: KNativePointer, original: KNativePointer, func: KNativePointer, isAnonymous: KBoolean): KNativePointer { + throw new Error("'UpdateFunctionDeclaration1 was not overloaded by native module initialization") + } + _FunctionDeclarationFunction(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionDeclarationFunction was not overloaded by native module initialization") + } + _FunctionDeclarationIsAnonymousConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'FunctionDeclarationIsAnonymousConst was not overloaded by native module initialization") + } + _FunctionDeclarationFunctionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionDeclarationFunctionConst was not overloaded by native module initialization") + } + _FunctionDeclarationAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionDeclarationAnnotations was not overloaded by native module initialization") + } + _FunctionDeclarationAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionDeclarationAnnotationsConst was not overloaded by native module initialization") + } + _FunctionDeclarationSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'FunctionDeclarationSetAnnotations was not overloaded by native module initialization") + } + _CreateETSTypeReference(context: KNativePointer, part: KNativePointer): KNativePointer { + throw new Error("'CreateETSTypeReference was not overloaded by native module initialization") + } + _UpdateETSTypeReference(context: KNativePointer, original: KNativePointer, part: KNativePointer): KNativePointer { + throw new Error("'UpdateETSTypeReference was not overloaded by native module initialization") + } + _ETSTypeReferencePart(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTypeReferencePart was not overloaded by native module initialization") + } + _ETSTypeReferencePartConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTypeReferencePartConst was not overloaded by native module initialization") + } + _ETSTypeReferenceBaseNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTypeReferenceBaseNameConst was not overloaded by native module initialization") + } + _CreateTSTypeReference(context: KNativePointer, typeName: KNativePointer, typeParams: KNativePointer): KNativePointer { + throw new Error("'CreateTSTypeReference was not overloaded by native module initialization") + } + _UpdateTSTypeReference(context: KNativePointer, original: KNativePointer, typeName: KNativePointer, typeParams: KNativePointer): KNativePointer { + throw new Error("'UpdateTSTypeReference was not overloaded by native module initialization") + } + _TSTypeReferenceTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeReferenceTypeParamsConst was not overloaded by native module initialization") + } + _TSTypeReferenceTypeNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeReferenceTypeNameConst was not overloaded by native module initialization") + } + _TSTypeReferenceBaseNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeReferenceBaseNameConst was not overloaded by native module initialization") + } + _CreateImportSource(context: KNativePointer, source: KNativePointer, resolvedSource: KNativePointer, hasDecl: KBoolean): KNativePointer { + throw new Error("'CreateImportSource was not overloaded by native module initialization") + } + _ImportSourceSourceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportSourceSourceConst was not overloaded by native module initialization") + } + _ImportSourceSource(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportSourceSource was not overloaded by native module initialization") + } + _ImportSourceResolvedSourceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportSourceResolvedSourceConst was not overloaded by native module initialization") + } + _ImportSourceResolvedSource(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportSourceResolvedSource was not overloaded by native module initialization") + } + _ImportSourceHasDeclConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ImportSourceHasDeclConst was not overloaded by native module initialization") + } + _CreateNamedType(context: KNativePointer, name: KNativePointer): KNativePointer { + throw new Error("'CreateNamedType was not overloaded by native module initialization") + } + _UpdateNamedType(context: KNativePointer, original: KNativePointer, name: KNativePointer): KNativePointer { + throw new Error("'UpdateNamedType was not overloaded by native module initialization") + } + _NamedTypeNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'NamedTypeNameConst was not overloaded by native module initialization") + } + _NamedTypeTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'NamedTypeTypeParamsConst was not overloaded by native module initialization") + } + _NamedTypeIsNullableConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'NamedTypeIsNullableConst was not overloaded by native module initialization") + } + _NamedTypeSetNullable(context: KNativePointer, receiver: KNativePointer, nullable: KBoolean): void { + throw new Error("'NamedTypeSetNullable was not overloaded by native module initialization") + } + _NamedTypeSetNext(context: KNativePointer, receiver: KNativePointer, next: KNativePointer): void { + throw new Error("'NamedTypeSetNext was not overloaded by native module initialization") + } + _NamedTypeSetTypeParams(context: KNativePointer, receiver: KNativePointer, typeParams: KNativePointer): void { + throw new Error("'NamedTypeSetTypeParams was not overloaded by native module initialization") + } + _NumberLiteralStrConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'NumberLiteralStrConst was not overloaded by native module initialization") + } + _CreateTSFunctionType(context: KNativePointer, signature: KNativePointer): KNativePointer { + throw new Error("'CreateTSFunctionType was not overloaded by native module initialization") + } + _UpdateTSFunctionType(context: KNativePointer, original: KNativePointer, signature: KNativePointer): KNativePointer { + throw new Error("'UpdateTSFunctionType was not overloaded by native module initialization") + } + _TSFunctionTypeTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSFunctionTypeTypeParamsConst was not overloaded by native module initialization") + } + _TSFunctionTypeTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSFunctionTypeTypeParams was not overloaded by native module initialization") + } + _TSFunctionTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSFunctionTypeParamsConst was not overloaded by native module initialization") + } + _TSFunctionTypeReturnTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSFunctionTypeReturnTypeConst was not overloaded by native module initialization") + } + _TSFunctionTypeReturnType(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSFunctionTypeReturnType was not overloaded by native module initialization") + } + _TSFunctionTypeSetNullable(context: KNativePointer, receiver: KNativePointer, nullable: KBoolean): void { + throw new Error("'TSFunctionTypeSetNullable was not overloaded by native module initialization") + } + _CreateTemplateElement(context: KNativePointer): KNativePointer { + throw new Error("'CreateTemplateElement was not overloaded by native module initialization") + } + _UpdateTemplateElement(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTemplateElement was not overloaded by native module initialization") + } + _CreateTemplateElement1(context: KNativePointer, raw: KStringPtr, cooked: KStringPtr): KNativePointer { + throw new Error("'CreateTemplateElement1 was not overloaded by native module initialization") + } + _UpdateTemplateElement1(context: KNativePointer, original: KNativePointer, raw: KStringPtr, cooked: KStringPtr): KNativePointer { + throw new Error("'UpdateTemplateElement1 was not overloaded by native module initialization") + } + _TemplateElementRawConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'TemplateElementRawConst was not overloaded by native module initialization") + } + _TemplateElementCookedConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'TemplateElementCookedConst was not overloaded by native module initialization") + } + _CreateTSInterfaceDeclaration(context: KNativePointer, _extends: BigUint64Array, _extendsSequenceLength: KUInt, id: KNativePointer, typeParams: KNativePointer, body: KNativePointer, isStatic: KBoolean, isExternal: KBoolean): KNativePointer { + throw new Error("'CreateTSInterfaceDeclaration was not overloaded by native module initialization") + } + _UpdateTSInterfaceDeclaration(context: KNativePointer, original: KNativePointer, _extends: BigUint64Array, _extendsSequenceLength: KUInt, id: KNativePointer, typeParams: KNativePointer, body: KNativePointer, isStatic: KBoolean, isExternal: KBoolean): KNativePointer { + throw new Error("'UpdateTSInterfaceDeclaration was not overloaded by native module initialization") + } + _TSInterfaceDeclarationBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationBody was not overloaded by native module initialization") + } + _TSInterfaceDeclarationBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationBodyConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationId(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationId was not overloaded by native module initialization") + } + _TSInterfaceDeclarationIdConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationIdConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationInternalNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'TSInterfaceDeclarationInternalNameConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationSetInternalName(context: KNativePointer, receiver: KNativePointer, internalName: KStringPtr): void { + throw new Error("'TSInterfaceDeclarationSetInternalName was not overloaded by native module initialization") + } + _TSInterfaceDeclarationIsStaticConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSInterfaceDeclarationIsStaticConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationIsFromExternalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSInterfaceDeclarationIsFromExternalConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationTypeParamsConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationTypeParams was not overloaded by native module initialization") + } + _TSInterfaceDeclarationExtends(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationExtends was not overloaded by native module initialization") + } + _TSInterfaceDeclarationExtendsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationExtendsConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationDecoratorsConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationGetAnonClass(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationGetAnonClass was not overloaded by native module initialization") + } + _TSInterfaceDeclarationGetAnonClassConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationGetAnonClassConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationSetAnonClass(context: KNativePointer, receiver: KNativePointer, anonClass: KNativePointer): void { + throw new Error("'TSInterfaceDeclarationSetAnonClass was not overloaded by native module initialization") + } + _TSInterfaceDeclarationAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationAnnotations was not overloaded by native module initialization") + } + _TSInterfaceDeclarationAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceDeclarationAnnotationsConst was not overloaded by native module initialization") + } + _TSInterfaceDeclarationSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'TSInterfaceDeclarationSetAnnotations was not overloaded by native module initialization") + } + _CreateVariableDeclaration(context: KNativePointer, kind: KInt, declarators: BigUint64Array, declaratorsSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateVariableDeclaration was not overloaded by native module initialization") + } + _UpdateVariableDeclaration(context: KNativePointer, original: KNativePointer, kind: KInt, declarators: BigUint64Array, declaratorsSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateVariableDeclaration was not overloaded by native module initialization") + } + _VariableDeclarationDeclaratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'VariableDeclarationDeclaratorsConst was not overloaded by native module initialization") + } + _VariableDeclarationKindConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'VariableDeclarationKindConst was not overloaded by native module initialization") + } + _VariableDeclarationDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'VariableDeclarationDecoratorsConst was not overloaded by native module initialization") + } + _VariableDeclarationGetDeclaratorByNameConst(context: KNativePointer, receiver: KNativePointer, name: KStringPtr): KNativePointer { + throw new Error("'VariableDeclarationGetDeclaratorByNameConst was not overloaded by native module initialization") + } + _VariableDeclarationAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'VariableDeclarationAnnotations was not overloaded by native module initialization") + } + _VariableDeclarationAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'VariableDeclarationAnnotationsConst was not overloaded by native module initialization") + } + _VariableDeclarationSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'VariableDeclarationSetAnnotations was not overloaded by native module initialization") + } + _CreateUndefinedLiteral(context: KNativePointer): KNativePointer { + throw new Error("'CreateUndefinedLiteral was not overloaded by native module initialization") + } + _UpdateUndefinedLiteral(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateUndefinedLiteral was not overloaded by native module initialization") + } + _CreateMemberExpression(context: KNativePointer, object_arg: KNativePointer, property: KNativePointer, kind: KInt, computed: KBoolean, optional_arg: KBoolean): KNativePointer { + throw new Error("'CreateMemberExpression was not overloaded by native module initialization") + } + _UpdateMemberExpression(context: KNativePointer, original: KNativePointer, object_arg: KNativePointer, property: KNativePointer, kind: KInt, computed: KBoolean, optional_arg: KBoolean): KNativePointer { + throw new Error("'UpdateMemberExpression was not overloaded by native module initialization") + } + _MemberExpressionObject(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MemberExpressionObject was not overloaded by native module initialization") + } + _MemberExpressionObjectConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MemberExpressionObjectConst was not overloaded by native module initialization") + } + _MemberExpressionSetObject(context: KNativePointer, receiver: KNativePointer, object_arg: KNativePointer): void { + throw new Error("'MemberExpressionSetObject was not overloaded by native module initialization") + } + _MemberExpressionSetProperty(context: KNativePointer, receiver: KNativePointer, prop: KNativePointer): void { + throw new Error("'MemberExpressionSetProperty was not overloaded by native module initialization") + } + _MemberExpressionProperty(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MemberExpressionProperty was not overloaded by native module initialization") + } + _MemberExpressionPropertyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MemberExpressionPropertyConst was not overloaded by native module initialization") + } + _MemberExpressionIsComputedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'MemberExpressionIsComputedConst was not overloaded by native module initialization") + } + _MemberExpressionKindConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'MemberExpressionKindConst was not overloaded by native module initialization") + } + _MemberExpressionAddMemberKind(context: KNativePointer, receiver: KNativePointer, kind: KInt): void { + throw new Error("'MemberExpressionAddMemberKind was not overloaded by native module initialization") + } + _MemberExpressionHasMemberKindConst(context: KNativePointer, receiver: KNativePointer, kind: KInt): KBoolean { + throw new Error("'MemberExpressionHasMemberKindConst was not overloaded by native module initialization") + } + _MemberExpressionRemoveMemberKind(context: KNativePointer, receiver: KNativePointer, kind: KInt): void { + throw new Error("'MemberExpressionRemoveMemberKind was not overloaded by native module initialization") + } + _MemberExpressionIsIgnoreBoxConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'MemberExpressionIsIgnoreBoxConst was not overloaded by native module initialization") + } + _MemberExpressionSetIgnoreBox(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'MemberExpressionSetIgnoreBox was not overloaded by native module initialization") + } + _MemberExpressionIsPrivateReferenceConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'MemberExpressionIsPrivateReferenceConst was not overloaded by native module initialization") + } + _CreateTSClassImplements(context: KNativePointer, expression: KNativePointer, typeParameters: KNativePointer): KNativePointer { + throw new Error("'CreateTSClassImplements was not overloaded by native module initialization") + } + _UpdateTSClassImplements(context: KNativePointer, original: KNativePointer, expression: KNativePointer, typeParameters: KNativePointer): KNativePointer { + throw new Error("'UpdateTSClassImplements was not overloaded by native module initialization") + } + _CreateTSClassImplements1(context: KNativePointer, expression: KNativePointer): KNativePointer { + throw new Error("'CreateTSClassImplements1 was not overloaded by native module initialization") + } + _UpdateTSClassImplements1(context: KNativePointer, original: KNativePointer, expression: KNativePointer): KNativePointer { + throw new Error("'UpdateTSClassImplements1 was not overloaded by native module initialization") + } + _TSClassImplementsExpr(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSClassImplementsExpr was not overloaded by native module initialization") + } + _TSClassImplementsExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSClassImplementsExprConst was not overloaded by native module initialization") + } + _TSClassImplementsTypeParametersConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSClassImplementsTypeParametersConst was not overloaded by native module initialization") + } + _CreateTSObjectKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSObjectKeyword was not overloaded by native module initialization") + } + _UpdateTSObjectKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSObjectKeyword was not overloaded by native module initialization") + } + _CreateETSUnionTypeIr(context: KNativePointer, types: BigUint64Array, typesSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateETSUnionTypeIr was not overloaded by native module initialization") + } + _UpdateETSUnionTypeIr(context: KNativePointer, original: KNativePointer, types: BigUint64Array, typesSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateETSUnionTypeIr was not overloaded by native module initialization") + } + _ETSUnionTypeIrTypesConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSUnionTypeIrTypesConst was not overloaded by native module initialization") + } + _CreateTSPropertySignature(context: KNativePointer, key: KNativePointer, typeAnnotation: KNativePointer, computed: KBoolean, optional_arg: KBoolean, readonly_arg: KBoolean): KNativePointer { + throw new Error("'CreateTSPropertySignature was not overloaded by native module initialization") + } + _UpdateTSPropertySignature(context: KNativePointer, original: KNativePointer, key: KNativePointer, typeAnnotation: KNativePointer, computed: KBoolean, optional_arg: KBoolean, readonly_arg: KBoolean): KNativePointer { + throw new Error("'UpdateTSPropertySignature was not overloaded by native module initialization") + } + _TSPropertySignatureKeyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSPropertySignatureKeyConst was not overloaded by native module initialization") + } + _TSPropertySignatureKey(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSPropertySignatureKey was not overloaded by native module initialization") + } + _TSPropertySignatureComputedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSPropertySignatureComputedConst was not overloaded by native module initialization") + } + _TSPropertySignatureOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSPropertySignatureOptionalConst was not overloaded by native module initialization") + } + _TSPropertySignatureReadonlyConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSPropertySignatureReadonlyConst was not overloaded by native module initialization") + } + _TSPropertySignatureTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSPropertySignatureTypeAnnotationConst was not overloaded by native module initialization") + } + _TSPropertySignatureSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'TSPropertySignatureSetTsTypeAnnotation was not overloaded by native module initialization") + } + _CreateTSConditionalType(context: KNativePointer, checkType: KNativePointer, extendsType: KNativePointer, trueType: KNativePointer, falseType: KNativePointer): KNativePointer { + throw new Error("'CreateTSConditionalType was not overloaded by native module initialization") + } + _UpdateTSConditionalType(context: KNativePointer, original: KNativePointer, checkType: KNativePointer, extendsType: KNativePointer, trueType: KNativePointer, falseType: KNativePointer): KNativePointer { + throw new Error("'UpdateTSConditionalType was not overloaded by native module initialization") + } + _TSConditionalTypeCheckTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConditionalTypeCheckTypeConst was not overloaded by native module initialization") + } + _TSConditionalTypeExtendsTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConditionalTypeExtendsTypeConst was not overloaded by native module initialization") + } + _TSConditionalTypeTrueTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConditionalTypeTrueTypeConst was not overloaded by native module initialization") + } + _TSConditionalTypeFalseTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSConditionalTypeFalseTypeConst was not overloaded by native module initialization") + } + _CreateTSLiteralType(context: KNativePointer, literal: KNativePointer): KNativePointer { + throw new Error("'CreateTSLiteralType was not overloaded by native module initialization") + } + _UpdateTSLiteralType(context: KNativePointer, original: KNativePointer, literal: KNativePointer): KNativePointer { + throw new Error("'UpdateTSLiteralType was not overloaded by native module initialization") + } + _TSLiteralTypeLiteralConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSLiteralTypeLiteralConst was not overloaded by native module initialization") + } + _CreateTSTypeAliasDeclaration(context: KNativePointer, id: KNativePointer, typeParams: KNativePointer, typeAnnotation: KNativePointer): KNativePointer { + throw new Error("'CreateTSTypeAliasDeclaration was not overloaded by native module initialization") + } + _UpdateTSTypeAliasDeclaration(context: KNativePointer, original: KNativePointer, id: KNativePointer, typeParams: KNativePointer, typeAnnotation: KNativePointer): KNativePointer { + throw new Error("'UpdateTSTypeAliasDeclaration was not overloaded by native module initialization") + } + _CreateTSTypeAliasDeclaration1(context: KNativePointer, id: KNativePointer): KNativePointer { + throw new Error("'CreateTSTypeAliasDeclaration1 was not overloaded by native module initialization") + } + _UpdateTSTypeAliasDeclaration1(context: KNativePointer, original: KNativePointer, id: KNativePointer): KNativePointer { + throw new Error("'UpdateTSTypeAliasDeclaration1 was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationId(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAliasDeclarationId was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationIdConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAliasDeclarationIdConst was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAliasDeclarationTypeParamsConst was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAliasDeclarationDecoratorsConst was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationSetTypeParameters(context: KNativePointer, receiver: KNativePointer, typeParams: KNativePointer): void { + throw new Error("'TSTypeAliasDeclarationSetTypeParameters was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAliasDeclarationAnnotations was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAliasDeclarationAnnotationsConst was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'TSTypeAliasDeclarationSetAnnotations was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAliasDeclarationTypeAnnotationConst was not overloaded by native module initialization") + } + _TSTypeAliasDeclarationSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'TSTypeAliasDeclarationSetTsTypeAnnotation was not overloaded by native module initialization") + } + _CreateDebuggerStatement(context: KNativePointer): KNativePointer { + throw new Error("'CreateDebuggerStatement was not overloaded by native module initialization") + } + _UpdateDebuggerStatement(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateDebuggerStatement was not overloaded by native module initialization") + } + _CreateReturnStatement(context: KNativePointer): KNativePointer { + throw new Error("'CreateReturnStatement was not overloaded by native module initialization") + } + _UpdateReturnStatement(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateReturnStatement was not overloaded by native module initialization") + } + _CreateReturnStatement1(context: KNativePointer, argument: KNativePointer): KNativePointer { + throw new Error("'CreateReturnStatement1 was not overloaded by native module initialization") + } + _UpdateReturnStatement1(context: KNativePointer, original: KNativePointer, argument: KNativePointer): KNativePointer { + throw new Error("'UpdateReturnStatement1 was not overloaded by native module initialization") + } + _ReturnStatementArgument(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ReturnStatementArgument was not overloaded by native module initialization") + } + _ReturnStatementArgumentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ReturnStatementArgumentConst was not overloaded by native module initialization") + } + _ReturnStatementSetArgument(context: KNativePointer, receiver: KNativePointer, arg: KNativePointer): void { + throw new Error("'ReturnStatementSetArgument was not overloaded by native module initialization") + } + _CreateExportDefaultDeclaration(context: KNativePointer, decl: KNativePointer, exportEquals: KBoolean): KNativePointer { + throw new Error("'CreateExportDefaultDeclaration was not overloaded by native module initialization") + } + _UpdateExportDefaultDeclaration(context: KNativePointer, original: KNativePointer, decl: KNativePointer, exportEquals: KBoolean): KNativePointer { + throw new Error("'UpdateExportDefaultDeclaration was not overloaded by native module initialization") + } + _ExportDefaultDeclarationDecl(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportDefaultDeclarationDecl was not overloaded by native module initialization") + } + _ExportDefaultDeclarationDeclConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportDefaultDeclarationDeclConst was not overloaded by native module initialization") + } + _ExportDefaultDeclarationIsExportEqualsConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ExportDefaultDeclarationIsExportEqualsConst was not overloaded by native module initialization") + } + _CreateScriptFunction(context: KNativePointer, databody: KNativePointer, datasignature: KNativePointer, datafuncFlags: KInt, dataflags: KInt): KNativePointer { + throw new Error("'CreateScriptFunction was not overloaded by native module initialization") + } + _UpdateScriptFunction(context: KNativePointer, original: KNativePointer, databody: KNativePointer, datasignature: KNativePointer, datafuncFlags: KInt, dataflags: KInt): KNativePointer { + throw new Error("'UpdateScriptFunction was not overloaded by native module initialization") + } + _ScriptFunctionIdConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionIdConst was not overloaded by native module initialization") + } + _ScriptFunctionId(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionId was not overloaded by native module initialization") + } + _ScriptFunctionParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionParamsConst was not overloaded by native module initialization") + } + _ScriptFunctionParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionParams was not overloaded by native module initialization") + } + _ScriptFunctionReturnStatementsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionReturnStatementsConst was not overloaded by native module initialization") + } + _ScriptFunctionReturnStatements(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionReturnStatements was not overloaded by native module initialization") + } + _ScriptFunctionTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionTypeParamsConst was not overloaded by native module initialization") + } + _ScriptFunctionTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionTypeParams was not overloaded by native module initialization") + } + _ScriptFunctionBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionBodyConst was not overloaded by native module initialization") + } + _ScriptFunctionBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionBody was not overloaded by native module initialization") + } + _ScriptFunctionAddReturnStatement(context: KNativePointer, receiver: KNativePointer, returnStatement: KNativePointer): void { + throw new Error("'ScriptFunctionAddReturnStatement was not overloaded by native module initialization") + } + _ScriptFunctionSetBody(context: KNativePointer, receiver: KNativePointer, body: KNativePointer): void { + throw new Error("'ScriptFunctionSetBody was not overloaded by native module initialization") + } + _ScriptFunctionReturnTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionReturnTypeAnnotationConst was not overloaded by native module initialization") + } + _ScriptFunctionReturnTypeAnnotation(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionReturnTypeAnnotation was not overloaded by native module initialization") + } + _ScriptFunctionSetReturnTypeAnnotation(context: KNativePointer, receiver: KNativePointer, node: KNativePointer): void { + throw new Error("'ScriptFunctionSetReturnTypeAnnotation was not overloaded by native module initialization") + } + _ScriptFunctionIsEntryPointConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsEntryPointConst was not overloaded by native module initialization") + } + _ScriptFunctionIsGeneratorConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsGeneratorConst was not overloaded by native module initialization") + } + _ScriptFunctionIsAsyncFuncConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsAsyncFuncConst was not overloaded by native module initialization") + } + _ScriptFunctionIsAsyncImplFuncConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsAsyncImplFuncConst was not overloaded by native module initialization") + } + _ScriptFunctionIsArrowConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsArrowConst was not overloaded by native module initialization") + } + _ScriptFunctionIsOverloadConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsOverloadConst was not overloaded by native module initialization") + } + _ScriptFunctionIsExternalOverloadConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsExternalOverloadConst was not overloaded by native module initialization") + } + _ScriptFunctionIsConstructorConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsConstructorConst was not overloaded by native module initialization") + } + _ScriptFunctionIsGetterConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsGetterConst was not overloaded by native module initialization") + } + _ScriptFunctionIsSetterConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsSetterConst was not overloaded by native module initialization") + } + _ScriptFunctionIsExtensionAccessorConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsExtensionAccessorConst was not overloaded by native module initialization") + } + _ScriptFunctionIsMethodConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsMethodConst was not overloaded by native module initialization") + } + _ScriptFunctionIsProxyConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsProxyConst was not overloaded by native module initialization") + } + _ScriptFunctionIsStaticBlockConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsStaticBlockConst was not overloaded by native module initialization") + } + _ScriptFunctionIsEnumConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsEnumConst was not overloaded by native module initialization") + } + _ScriptFunctionIsHiddenConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsHiddenConst was not overloaded by native module initialization") + } + _ScriptFunctionIsExternalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsExternalConst was not overloaded by native module initialization") + } + _ScriptFunctionIsImplicitSuperCallNeededConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsImplicitSuperCallNeededConst was not overloaded by native module initialization") + } + _ScriptFunctionHasBodyConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionHasBodyConst was not overloaded by native module initialization") + } + _ScriptFunctionHasRestParameterConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionHasRestParameterConst was not overloaded by native module initialization") + } + _ScriptFunctionHasReturnStatementConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionHasReturnStatementConst was not overloaded by native module initialization") + } + _ScriptFunctionHasThrowStatementConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionHasThrowStatementConst was not overloaded by native module initialization") + } + _ScriptFunctionIsThrowingConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsThrowingConst was not overloaded by native module initialization") + } + _ScriptFunctionIsRethrowingConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsRethrowingConst was not overloaded by native module initialization") + } + _ScriptFunctionIsDynamicConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsDynamicConst was not overloaded by native module initialization") + } + _ScriptFunctionIsExtensionMethodConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionIsExtensionMethodConst was not overloaded by native module initialization") + } + _ScriptFunctionFlagsConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'ScriptFunctionFlagsConst was not overloaded by native module initialization") + } + _ScriptFunctionHasReceiverConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ScriptFunctionHasReceiverConst was not overloaded by native module initialization") + } + _ScriptFunctionSetIdent(context: KNativePointer, receiver: KNativePointer, id: KNativePointer): void { + throw new Error("'ScriptFunctionSetIdent was not overloaded by native module initialization") + } + _ScriptFunctionAddFlag(context: KNativePointer, receiver: KNativePointer, flags: KInt): void { + throw new Error("'ScriptFunctionAddFlag was not overloaded by native module initialization") + } + _ScriptFunctionAddModifier(context: KNativePointer, receiver: KNativePointer, flags: KInt): void { + throw new Error("'ScriptFunctionAddModifier was not overloaded by native module initialization") + } + _ScriptFunctionFormalParamsLengthConst(context: KNativePointer, receiver: KNativePointer): KUInt { + throw new Error("'ScriptFunctionFormalParamsLengthConst was not overloaded by native module initialization") + } + _ScriptFunctionAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionAnnotations was not overloaded by native module initialization") + } + _ScriptFunctionAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ScriptFunctionAnnotationsConst was not overloaded by native module initialization") + } + _ScriptFunctionSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'ScriptFunctionSetAnnotations was not overloaded by native module initialization") + } + _CreateClassDefinition(context: KNativePointer, ident: KNativePointer, typeParams: KNativePointer, superTypeParams: KNativePointer, _implements: BigUint64Array, _implementsSequenceLength: KUInt, ctor: KNativePointer, superClass: KNativePointer, body: BigUint64Array, bodySequenceLength: KUInt, modifiers: KInt, flags: KInt): KNativePointer { + throw new Error("'CreateClassDefinition was not overloaded by native module initialization") + } + _UpdateClassDefinition(context: KNativePointer, original: KNativePointer, ident: KNativePointer, typeParams: KNativePointer, superTypeParams: KNativePointer, _implements: BigUint64Array, _implementsSequenceLength: KUInt, ctor: KNativePointer, superClass: KNativePointer, body: BigUint64Array, bodySequenceLength: KUInt, modifiers: KInt, flags: KInt): KNativePointer { + throw new Error("'UpdateClassDefinition was not overloaded by native module initialization") + } + _CreateClassDefinition1(context: KNativePointer, ident: KNativePointer, body: BigUint64Array, bodySequenceLength: KUInt, modifiers: KInt, flags: KInt): KNativePointer { + throw new Error("'CreateClassDefinition1 was not overloaded by native module initialization") + } + _UpdateClassDefinition1(context: KNativePointer, original: KNativePointer, ident: KNativePointer, body: BigUint64Array, bodySequenceLength: KUInt, modifiers: KInt, flags: KInt): KNativePointer { + throw new Error("'UpdateClassDefinition1 was not overloaded by native module initialization") + } + _CreateClassDefinition2(context: KNativePointer, ident: KNativePointer, modifiers: KInt, flags: KInt): KNativePointer { + throw new Error("'CreateClassDefinition2 was not overloaded by native module initialization") + } + _UpdateClassDefinition2(context: KNativePointer, original: KNativePointer, ident: KNativePointer, modifiers: KInt, flags: KInt): KNativePointer { + throw new Error("'UpdateClassDefinition2 was not overloaded by native module initialization") + } + _ClassDefinitionIdentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionIdentConst was not overloaded by native module initialization") + } + _ClassDefinitionIdent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionIdent was not overloaded by native module initialization") + } + _ClassDefinitionSetIdent(context: KNativePointer, receiver: KNativePointer, ident: KNativePointer): void { + throw new Error("'ClassDefinitionSetIdent was not overloaded by native module initialization") + } + _ClassDefinitionInternalNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ClassDefinitionInternalNameConst was not overloaded by native module initialization") + } + _ClassDefinitionSetInternalName(context: KNativePointer, receiver: KNativePointer, internalName: KStringPtr): void { + throw new Error("'ClassDefinitionSetInternalName was not overloaded by native module initialization") + } + _ClassDefinitionSuper(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionSuper was not overloaded by native module initialization") + } + _ClassDefinitionSuperConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionSuperConst was not overloaded by native module initialization") + } + _ClassDefinitionSetSuper(context: KNativePointer, receiver: KNativePointer, superClass: KNativePointer): void { + throw new Error("'ClassDefinitionSetSuper was not overloaded by native module initialization") + } + _ClassDefinitionIsGlobalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsGlobalConst was not overloaded by native module initialization") + } + _ClassDefinitionIsLocalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsLocalConst was not overloaded by native module initialization") + } + _ClassDefinitionIsExternConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsExternConst was not overloaded by native module initialization") + } + _ClassDefinitionIsFromExternalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsFromExternalConst was not overloaded by native module initialization") + } + _ClassDefinitionIsInnerConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsInnerConst was not overloaded by native module initialization") + } + _ClassDefinitionIsGlobalInitializedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsGlobalInitializedConst was not overloaded by native module initialization") + } + _ClassDefinitionIsClassDefinitionCheckedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsClassDefinitionCheckedConst was not overloaded by native module initialization") + } + _ClassDefinitionIsAnonymousConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsAnonymousConst was not overloaded by native module initialization") + } + _ClassDefinitionIsNamespaceTransformedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsNamespaceTransformedConst was not overloaded by native module initialization") + } + _ClassDefinitionIsModuleConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionIsModuleConst was not overloaded by native module initialization") + } + _ClassDefinitionSetGlobalInitialized(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ClassDefinitionSetGlobalInitialized was not overloaded by native module initialization") + } + _ClassDefinitionSetInnerModifier(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ClassDefinitionSetInnerModifier was not overloaded by native module initialization") + } + _ClassDefinitionSetClassDefinitionChecked(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ClassDefinitionSetClassDefinitionChecked was not overloaded by native module initialization") + } + _ClassDefinitionSetAnonymousModifier(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ClassDefinitionSetAnonymousModifier was not overloaded by native module initialization") + } + _ClassDefinitionSetNamespaceTransformed(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ClassDefinitionSetNamespaceTransformed was not overloaded by native module initialization") + } + _ClassDefinitionModifiersConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'ClassDefinitionModifiersConst was not overloaded by native module initialization") + } + _ClassDefinitionSetModifiers(context: KNativePointer, receiver: KNativePointer, modifiers: KInt): void { + throw new Error("'ClassDefinitionSetModifiers was not overloaded by native module initialization") + } + _ClassDefinitionAddProperties(context: KNativePointer, receiver: KNativePointer, body: BigUint64Array, bodySequenceLength: KUInt): void { + throw new Error("'ClassDefinitionAddProperties was not overloaded by native module initialization") + } + _ClassDefinitionBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionBody was not overloaded by native module initialization") + } + _ClassDefinitionBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionBodyConst was not overloaded by native module initialization") + } + _ClassDefinitionCtor(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionCtor was not overloaded by native module initialization") + } + _ClassDefinitionSetCtor(context: KNativePointer, receiver: KNativePointer, ctor: KNativePointer): void { + throw new Error("'ClassDefinitionSetCtor was not overloaded by native module initialization") + } + _ClassDefinitionImplements(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionImplements was not overloaded by native module initialization") + } + _ClassDefinitionImplementsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionImplementsConst was not overloaded by native module initialization") + } + _ClassDefinitionTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionTypeParamsConst was not overloaded by native module initialization") + } + _ClassDefinitionTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionTypeParams was not overloaded by native module initialization") + } + _ClassDefinitionSetTypeParams(context: KNativePointer, receiver: KNativePointer, typeParams: KNativePointer): void { + throw new Error("'ClassDefinitionSetTypeParams was not overloaded by native module initialization") + } + _ClassDefinitionSuperTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionSuperTypeParamsConst was not overloaded by native module initialization") + } + _ClassDefinitionSuperTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionSuperTypeParams was not overloaded by native module initialization") + } + _ClassDefinitionLocalTypeCounter(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'ClassDefinitionLocalTypeCounter was not overloaded by native module initialization") + } + _ClassDefinitionLocalIndexConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'ClassDefinitionLocalIndexConst was not overloaded by native module initialization") + } + _ClassDefinitionLocalPrefixConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ClassDefinitionLocalPrefixConst was not overloaded by native module initialization") + } + _ClassDefinitionSetOrigEnumDecl(context: KNativePointer, receiver: KNativePointer, enumDecl: KNativePointer): void { + throw new Error("'ClassDefinitionSetOrigEnumDecl was not overloaded by native module initialization") + } + _ClassDefinitionOrigEnumDeclConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionOrigEnumDeclConst was not overloaded by native module initialization") + } + _ClassDefinitionGetAnonClass(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionGetAnonClass was not overloaded by native module initialization") + } + _ClassDefinitionSetAnonClass(context: KNativePointer, receiver: KNativePointer, anonClass: KNativePointer): void { + throw new Error("'ClassDefinitionSetAnonClass was not overloaded by native module initialization") + } + _ClassDefinitionCtorConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionCtorConst was not overloaded by native module initialization") + } + _ClassDefinitionHasPrivateMethodConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionHasPrivateMethodConst was not overloaded by native module initialization") + } + _ClassDefinitionHasComputedInstanceFieldConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ClassDefinitionHasComputedInstanceFieldConst was not overloaded by native module initialization") + } + _ClassDefinitionHasMatchingPrivateKeyConst(context: KNativePointer, receiver: KNativePointer, name: KStringPtr): KBoolean { + throw new Error("'ClassDefinitionHasMatchingPrivateKeyConst was not overloaded by native module initialization") + } + _ClassDefinitionAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionAnnotations was not overloaded by native module initialization") + } + _ClassDefinitionAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDefinitionAnnotationsConst was not overloaded by native module initialization") + } + _ClassDefinitionSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'ClassDefinitionSetAnnotations was not overloaded by native module initialization") + } + _CreateArrayExpression(context: KNativePointer, elements: BigUint64Array, elementsSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateArrayExpression was not overloaded by native module initialization") + } + _UpdateArrayExpression(context: KNativePointer, original: KNativePointer, elements: BigUint64Array, elementsSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateArrayExpression was not overloaded by native module initialization") + } + _CreateArrayExpression1(context: KNativePointer, nodeType: KInt, elements: BigUint64Array, elementsSequenceLength: KUInt, trailingComma: KBoolean): KNativePointer { + throw new Error("'CreateArrayExpression1 was not overloaded by native module initialization") + } + _UpdateArrayExpression1(context: KNativePointer, original: KNativePointer, nodeType: KInt, elements: BigUint64Array, elementsSequenceLength: KUInt, trailingComma: KBoolean): KNativePointer { + throw new Error("'UpdateArrayExpression1 was not overloaded by native module initialization") + } + _ArrayExpressionElementsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrayExpressionElementsConst was not overloaded by native module initialization") + } + _ArrayExpressionElements(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrayExpressionElements was not overloaded by native module initialization") + } + _ArrayExpressionSetElements(context: KNativePointer, receiver: KNativePointer, elements: BigUint64Array, elementsSequenceLength: KUInt): void { + throw new Error("'ArrayExpressionSetElements was not overloaded by native module initialization") + } + _ArrayExpressionIsDeclarationConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ArrayExpressionIsDeclarationConst was not overloaded by native module initialization") + } + _ArrayExpressionIsOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ArrayExpressionIsOptionalConst was not overloaded by native module initialization") + } + _ArrayExpressionSetDeclaration(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ArrayExpressionSetDeclaration was not overloaded by native module initialization") + } + _ArrayExpressionSetOptional(context: KNativePointer, receiver: KNativePointer, optional_arg: KBoolean): void { + throw new Error("'ArrayExpressionSetOptional was not overloaded by native module initialization") + } + _ArrayExpressionDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrayExpressionDecoratorsConst was not overloaded by native module initialization") + } + _ArrayExpressionConvertibleToArrayPattern(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ArrayExpressionConvertibleToArrayPattern was not overloaded by native module initialization") + } + _ArrayExpressionValidateExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrayExpressionValidateExpression was not overloaded by native module initialization") + } + _ArrayExpressionHandleNestedArrayExpression(context: KNativePointer, receiver: KNativePointer, currentElement: KNativePointer, isPreferredTuple: KBoolean, idx: KUInt): KBoolean { + throw new Error("'ArrayExpressionHandleNestedArrayExpression was not overloaded by native module initialization") + } + _ArrayExpressionTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrayExpressionTypeAnnotationConst was not overloaded by native module initialization") + } + _ArrayExpressionSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'ArrayExpressionSetTsTypeAnnotation was not overloaded by native module initialization") + } + _CreateTSInterfaceBody(context: KNativePointer, body: BigUint64Array, bodySequenceLength: KUInt): KNativePointer { + throw new Error("'CreateTSInterfaceBody was not overloaded by native module initialization") + } + _UpdateTSInterfaceBody(context: KNativePointer, original: KNativePointer, body: BigUint64Array, bodySequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateTSInterfaceBody was not overloaded by native module initialization") + } + _TSInterfaceBodyBodyPtr(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceBodyBodyPtr was not overloaded by native module initialization") + } + _TSInterfaceBodyBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceBodyBody was not overloaded by native module initialization") + } + _TSInterfaceBodyBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceBodyBodyConst was not overloaded by native module initialization") + } + _CreateTSTypeQuery(context: KNativePointer, exprName: KNativePointer): KNativePointer { + throw new Error("'CreateTSTypeQuery was not overloaded by native module initialization") + } + _UpdateTSTypeQuery(context: KNativePointer, original: KNativePointer, exprName: KNativePointer): KNativePointer { + throw new Error("'UpdateTSTypeQuery was not overloaded by native module initialization") + } + _TSTypeQueryExprNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeQueryExprNameConst was not overloaded by native module initialization") + } + _CreateTSBigintKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSBigintKeyword was not overloaded by native module initialization") + } + _UpdateTSBigintKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSBigintKeyword was not overloaded by native module initialization") + } + _CreateProperty(context: KNativePointer, key: KNativePointer, value: KNativePointer): KNativePointer { + throw new Error("'CreateProperty was not overloaded by native module initialization") + } + _UpdateProperty(context: KNativePointer, original: KNativePointer, key: KNativePointer, value: KNativePointer): KNativePointer { + throw new Error("'UpdateProperty was not overloaded by native module initialization") + } + _CreateProperty1(context: KNativePointer, kind: KInt, key: KNativePointer, value: KNativePointer, isMethod: KBoolean, isComputed: KBoolean): KNativePointer { + throw new Error("'CreateProperty1 was not overloaded by native module initialization") + } + _UpdateProperty1(context: KNativePointer, original: KNativePointer, kind: KInt, key: KNativePointer, value: KNativePointer, isMethod: KBoolean, isComputed: KBoolean): KNativePointer { + throw new Error("'UpdateProperty1 was not overloaded by native module initialization") + } + _PropertyKey(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'PropertyKey was not overloaded by native module initialization") + } + _PropertyKeyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'PropertyKeyConst was not overloaded by native module initialization") + } + _PropertyValueConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'PropertyValueConst was not overloaded by native module initialization") + } + _PropertyValue(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'PropertyValue was not overloaded by native module initialization") + } + _PropertyKindConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'PropertyKindConst was not overloaded by native module initialization") + } + _PropertyIsMethodConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'PropertyIsMethodConst was not overloaded by native module initialization") + } + _PropertyIsShorthandConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'PropertyIsShorthandConst was not overloaded by native module initialization") + } + _PropertyIsComputedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'PropertyIsComputedConst was not overloaded by native module initialization") + } + _PropertyIsAccessorConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'PropertyIsAccessorConst was not overloaded by native module initialization") + } + _PropertyIsAccessorKind(context: KNativePointer, receiver: KNativePointer, kind: KInt): KBoolean { + throw new Error("'PropertyIsAccessorKind was not overloaded by native module initialization") + } + _PropertyConvertibleToPatternProperty(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'PropertyConvertibleToPatternProperty was not overloaded by native module initialization") + } + _PropertyValidateExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'PropertyValidateExpression was not overloaded by native module initialization") + } + _CreateVariableDeclarator(context: KNativePointer, flag: KInt, ident: KNativePointer): KNativePointer { + throw new Error("'CreateVariableDeclarator was not overloaded by native module initialization") + } + _UpdateVariableDeclarator(context: KNativePointer, original: KNativePointer, flag: KInt, ident: KNativePointer): KNativePointer { + throw new Error("'UpdateVariableDeclarator was not overloaded by native module initialization") + } + _CreateVariableDeclarator1(context: KNativePointer, flag: KInt, ident: KNativePointer, init: KNativePointer): KNativePointer { + throw new Error("'CreateVariableDeclarator1 was not overloaded by native module initialization") + } + _UpdateVariableDeclarator1(context: KNativePointer, original: KNativePointer, flag: KInt, ident: KNativePointer, init: KNativePointer): KNativePointer { + throw new Error("'UpdateVariableDeclarator1 was not overloaded by native module initialization") + } + _VariableDeclaratorInit(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'VariableDeclaratorInit was not overloaded by native module initialization") + } + _VariableDeclaratorInitConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'VariableDeclaratorInitConst was not overloaded by native module initialization") + } + _VariableDeclaratorSetInit(context: KNativePointer, receiver: KNativePointer, init: KNativePointer): void { + throw new Error("'VariableDeclaratorSetInit was not overloaded by native module initialization") + } + _VariableDeclaratorId(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'VariableDeclaratorId was not overloaded by native module initialization") + } + _VariableDeclaratorIdConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'VariableDeclaratorIdConst was not overloaded by native module initialization") + } + _VariableDeclaratorFlag(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'VariableDeclaratorFlag was not overloaded by native module initialization") + } + _CreateStringLiteral(context: KNativePointer): KNativePointer { + throw new Error("'CreateStringLiteral was not overloaded by native module initialization") + } + _UpdateStringLiteral(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateStringLiteral was not overloaded by native module initialization") + } + _CreateStringLiteral1(context: KNativePointer, str: KStringPtr): KNativePointer { + throw new Error("'CreateStringLiteral1 was not overloaded by native module initialization") + } + _UpdateStringLiteral1(context: KNativePointer, original: KNativePointer, str: KStringPtr): KNativePointer { + throw new Error("'UpdateStringLiteral1 was not overloaded by native module initialization") + } + _StringLiteralStrConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'StringLiteralStrConst was not overloaded by native module initialization") + } + _CreateTSTypeAssertion(context: KNativePointer, typeAnnotation: KNativePointer, expression: KNativePointer): KNativePointer { + throw new Error("'CreateTSTypeAssertion was not overloaded by native module initialization") + } + _UpdateTSTypeAssertion(context: KNativePointer, original: KNativePointer, typeAnnotation: KNativePointer, expression: KNativePointer): KNativePointer { + throw new Error("'UpdateTSTypeAssertion was not overloaded by native module initialization") + } + _TSTypeAssertionGetExpressionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAssertionGetExpressionConst was not overloaded by native module initialization") + } + _TSTypeAssertionTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeAssertionTypeAnnotationConst was not overloaded by native module initialization") + } + _TSTypeAssertionSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'TSTypeAssertionSetTsTypeAnnotation was not overloaded by native module initialization") + } + _CreateTSExternalModuleReference(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateTSExternalModuleReference was not overloaded by native module initialization") + } + _UpdateTSExternalModuleReference(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateTSExternalModuleReference was not overloaded by native module initialization") + } + _TSExternalModuleReferenceExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSExternalModuleReferenceExprConst was not overloaded by native module initialization") + } + _CreateTSUndefinedKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSUndefinedKeyword was not overloaded by native module initialization") + } + _UpdateTSUndefinedKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSUndefinedKeyword was not overloaded by native module initialization") + } + _CreateETSTuple(context: KNativePointer): KNativePointer { + throw new Error("'CreateETSTuple was not overloaded by native module initialization") + } + _UpdateETSTuple(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateETSTuple was not overloaded by native module initialization") + } + _CreateETSTuple1(context: KNativePointer, size: KUInt): KNativePointer { + throw new Error("'CreateETSTuple1 was not overloaded by native module initialization") + } + _UpdateETSTuple1(context: KNativePointer, original: KNativePointer, size: KUInt): KNativePointer { + throw new Error("'UpdateETSTuple1 was not overloaded by native module initialization") + } + _CreateETSTuple2(context: KNativePointer, typeList: BigUint64Array, typeListSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateETSTuple2 was not overloaded by native module initialization") + } + _UpdateETSTuple2(context: KNativePointer, original: KNativePointer, typeList: BigUint64Array, typeListSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateETSTuple2 was not overloaded by native module initialization") + } + _ETSTupleGetTupleSizeConst(context: KNativePointer, receiver: KNativePointer): KUInt { + throw new Error("'ETSTupleGetTupleSizeConst was not overloaded by native module initialization") + } + _ETSTupleGetTupleTypeAnnotationsListConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTupleGetTupleTypeAnnotationsListConst was not overloaded by native module initialization") + } + _ETSTupleHasSpreadTypeConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSTupleHasSpreadTypeConst was not overloaded by native module initialization") + } + _ETSTupleSetSpreadType(context: KNativePointer, receiver: KNativePointer, newSpreadType: KNativePointer): void { + throw new Error("'ETSTupleSetSpreadType was not overloaded by native module initialization") + } + _ETSTupleSetTypeAnnotationsList(context: KNativePointer, receiver: KNativePointer, typeNodeList: BigUint64Array, typeNodeListSequenceLength: KUInt): void { + throw new Error("'ETSTupleSetTypeAnnotationsList was not overloaded by native module initialization") + } + _TryStatementFinallyBlockConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TryStatementFinallyBlockConst was not overloaded by native module initialization") + } + _TryStatementBlockConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TryStatementBlockConst was not overloaded by native module initialization") + } + _TryStatementHasFinalizerConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TryStatementHasFinalizerConst was not overloaded by native module initialization") + } + _TryStatementHasDefaultCatchClauseConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TryStatementHasDefaultCatchClauseConst was not overloaded by native module initialization") + } + _TryStatementCatchClausesConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TryStatementCatchClausesConst was not overloaded by native module initialization") + } + _TryStatementFinallyCanCompleteNormallyConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TryStatementFinallyCanCompleteNormallyConst was not overloaded by native module initialization") + } + _TryStatementSetFinallyCanCompleteNormally(context: KNativePointer, receiver: KNativePointer, finallyCanCompleteNormally: KBoolean): void { + throw new Error("'TryStatementSetFinallyCanCompleteNormally was not overloaded by native module initialization") + } + _AstNodeIsProgramConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsProgramConst was not overloaded by native module initialization") + } + _AstNodeIsStatementConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsStatementConst was not overloaded by native module initialization") + } + _AstNodeIsExpressionConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsExpressionConst was not overloaded by native module initialization") + } + _AstNodeIsTypedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsTypedConst was not overloaded by native module initialization") + } + _AstNodeAsTyped(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeAsTyped was not overloaded by native module initialization") + } + _AstNodeAsTypedConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeAsTypedConst was not overloaded by native module initialization") + } + _AstNodeIsBrokenStatementConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsBrokenStatementConst was not overloaded by native module initialization") + } + _AstNodeAsExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeAsExpression was not overloaded by native module initialization") + } + _AstNodeAsExpressionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeAsExpressionConst was not overloaded by native module initialization") + } + _AstNodeAsStatement(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeAsStatement was not overloaded by native module initialization") + } + _AstNodeAsStatementConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeAsStatementConst was not overloaded by native module initialization") + } + _AstNodeTypeConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'AstNodeTypeConst was not overloaded by native module initialization") + } + _AstNodeParent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeParent was not overloaded by native module initialization") + } + _AstNodeParentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeParentConst was not overloaded by native module initialization") + } + _AstNodeSetParent(context: KNativePointer, receiver: KNativePointer, parent: KNativePointer): void { + throw new Error("'AstNodeSetParent was not overloaded by native module initialization") + } + _AstNodeDecoratorsPtrConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeDecoratorsPtrConst was not overloaded by native module initialization") + } + _AstNodeAddDecorators(context: KNativePointer, receiver: KNativePointer, decorators: BigUint64Array, decoratorsSequenceLength: KUInt): void { + throw new Error("'AstNodeAddDecorators was not overloaded by native module initialization") + } + _AstNodeCanHaveDecoratorConst(context: KNativePointer, receiver: KNativePointer, inTs: KBoolean): KBoolean { + throw new Error("'AstNodeCanHaveDecoratorConst was not overloaded by native module initialization") + } + _AstNodeIsReadonlyConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsReadonlyConst was not overloaded by native module initialization") + } + _AstNodeIsReadonlyTypeConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsReadonlyTypeConst was not overloaded by native module initialization") + } + _AstNodeIsOptionalDeclarationConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsOptionalDeclarationConst was not overloaded by native module initialization") + } + _AstNodeIsDefiniteConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsDefiniteConst was not overloaded by native module initialization") + } + _AstNodeIsConstructorConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsConstructorConst was not overloaded by native module initialization") + } + _AstNodeIsOverrideConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsOverrideConst was not overloaded by native module initialization") + } + _AstNodeSetOverride(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'AstNodeSetOverride was not overloaded by native module initialization") + } + _AstNodeIsAsyncConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsAsyncConst was not overloaded by native module initialization") + } + _AstNodeIsSynchronizedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsSynchronizedConst was not overloaded by native module initialization") + } + _AstNodeIsNativeConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsNativeConst was not overloaded by native module initialization") + } + _AstNodeIsConstConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsConstConst was not overloaded by native module initialization") + } + _AstNodeIsStaticConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsStaticConst was not overloaded by native module initialization") + } + _AstNodeIsFinalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsFinalConst was not overloaded by native module initialization") + } + _AstNodeIsAbstractConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsAbstractConst was not overloaded by native module initialization") + } + _AstNodeIsPublicConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsPublicConst was not overloaded by native module initialization") + } + _AstNodeIsProtectedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsProtectedConst was not overloaded by native module initialization") + } + _AstNodeIsPrivateConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsPrivateConst was not overloaded by native module initialization") + } + _AstNodeIsInternalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsInternalConst was not overloaded by native module initialization") + } + _AstNodeIsExportedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsExportedConst was not overloaded by native module initialization") + } + _AstNodeIsDefaultExportedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsDefaultExportedConst was not overloaded by native module initialization") + } + _AstNodeIsExportedTypeConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsExportedTypeConst was not overloaded by native module initialization") + } + _AstNodeIsDeclareConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsDeclareConst was not overloaded by native module initialization") + } + _AstNodeIsInConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsInConst was not overloaded by native module initialization") + } + _AstNodeIsOutConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsOutConst was not overloaded by native module initialization") + } + _AstNodeIsSetterConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsSetterConst was not overloaded by native module initialization") + } + _AstNodeAddModifier(context: KNativePointer, receiver: KNativePointer, flags: KInt): void { + throw new Error("'AstNodeAddModifier was not overloaded by native module initialization") + } + _AstNodeClearModifier(context: KNativePointer, receiver: KNativePointer, flags: KInt): void { + throw new Error("'AstNodeClearModifier was not overloaded by native module initialization") + } + _AstNodeModifiers(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'AstNodeModifiers was not overloaded by native module initialization") + } + _AstNodeModifiersConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'AstNodeModifiersConst was not overloaded by native module initialization") + } + _AstNodeHasExportAliasConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeHasExportAliasConst was not overloaded by native module initialization") + } + _AstNodeAsClassElement(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeAsClassElement was not overloaded by native module initialization") + } + _AstNodeAsClassElementConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeAsClassElementConst was not overloaded by native module initialization") + } + _AstNodeIsScopeBearerConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AstNodeIsScopeBearerConst was not overloaded by native module initialization") + } + _AstNodeClearScope(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'AstNodeClearScope was not overloaded by native module initialization") + } + _AstNodeGetTopStatement(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeGetTopStatement was not overloaded by native module initialization") + } + _AstNodeGetTopStatementConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeGetTopStatementConst was not overloaded by native module initialization") + } + _AstNodeClone(context: KNativePointer, receiver: KNativePointer, parent: KNativePointer): KNativePointer { + throw new Error("'AstNodeClone was not overloaded by native module initialization") + } + _AstNodeDumpJSONConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'AstNodeDumpJSONConst was not overloaded by native module initialization") + } + _AstNodeDumpEtsSrcConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'AstNodeDumpEtsSrcConst was not overloaded by native module initialization") + } + _AstNodeDumpConst(context: KNativePointer, receiver: KNativePointer, dumper: KNativePointer): void { + throw new Error("'AstNodeDumpConst was not overloaded by native module initialization") + } + _AstNodeDumpConst1(context: KNativePointer, receiver: KNativePointer, dumper: KNativePointer): void { + throw new Error("'AstNodeDumpConst1 was not overloaded by native module initialization") + } + _AstNodeSetTransformedNode(context: KNativePointer, receiver: KNativePointer, transformationName: KStringPtr, transformedNode: KNativePointer): void { + throw new Error("'AstNodeSetTransformedNode was not overloaded by native module initialization") + } + _AstNodeSetOriginalNode(context: KNativePointer, receiver: KNativePointer, originalNode: KNativePointer): void { + throw new Error("'AstNodeSetOriginalNode was not overloaded by native module initialization") + } + _AstNodeOriginalNodeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AstNodeOriginalNodeConst was not overloaded by native module initialization") + } + _CreateUnaryExpression(context: KNativePointer, argument: KNativePointer, unaryOperator: KInt): KNativePointer { + throw new Error("'CreateUnaryExpression was not overloaded by native module initialization") + } + _UpdateUnaryExpression(context: KNativePointer, original: KNativePointer, argument: KNativePointer, unaryOperator: KInt): KNativePointer { + throw new Error("'UpdateUnaryExpression was not overloaded by native module initialization") + } + _UnaryExpressionOperatorTypeConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'UnaryExpressionOperatorTypeConst was not overloaded by native module initialization") + } + _UnaryExpressionArgument(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'UnaryExpressionArgument was not overloaded by native module initialization") + } + _UnaryExpressionArgumentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'UnaryExpressionArgumentConst was not overloaded by native module initialization") + } + _CreateForInStatement(context: KNativePointer, left: KNativePointer, right: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'CreateForInStatement was not overloaded by native module initialization") + } + _UpdateForInStatement(context: KNativePointer, original: KNativePointer, left: KNativePointer, right: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'UpdateForInStatement was not overloaded by native module initialization") + } + _ForInStatementLeft(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForInStatementLeft was not overloaded by native module initialization") + } + _ForInStatementLeftConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForInStatementLeftConst was not overloaded by native module initialization") + } + _ForInStatementRight(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForInStatementRight was not overloaded by native module initialization") + } + _ForInStatementRightConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForInStatementRightConst was not overloaded by native module initialization") + } + _ForInStatementBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForInStatementBody was not overloaded by native module initialization") + } + _ForInStatementBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForInStatementBodyConst was not overloaded by native module initialization") + } + _CreateThisExpression(context: KNativePointer): KNativePointer { + throw new Error("'CreateThisExpression was not overloaded by native module initialization") + } + _UpdateThisExpression(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateThisExpression was not overloaded by native module initialization") + } + _CreateTSMethodSignature(context: KNativePointer, key: KNativePointer, signature: KNativePointer, computed: KBoolean, optional_arg: KBoolean): KNativePointer { + throw new Error("'CreateTSMethodSignature was not overloaded by native module initialization") + } + _UpdateTSMethodSignature(context: KNativePointer, original: KNativePointer, key: KNativePointer, signature: KNativePointer, computed: KBoolean, optional_arg: KBoolean): KNativePointer { + throw new Error("'UpdateTSMethodSignature was not overloaded by native module initialization") + } + _TSMethodSignatureKeyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMethodSignatureKeyConst was not overloaded by native module initialization") + } + _TSMethodSignatureKey(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMethodSignatureKey was not overloaded by native module initialization") + } + _TSMethodSignatureTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMethodSignatureTypeParamsConst was not overloaded by native module initialization") + } + _TSMethodSignatureTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMethodSignatureTypeParams was not overloaded by native module initialization") + } + _TSMethodSignatureParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMethodSignatureParamsConst was not overloaded by native module initialization") + } + _TSMethodSignatureReturnTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMethodSignatureReturnTypeAnnotationConst was not overloaded by native module initialization") + } + _TSMethodSignatureReturnTypeAnnotation(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMethodSignatureReturnTypeAnnotation was not overloaded by native module initialization") + } + _TSMethodSignatureComputedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSMethodSignatureComputedConst was not overloaded by native module initialization") + } + _TSMethodSignatureOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSMethodSignatureOptionalConst was not overloaded by native module initialization") + } + _CreateBinaryExpression(context: KNativePointer, left: KNativePointer, right: KNativePointer, operatorType: KInt): KNativePointer { + throw new Error("'CreateBinaryExpression was not overloaded by native module initialization") + } + _UpdateBinaryExpression(context: KNativePointer, original: KNativePointer, left: KNativePointer, right: KNativePointer, operatorType: KInt): KNativePointer { + throw new Error("'UpdateBinaryExpression was not overloaded by native module initialization") + } + _BinaryExpressionLeftConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BinaryExpressionLeftConst was not overloaded by native module initialization") + } + _BinaryExpressionLeft(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BinaryExpressionLeft was not overloaded by native module initialization") + } + _BinaryExpressionRightConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BinaryExpressionRightConst was not overloaded by native module initialization") + } + _BinaryExpressionRight(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BinaryExpressionRight was not overloaded by native module initialization") + } + _BinaryExpressionResultConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BinaryExpressionResultConst was not overloaded by native module initialization") + } + _BinaryExpressionResult(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BinaryExpressionResult was not overloaded by native module initialization") + } + _BinaryExpressionOperatorTypeConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'BinaryExpressionOperatorTypeConst was not overloaded by native module initialization") + } + _BinaryExpressionIsLogicalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'BinaryExpressionIsLogicalConst was not overloaded by native module initialization") + } + _BinaryExpressionIsLogicalExtendedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'BinaryExpressionIsLogicalExtendedConst was not overloaded by native module initialization") + } + _BinaryExpressionIsBitwiseConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'BinaryExpressionIsBitwiseConst was not overloaded by native module initialization") + } + _BinaryExpressionIsArithmeticConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'BinaryExpressionIsArithmeticConst was not overloaded by native module initialization") + } + _BinaryExpressionSetLeft(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'BinaryExpressionSetLeft was not overloaded by native module initialization") + } + _BinaryExpressionSetRight(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'BinaryExpressionSetRight was not overloaded by native module initialization") + } + _BinaryExpressionSetResult(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'BinaryExpressionSetResult was not overloaded by native module initialization") + } + _BinaryExpressionSetOperator(context: KNativePointer, receiver: KNativePointer, operatorType: KInt): void { + throw new Error("'BinaryExpressionSetOperator was not overloaded by native module initialization") + } + _CreateSuperExpression(context: KNativePointer): KNativePointer { + throw new Error("'CreateSuperExpression was not overloaded by native module initialization") + } + _UpdateSuperExpression(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateSuperExpression was not overloaded by native module initialization") + } + _CreateAssertStatement(context: KNativePointer, test: KNativePointer, second: KNativePointer): KNativePointer { + throw new Error("'CreateAssertStatement was not overloaded by native module initialization") + } + _UpdateAssertStatement(context: KNativePointer, original: KNativePointer, test: KNativePointer, second: KNativePointer): KNativePointer { + throw new Error("'UpdateAssertStatement was not overloaded by native module initialization") + } + _AssertStatementTestConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssertStatementTestConst was not overloaded by native module initialization") + } + _AssertStatementTest(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssertStatementTest was not overloaded by native module initialization") + } + _AssertStatementSecondConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssertStatementSecondConst was not overloaded by native module initialization") + } + _CreateTSStringKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSStringKeyword was not overloaded by native module initialization") + } + _UpdateTSStringKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSStringKeyword was not overloaded by native module initialization") + } + _CreateAssignmentExpression(context: KNativePointer, left: KNativePointer, right: KNativePointer, assignmentOperator: KInt): KNativePointer { + throw new Error("'CreateAssignmentExpression was not overloaded by native module initialization") + } + _UpdateAssignmentExpression(context: KNativePointer, original: KNativePointer, left: KNativePointer, right: KNativePointer, assignmentOperator: KInt): KNativePointer { + throw new Error("'UpdateAssignmentExpression was not overloaded by native module initialization") + } + _CreateAssignmentExpression1(context: KNativePointer, type: KInt, left: KNativePointer, right: KNativePointer, assignmentOperator: KInt): KNativePointer { + throw new Error("'CreateAssignmentExpression1 was not overloaded by native module initialization") + } + _UpdateAssignmentExpression1(context: KNativePointer, original: KNativePointer, type: KInt, left: KNativePointer, right: KNativePointer, assignmentOperator: KInt): KNativePointer { + throw new Error("'UpdateAssignmentExpression1 was not overloaded by native module initialization") + } + _AssignmentExpressionLeftConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssignmentExpressionLeftConst was not overloaded by native module initialization") + } + _AssignmentExpressionLeft(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssignmentExpressionLeft was not overloaded by native module initialization") + } + _AssignmentExpressionRight(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssignmentExpressionRight was not overloaded by native module initialization") + } + _AssignmentExpressionRightConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssignmentExpressionRightConst was not overloaded by native module initialization") + } + _AssignmentExpressionSetRight(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'AssignmentExpressionSetRight was not overloaded by native module initialization") + } + _AssignmentExpressionSetLeft(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'AssignmentExpressionSetLeft was not overloaded by native module initialization") + } + _AssignmentExpressionResultConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssignmentExpressionResultConst was not overloaded by native module initialization") + } + _AssignmentExpressionResult(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AssignmentExpressionResult was not overloaded by native module initialization") + } + _AssignmentExpressionOperatorTypeConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'AssignmentExpressionOperatorTypeConst was not overloaded by native module initialization") + } + _AssignmentExpressionSetOperatorType(context: KNativePointer, receiver: KNativePointer, tokenType: KInt): KInt { + throw new Error("'AssignmentExpressionSetOperatorType was not overloaded by native module initialization") + } + _AssignmentExpressionSetResult(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'AssignmentExpressionSetResult was not overloaded by native module initialization") + } + _AssignmentExpressionIsLogicalExtendedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AssignmentExpressionIsLogicalExtendedConst was not overloaded by native module initialization") + } + _AssignmentExpressionSetIgnoreConstAssign(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'AssignmentExpressionSetIgnoreConstAssign was not overloaded by native module initialization") + } + _AssignmentExpressionIsIgnoreConstAssignConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AssignmentExpressionIsIgnoreConstAssignConst was not overloaded by native module initialization") + } + _AssignmentExpressionConvertibleToAssignmentPatternLeft(context: KNativePointer, receiver: KNativePointer, mustBePattern: KBoolean): KBoolean { + throw new Error("'AssignmentExpressionConvertibleToAssignmentPatternLeft was not overloaded by native module initialization") + } + _AssignmentExpressionConvertibleToAssignmentPatternRight(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AssignmentExpressionConvertibleToAssignmentPatternRight was not overloaded by native module initialization") + } + _AssignmentExpressionConvertibleToAssignmentPattern(context: KNativePointer, receiver: KNativePointer, mustBePattern: KBoolean): KBoolean { + throw new Error("'AssignmentExpressionConvertibleToAssignmentPattern was not overloaded by native module initialization") + } + _CreateExpressionStatement(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateExpressionStatement was not overloaded by native module initialization") + } + _UpdateExpressionStatement(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateExpressionStatement was not overloaded by native module initialization") + } + _ExpressionStatementGetExpressionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExpressionStatementGetExpressionConst was not overloaded by native module initialization") + } + _ExpressionStatementGetExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExpressionStatementGetExpression was not overloaded by native module initialization") + } + _ExpressionStatementSetExpression(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'ExpressionStatementSetExpression was not overloaded by native module initialization") + } + _ETSModuleIdent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSModuleIdent was not overloaded by native module initialization") + } + _ETSModuleIdentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSModuleIdentConst was not overloaded by native module initialization") + } + _ETSModuleIsETSScriptConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSModuleIsETSScriptConst was not overloaded by native module initialization") + } + _ETSModuleIsNamespaceConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSModuleIsNamespaceConst was not overloaded by native module initialization") + } + _ETSModuleIsNamespaceChainLastNodeConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSModuleIsNamespaceChainLastNodeConst was not overloaded by native module initialization") + } + _ETSModuleSetNamespaceChainLastNode(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ETSModuleSetNamespaceChainLastNode was not overloaded by native module initialization") + } + _ETSModuleAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSModuleAnnotations was not overloaded by native module initialization") + } + _ETSModuleAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSModuleAnnotationsConst was not overloaded by native module initialization") + } + _ETSModuleSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'ETSModuleSetAnnotations was not overloaded by native module initialization") + } + _CreateMetaProperty(context: KNativePointer, kind: KInt): KNativePointer { + throw new Error("'CreateMetaProperty was not overloaded by native module initialization") + } + _UpdateMetaProperty(context: KNativePointer, original: KNativePointer, kind: KInt): KNativePointer { + throw new Error("'UpdateMetaProperty was not overloaded by native module initialization") + } + _MetaPropertyKindConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'MetaPropertyKindConst was not overloaded by native module initialization") + } + _CreateTSArrayType(context: KNativePointer, elementType: KNativePointer): KNativePointer { + throw new Error("'CreateTSArrayType was not overloaded by native module initialization") + } + _UpdateTSArrayType(context: KNativePointer, original: KNativePointer, elementType: KNativePointer): KNativePointer { + throw new Error("'UpdateTSArrayType was not overloaded by native module initialization") + } + _TSArrayTypeElementTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSArrayTypeElementTypeConst was not overloaded by native module initialization") + } + _CreateTSSignatureDeclaration(context: KNativePointer, kind: KInt, signature: KNativePointer): KNativePointer { + throw new Error("'CreateTSSignatureDeclaration was not overloaded by native module initialization") + } + _UpdateTSSignatureDeclaration(context: KNativePointer, original: KNativePointer, kind: KInt, signature: KNativePointer): KNativePointer { + throw new Error("'UpdateTSSignatureDeclaration was not overloaded by native module initialization") + } + _TSSignatureDeclarationTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSSignatureDeclarationTypeParamsConst was not overloaded by native module initialization") + } + _TSSignatureDeclarationTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSSignatureDeclarationTypeParams was not overloaded by native module initialization") + } + _TSSignatureDeclarationParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSSignatureDeclarationParamsConst was not overloaded by native module initialization") + } + _TSSignatureDeclarationReturnTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSSignatureDeclarationReturnTypeAnnotationConst was not overloaded by native module initialization") + } + _TSSignatureDeclarationReturnTypeAnnotation(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSSignatureDeclarationReturnTypeAnnotation was not overloaded by native module initialization") + } + _TSSignatureDeclarationKindConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'TSSignatureDeclarationKindConst was not overloaded by native module initialization") + } + _CreateExportAllDeclaration(context: KNativePointer, source: KNativePointer, exported: KNativePointer): KNativePointer { + throw new Error("'CreateExportAllDeclaration was not overloaded by native module initialization") + } + _UpdateExportAllDeclaration(context: KNativePointer, original: KNativePointer, source: KNativePointer, exported: KNativePointer): KNativePointer { + throw new Error("'UpdateExportAllDeclaration was not overloaded by native module initialization") + } + _ExportAllDeclarationSourceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportAllDeclarationSourceConst was not overloaded by native module initialization") + } + _ExportAllDeclarationExportedConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportAllDeclarationExportedConst was not overloaded by native module initialization") + } + _CreateExportSpecifier(context: KNativePointer, local: KNativePointer, exported: KNativePointer): KNativePointer { + throw new Error("'CreateExportSpecifier was not overloaded by native module initialization") + } + _UpdateExportSpecifier(context: KNativePointer, original: KNativePointer, local: KNativePointer, exported: KNativePointer): KNativePointer { + throw new Error("'UpdateExportSpecifier was not overloaded by native module initialization") + } + _ExportSpecifierLocalConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportSpecifierLocalConst was not overloaded by native module initialization") + } + _ExportSpecifierExportedConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportSpecifierExportedConst was not overloaded by native module initialization") + } + _CreateTSTupleType(context: KNativePointer, elementTypes: BigUint64Array, elementTypesSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateTSTupleType was not overloaded by native module initialization") + } + _UpdateTSTupleType(context: KNativePointer, original: KNativePointer, elementTypes: BigUint64Array, elementTypesSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateTSTupleType was not overloaded by native module initialization") + } + _TSTupleTypeElementTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTupleTypeElementTypeConst was not overloaded by native module initialization") + } + _CreateFunctionExpression(context: KNativePointer, func: KNativePointer): KNativePointer { + throw new Error("'CreateFunctionExpression was not overloaded by native module initialization") + } + _UpdateFunctionExpression(context: KNativePointer, original: KNativePointer, func: KNativePointer): KNativePointer { + throw new Error("'UpdateFunctionExpression was not overloaded by native module initialization") + } + _CreateFunctionExpression1(context: KNativePointer, namedExpr: KNativePointer, func: KNativePointer): KNativePointer { + throw new Error("'CreateFunctionExpression1 was not overloaded by native module initialization") + } + _UpdateFunctionExpression1(context: KNativePointer, original: KNativePointer, namedExpr: KNativePointer, func: KNativePointer): KNativePointer { + throw new Error("'UpdateFunctionExpression1 was not overloaded by native module initialization") + } + _FunctionExpressionFunctionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionExpressionFunctionConst was not overloaded by native module initialization") + } + _FunctionExpressionFunction(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionExpressionFunction was not overloaded by native module initialization") + } + _FunctionExpressionIsAnonymousConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'FunctionExpressionIsAnonymousConst was not overloaded by native module initialization") + } + _FunctionExpressionId(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionExpressionId was not overloaded by native module initialization") + } + _CreateTSIndexSignature(context: KNativePointer, param: KNativePointer, typeAnnotation: KNativePointer, readonly_arg: KBoolean): KNativePointer { + throw new Error("'CreateTSIndexSignature was not overloaded by native module initialization") + } + _UpdateTSIndexSignature(context: KNativePointer, original: KNativePointer, param: KNativePointer, typeAnnotation: KNativePointer, readonly_arg: KBoolean): KNativePointer { + throw new Error("'UpdateTSIndexSignature was not overloaded by native module initialization") + } + _TSIndexSignatureParamConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSIndexSignatureParamConst was not overloaded by native module initialization") + } + _TSIndexSignatureTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSIndexSignatureTypeAnnotationConst was not overloaded by native module initialization") + } + _TSIndexSignatureReadonlyConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSIndexSignatureReadonlyConst was not overloaded by native module initialization") + } + _TSIndexSignatureKindConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'TSIndexSignatureKindConst was not overloaded by native module initialization") + } + _CreateTSModuleDeclaration(context: KNativePointer, name: KNativePointer, body: KNativePointer, declare: KBoolean, _global: KBoolean): KNativePointer { + throw new Error("'CreateTSModuleDeclaration was not overloaded by native module initialization") + } + _UpdateTSModuleDeclaration(context: KNativePointer, original: KNativePointer, name: KNativePointer, body: KNativePointer, declare: KBoolean, _global: KBoolean): KNativePointer { + throw new Error("'UpdateTSModuleDeclaration was not overloaded by native module initialization") + } + _TSModuleDeclarationNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSModuleDeclarationNameConst was not overloaded by native module initialization") + } + _TSModuleDeclarationBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSModuleDeclarationBodyConst was not overloaded by native module initialization") + } + _TSModuleDeclarationGlobalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSModuleDeclarationGlobalConst was not overloaded by native module initialization") + } + _TSModuleDeclarationIsExternalOrAmbientConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSModuleDeclarationIsExternalOrAmbientConst was not overloaded by native module initialization") + } + _CreateImportDeclaration(context: KNativePointer, source: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt, importKind: KInt): KNativePointer { + throw new Error("'CreateImportDeclaration was not overloaded by native module initialization") + } + _UpdateImportDeclaration(context: KNativePointer, original: KNativePointer, source: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt, importKind: KInt): KNativePointer { + throw new Error("'UpdateImportDeclaration was not overloaded by native module initialization") + } + _ImportDeclarationSourceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportDeclarationSourceConst was not overloaded by native module initialization") + } + _ImportDeclarationSource(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportDeclarationSource was not overloaded by native module initialization") + } + _ImportDeclarationSpecifiersConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportDeclarationSpecifiersConst was not overloaded by native module initialization") + } + _ImportDeclarationSpecifiers(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportDeclarationSpecifiers was not overloaded by native module initialization") + } + _ImportDeclarationIsTypeKindConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ImportDeclarationIsTypeKindConst was not overloaded by native module initialization") + } + _CreateTSParenthesizedType(context: KNativePointer, type: KNativePointer): KNativePointer { + throw new Error("'CreateTSParenthesizedType was not overloaded by native module initialization") + } + _UpdateTSParenthesizedType(context: KNativePointer, original: KNativePointer, type: KNativePointer): KNativePointer { + throw new Error("'UpdateTSParenthesizedType was not overloaded by native module initialization") + } + _TSParenthesizedTypeTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSParenthesizedTypeTypeConst was not overloaded by native module initialization") + } + _CreateCharLiteral(context: KNativePointer): KNativePointer { + throw new Error("'CreateCharLiteral was not overloaded by native module initialization") + } + _UpdateCharLiteral(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateCharLiteral was not overloaded by native module initialization") + } + _CreateETSPackageDeclaration(context: KNativePointer, name: KNativePointer): KNativePointer { + throw new Error("'CreateETSPackageDeclaration was not overloaded by native module initialization") + } + _UpdateETSPackageDeclaration(context: KNativePointer, original: KNativePointer, name: KNativePointer): KNativePointer { + throw new Error("'UpdateETSPackageDeclaration was not overloaded by native module initialization") + } + _CreateETSImportDeclaration(context: KNativePointer, importPath: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt, importKind: KInt): KNativePointer { + throw new Error("'CreateETSImportDeclaration was not overloaded by native module initialization") + } + _UpdateETSImportDeclaration(context: KNativePointer, original: KNativePointer, source: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt, importKind: KInt): KNativePointer { + throw new Error("'UpdateETSImportDeclaration was not overloaded by native module initialization") + } + _ETSImportDeclarationHasDeclConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSImportDeclarationHasDeclConst was not overloaded by native module initialization") + } + _ETSImportDeclarationIsPureDynamicConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSImportDeclarationIsPureDynamicConst was not overloaded by native module initialization") + } + _ETSImportDeclarationAssemblerName(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ETSImportDeclarationAssemblerName was not overloaded by native module initialization") + } + _ETSImportDeclarationAssemblerNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ETSImportDeclarationAssemblerNameConst was not overloaded by native module initialization") + } + _ETSImportDeclarationSourceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSImportDeclarationSourceConst was not overloaded by native module initialization") + } + _ETSImportDeclarationResolvedSource(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSImportDeclarationResolvedSource was not overloaded by native module initialization") + } + _ETSImportDeclarationResolvedSourceConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ETSImportDeclarationResolvedSourceConst was not overloaded by native module initialization") + } + _CreateETSStructDeclaration(context: KNativePointer, def: KNativePointer): KNativePointer { + throw new Error("'CreateETSStructDeclaration was not overloaded by native module initialization") + } + _UpdateETSStructDeclaration(context: KNativePointer, original: KNativePointer, def: KNativePointer): KNativePointer { + throw new Error("'UpdateETSStructDeclaration was not overloaded by native module initialization") + } + _CreateTSModuleBlock(context: KNativePointer, statements: BigUint64Array, statementsSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateTSModuleBlock was not overloaded by native module initialization") + } + _UpdateTSModuleBlock(context: KNativePointer, original: KNativePointer, statements: BigUint64Array, statementsSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateTSModuleBlock was not overloaded by native module initialization") + } + _TSModuleBlockStatementsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSModuleBlockStatementsConst was not overloaded by native module initialization") + } + _CreateETSNewArrayInstanceExpression(context: KNativePointer, typeReference: KNativePointer, dimension: KNativePointer): KNativePointer { + throw new Error("'CreateETSNewArrayInstanceExpression was not overloaded by native module initialization") + } + _UpdateETSNewArrayInstanceExpression(context: KNativePointer, original: KNativePointer, typeReference: KNativePointer, dimension: KNativePointer): KNativePointer { + throw new Error("'UpdateETSNewArrayInstanceExpression was not overloaded by native module initialization") + } + _ETSNewArrayInstanceExpressionTypeReference(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewArrayInstanceExpressionTypeReference was not overloaded by native module initialization") + } + _ETSNewArrayInstanceExpressionTypeReferenceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewArrayInstanceExpressionTypeReferenceConst was not overloaded by native module initialization") + } + _ETSNewArrayInstanceExpressionDimension(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewArrayInstanceExpressionDimension was not overloaded by native module initialization") + } + _ETSNewArrayInstanceExpressionDimensionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewArrayInstanceExpressionDimensionConst was not overloaded by native module initialization") + } + _ETSNewArrayInstanceExpressionSetDimension(context: KNativePointer, receiver: KNativePointer, dimension: KNativePointer): void { + throw new Error("'ETSNewArrayInstanceExpressionSetDimension was not overloaded by native module initialization") + } + _CreateAnnotationDeclaration(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateAnnotationDeclaration was not overloaded by native module initialization") + } + _UpdateAnnotationDeclaration(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateAnnotationDeclaration was not overloaded by native module initialization") + } + _CreateAnnotationDeclaration1(context: KNativePointer, expr: KNativePointer, properties: BigUint64Array, propertiesSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateAnnotationDeclaration1 was not overloaded by native module initialization") + } + _UpdateAnnotationDeclaration1(context: KNativePointer, original: KNativePointer, expr: KNativePointer, properties: BigUint64Array, propertiesSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateAnnotationDeclaration1 was not overloaded by native module initialization") + } + _AnnotationDeclarationInternalNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'AnnotationDeclarationInternalNameConst was not overloaded by native module initialization") + } + _AnnotationDeclarationSetInternalName(context: KNativePointer, receiver: KNativePointer, internalName: KStringPtr): void { + throw new Error("'AnnotationDeclarationSetInternalName was not overloaded by native module initialization") + } + _AnnotationDeclarationExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationDeclarationExprConst was not overloaded by native module initialization") + } + _AnnotationDeclarationExpr(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationDeclarationExpr was not overloaded by native module initialization") + } + _AnnotationDeclarationProperties(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationDeclarationProperties was not overloaded by native module initialization") + } + _AnnotationDeclarationPropertiesConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationDeclarationPropertiesConst was not overloaded by native module initialization") + } + _AnnotationDeclarationPropertiesPtrConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationDeclarationPropertiesPtrConst was not overloaded by native module initialization") + } + _AnnotationDeclarationAddProperties(context: KNativePointer, receiver: KNativePointer, properties: BigUint64Array, propertiesSequenceLength: KUInt): void { + throw new Error("'AnnotationDeclarationAddProperties was not overloaded by native module initialization") + } + _AnnotationDeclarationIsSourceRetentionConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AnnotationDeclarationIsSourceRetentionConst was not overloaded by native module initialization") + } + _AnnotationDeclarationIsBytecodeRetentionConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AnnotationDeclarationIsBytecodeRetentionConst was not overloaded by native module initialization") + } + _AnnotationDeclarationIsRuntimeRetentionConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'AnnotationDeclarationIsRuntimeRetentionConst was not overloaded by native module initialization") + } + _AnnotationDeclarationSetSourceRetention(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'AnnotationDeclarationSetSourceRetention was not overloaded by native module initialization") + } + _AnnotationDeclarationSetBytecodeRetention(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'AnnotationDeclarationSetBytecodeRetention was not overloaded by native module initialization") + } + _AnnotationDeclarationSetRuntimeRetention(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'AnnotationDeclarationSetRuntimeRetention was not overloaded by native module initialization") + } + _AnnotationDeclarationGetBaseNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationDeclarationGetBaseNameConst was not overloaded by native module initialization") + } + _AnnotationDeclarationAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationDeclarationAnnotations was not overloaded by native module initialization") + } + _AnnotationDeclarationAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationDeclarationAnnotationsConst was not overloaded by native module initialization") + } + _AnnotationDeclarationSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'AnnotationDeclarationSetAnnotations was not overloaded by native module initialization") + } + _CreateAnnotationUsageIr(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateAnnotationUsageIr was not overloaded by native module initialization") + } + _UpdateAnnotationUsageIr(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateAnnotationUsageIr was not overloaded by native module initialization") + } + _CreateAnnotationUsageIr1(context: KNativePointer, expr: KNativePointer, properties: BigUint64Array, propertiesSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateAnnotationUsageIr1 was not overloaded by native module initialization") + } + _UpdateAnnotationUsageIr1(context: KNativePointer, original: KNativePointer, expr: KNativePointer, properties: BigUint64Array, propertiesSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateAnnotationUsageIr1 was not overloaded by native module initialization") + } + _AnnotationUsageIrExpr(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationUsageIrExpr was not overloaded by native module initialization") + } + _AnnotationUsageIrProperties(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationUsageIrProperties was not overloaded by native module initialization") + } + _AnnotationUsageIrPropertiesConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationUsageIrPropertiesConst was not overloaded by native module initialization") + } + _AnnotationUsageIrPropertiesPtrConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationUsageIrPropertiesPtrConst was not overloaded by native module initialization") + } + _AnnotationUsageIrAddProperty(context: KNativePointer, receiver: KNativePointer, property: KNativePointer): void { + throw new Error("'AnnotationUsageIrAddProperty was not overloaded by native module initialization") + } + _AnnotationUsageIrSetProperties(context: KNativePointer, receiver: KNativePointer, properties: BigUint64Array, propertiesSequenceLength: KUInt): void { + throw new Error("'AnnotationUsageIrSetProperties was not overloaded by native module initialization") + } + _AnnotationUsageIrGetBaseNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotationUsageIrGetBaseNameConst was not overloaded by native module initialization") + } + _CreateEmptyStatement(context: KNativePointer): KNativePointer { + throw new Error("'CreateEmptyStatement was not overloaded by native module initialization") + } + _UpdateEmptyStatement(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateEmptyStatement was not overloaded by native module initialization") + } + _CreateETSLaunchExpression(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateETSLaunchExpression was not overloaded by native module initialization") + } + _UpdateETSLaunchExpression(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateETSLaunchExpression was not overloaded by native module initialization") + } + _ETSLaunchExpressionIsStaticCallConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSLaunchExpressionIsStaticCallConst was not overloaded by native module initialization") + } + _ETSLaunchExpressionCallConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSLaunchExpressionCallConst was not overloaded by native module initialization") + } + _CreateWhileStatement(context: KNativePointer, test: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'CreateWhileStatement was not overloaded by native module initialization") + } + _UpdateWhileStatement(context: KNativePointer, original: KNativePointer, test: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'UpdateWhileStatement was not overloaded by native module initialization") + } + _WhileStatementTestConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'WhileStatementTestConst was not overloaded by native module initialization") + } + _WhileStatementTest(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'WhileStatementTest was not overloaded by native module initialization") + } + _WhileStatementBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'WhileStatementBodyConst was not overloaded by native module initialization") + } + _WhileStatementBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'WhileStatementBody was not overloaded by native module initialization") + } + _CreateFunctionSignature(context: KNativePointer, typeParams: KNativePointer, params: BigUint64Array, paramsSequenceLength: KUInt, returnTypeAnnotation: KNativePointer, hasReceiver: KBoolean): KNativePointer { + throw new Error("'CreateFunctionSignature was not overloaded by native module initialization") + } + _FunctionSignatureParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionSignatureParamsConst was not overloaded by native module initialization") + } + _FunctionSignatureParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionSignatureParams was not overloaded by native module initialization") + } + _FunctionSignatureTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionSignatureTypeParams was not overloaded by native module initialization") + } + _FunctionSignatureTypeParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionSignatureTypeParamsConst was not overloaded by native module initialization") + } + _FunctionSignatureReturnType(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionSignatureReturnType was not overloaded by native module initialization") + } + _FunctionSignatureSetReturnType(context: KNativePointer, receiver: KNativePointer, type: KNativePointer): void { + throw new Error("'FunctionSignatureSetReturnType was not overloaded by native module initialization") + } + _FunctionSignatureReturnTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionSignatureReturnTypeConst was not overloaded by native module initialization") + } + _FunctionSignatureClone(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'FunctionSignatureClone was not overloaded by native module initialization") + } + _FunctionSignatureHasReceiverConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'FunctionSignatureHasReceiverConst was not overloaded by native module initialization") + } + _CreateChainExpression(context: KNativePointer, expression: KNativePointer): KNativePointer { + throw new Error("'CreateChainExpression was not overloaded by native module initialization") + } + _UpdateChainExpression(context: KNativePointer, original: KNativePointer, expression: KNativePointer): KNativePointer { + throw new Error("'UpdateChainExpression was not overloaded by native module initialization") + } + _ChainExpressionGetExpressionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ChainExpressionGetExpressionConst was not overloaded by native module initialization") + } + _ChainExpressionGetExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ChainExpressionGetExpression was not overloaded by native module initialization") + } + _CreateTSIntersectionType(context: KNativePointer, types: BigUint64Array, typesSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateTSIntersectionType was not overloaded by native module initialization") + } + _UpdateTSIntersectionType(context: KNativePointer, original: KNativePointer, types: BigUint64Array, typesSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateTSIntersectionType was not overloaded by native module initialization") + } + _TSIntersectionTypeTypesConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSIntersectionTypeTypesConst was not overloaded by native module initialization") + } + _CreateUpdateExpression(context: KNativePointer, argument: KNativePointer, updateOperator: KInt, isPrefix: KBoolean): KNativePointer { + throw new Error("'CreateUpdateExpression was not overloaded by native module initialization") + } + _UpdateUpdateExpression(context: KNativePointer, original: KNativePointer, argument: KNativePointer, updateOperator: KInt, isPrefix: KBoolean): KNativePointer { + throw new Error("'UpdateUpdateExpression was not overloaded by native module initialization") + } + _UpdateExpressionOperatorTypeConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'UpdateExpressionOperatorTypeConst was not overloaded by native module initialization") + } + _UpdateExpressionArgument(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'UpdateExpressionArgument was not overloaded by native module initialization") + } + _UpdateExpressionArgumentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'UpdateExpressionArgumentConst was not overloaded by native module initialization") + } + _UpdateExpressionIsPrefixConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'UpdateExpressionIsPrefixConst was not overloaded by native module initialization") + } + _CreateBlockExpression(context: KNativePointer, statements: BigUint64Array, statementsSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateBlockExpression was not overloaded by native module initialization") + } + _UpdateBlockExpression(context: KNativePointer, original: KNativePointer, statements: BigUint64Array, statementsSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateBlockExpression was not overloaded by native module initialization") + } + _BlockExpressionStatementsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BlockExpressionStatementsConst was not overloaded by native module initialization") + } + _BlockExpressionStatements(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BlockExpressionStatements was not overloaded by native module initialization") + } + _BlockExpressionAddStatements(context: KNativePointer, receiver: KNativePointer, statements: BigUint64Array, statementsSequenceLength: KUInt): void { + throw new Error("'BlockExpressionAddStatements was not overloaded by native module initialization") + } + _BlockExpressionAddStatement(context: KNativePointer, receiver: KNativePointer, statement: KNativePointer): void { + throw new Error("'BlockExpressionAddStatement was not overloaded by native module initialization") + } + _CreateTSTypeLiteral(context: KNativePointer, members: BigUint64Array, membersSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateTSTypeLiteral was not overloaded by native module initialization") + } + _UpdateTSTypeLiteral(context: KNativePointer, original: KNativePointer, members: BigUint64Array, membersSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateTSTypeLiteral was not overloaded by native module initialization") + } + _TSTypeLiteralMembersConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeLiteralMembersConst was not overloaded by native module initialization") + } + _CreateTSTypeParameter(context: KNativePointer, name: KNativePointer, constraint: KNativePointer, defaultType: KNativePointer): KNativePointer { + throw new Error("'CreateTSTypeParameter was not overloaded by native module initialization") + } + _UpdateTSTypeParameter(context: KNativePointer, original: KNativePointer, name: KNativePointer, constraint: KNativePointer, defaultType: KNativePointer): KNativePointer { + throw new Error("'UpdateTSTypeParameter was not overloaded by native module initialization") + } + _CreateTSTypeParameter1(context: KNativePointer, name: KNativePointer, constraint: KNativePointer, defaultType: KNativePointer, flags: KInt): KNativePointer { + throw new Error("'CreateTSTypeParameter1 was not overloaded by native module initialization") + } + _UpdateTSTypeParameter1(context: KNativePointer, original: KNativePointer, name: KNativePointer, constraint: KNativePointer, defaultType: KNativePointer, flags: KInt): KNativePointer { + throw new Error("'UpdateTSTypeParameter1 was not overloaded by native module initialization") + } + _TSTypeParameterNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterNameConst was not overloaded by native module initialization") + } + _TSTypeParameterName(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterName was not overloaded by native module initialization") + } + _TSTypeParameterConstraint(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterConstraint was not overloaded by native module initialization") + } + _TSTypeParameterConstraintConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterConstraintConst was not overloaded by native module initialization") + } + _TSTypeParameterSetConstraint(context: KNativePointer, receiver: KNativePointer, constraint: KNativePointer): void { + throw new Error("'TSTypeParameterSetConstraint was not overloaded by native module initialization") + } + _TSTypeParameterDefaultTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterDefaultTypeConst was not overloaded by native module initialization") + } + _TSTypeParameterSetDefaultType(context: KNativePointer, receiver: KNativePointer, defaultType: KNativePointer): void { + throw new Error("'TSTypeParameterSetDefaultType was not overloaded by native module initialization") + } + _TSTypeParameterAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterAnnotations was not overloaded by native module initialization") + } + _TSTypeParameterAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterAnnotationsConst was not overloaded by native module initialization") + } + _TSTypeParameterSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'TSTypeParameterSetAnnotations was not overloaded by native module initialization") + } + _CreateTSBooleanKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSBooleanKeyword was not overloaded by native module initialization") + } + _UpdateTSBooleanKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSBooleanKeyword was not overloaded by native module initialization") + } + _CreateSpreadElement(context: KNativePointer, nodeType: KInt, argument: KNativePointer): KNativePointer { + throw new Error("'CreateSpreadElement was not overloaded by native module initialization") + } + _UpdateSpreadElement(context: KNativePointer, original: KNativePointer, nodeType: KInt, argument: KNativePointer): KNativePointer { + throw new Error("'UpdateSpreadElement was not overloaded by native module initialization") + } + _SpreadElementArgumentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SpreadElementArgumentConst was not overloaded by native module initialization") + } + _SpreadElementArgument(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SpreadElementArgument was not overloaded by native module initialization") + } + _SpreadElementIsOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'SpreadElementIsOptionalConst was not overloaded by native module initialization") + } + _SpreadElementDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SpreadElementDecoratorsConst was not overloaded by native module initialization") + } + _SpreadElementSetOptional(context: KNativePointer, receiver: KNativePointer, optional_arg: KBoolean): void { + throw new Error("'SpreadElementSetOptional was not overloaded by native module initialization") + } + _SpreadElementValidateExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SpreadElementValidateExpression was not overloaded by native module initialization") + } + _SpreadElementConvertibleToRest(context: KNativePointer, receiver: KNativePointer, isDeclaration: KBoolean, allowPattern: KBoolean): KBoolean { + throw new Error("'SpreadElementConvertibleToRest was not overloaded by native module initialization") + } + _SpreadElementTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SpreadElementTypeAnnotationConst was not overloaded by native module initialization") + } + _SpreadElementSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'SpreadElementSetTsTypeAnnotation was not overloaded by native module initialization") + } + _CreateTSTypePredicate(context: KNativePointer, parameterName: KNativePointer, typeAnnotation: KNativePointer, asserts: KBoolean): KNativePointer { + throw new Error("'CreateTSTypePredicate was not overloaded by native module initialization") + } + _UpdateTSTypePredicate(context: KNativePointer, original: KNativePointer, parameterName: KNativePointer, typeAnnotation: KNativePointer, asserts: KBoolean): KNativePointer { + throw new Error("'UpdateTSTypePredicate was not overloaded by native module initialization") + } + _TSTypePredicateParameterNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypePredicateParameterNameConst was not overloaded by native module initialization") + } + _TSTypePredicateTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypePredicateTypeAnnotationConst was not overloaded by native module initialization") + } + _TSTypePredicateAssertsConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSTypePredicateAssertsConst was not overloaded by native module initialization") + } + _CreateImportNamespaceSpecifier(context: KNativePointer, local: KNativePointer): KNativePointer { + throw new Error("'CreateImportNamespaceSpecifier was not overloaded by native module initialization") + } + _UpdateImportNamespaceSpecifier(context: KNativePointer, original: KNativePointer, local: KNativePointer): KNativePointer { + throw new Error("'UpdateImportNamespaceSpecifier was not overloaded by native module initialization") + } + _ImportNamespaceSpecifierLocal(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportNamespaceSpecifierLocal was not overloaded by native module initialization") + } + _ImportNamespaceSpecifierLocalConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportNamespaceSpecifierLocalConst was not overloaded by native module initialization") + } + _CreateExportNamedDeclaration(context: KNativePointer, source: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateExportNamedDeclaration was not overloaded by native module initialization") + } + _UpdateExportNamedDeclaration(context: KNativePointer, original: KNativePointer, source: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateExportNamedDeclaration was not overloaded by native module initialization") + } + _CreateExportNamedDeclaration1(context: KNativePointer, decl: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateExportNamedDeclaration1 was not overloaded by native module initialization") + } + _UpdateExportNamedDeclaration1(context: KNativePointer, original: KNativePointer, decl: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateExportNamedDeclaration1 was not overloaded by native module initialization") + } + _CreateExportNamedDeclaration2(context: KNativePointer, decl: KNativePointer): KNativePointer { + throw new Error("'CreateExportNamedDeclaration2 was not overloaded by native module initialization") + } + _UpdateExportNamedDeclaration2(context: KNativePointer, original: KNativePointer, decl: KNativePointer): KNativePointer { + throw new Error("'UpdateExportNamedDeclaration2 was not overloaded by native module initialization") + } + _ExportNamedDeclarationDeclConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportNamedDeclarationDeclConst was not overloaded by native module initialization") + } + _ExportNamedDeclarationSourceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportNamedDeclarationSourceConst was not overloaded by native module initialization") + } + _ExportNamedDeclarationSpecifiersConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExportNamedDeclarationSpecifiersConst was not overloaded by native module initialization") + } + _CreateETSParameterExpression(context: KNativePointer, identOrSpread: KNativePointer, isOptional: KBoolean): KNativePointer { + throw new Error("'CreateETSParameterExpression was not overloaded by native module initialization") + } + _UpdateETSParameterExpression(context: KNativePointer, original: KNativePointer, identOrSpread: KNativePointer, isOptional: KBoolean): KNativePointer { + throw new Error("'UpdateETSParameterExpression was not overloaded by native module initialization") + } + _CreateETSParameterExpression1(context: KNativePointer, identOrSpread: KNativePointer, initializer: KNativePointer): KNativePointer { + throw new Error("'CreateETSParameterExpression1 was not overloaded by native module initialization") + } + _UpdateETSParameterExpression1(context: KNativePointer, original: KNativePointer, identOrSpread: KNativePointer, initializer: KNativePointer): KNativePointer { + throw new Error("'UpdateETSParameterExpression1 was not overloaded by native module initialization") + } + _ETSParameterExpressionNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ETSParameterExpressionNameConst was not overloaded by native module initialization") + } + _ETSParameterExpressionIdentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionIdentConst was not overloaded by native module initialization") + } + _ETSParameterExpressionIdent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionIdent was not overloaded by native module initialization") + } + _ETSParameterExpressionSetIdent(context: KNativePointer, receiver: KNativePointer, ident: KNativePointer): void { + throw new Error("'ETSParameterExpressionSetIdent was not overloaded by native module initialization") + } + _ETSParameterExpressionRestParameterConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionRestParameterConst was not overloaded by native module initialization") + } + _ETSParameterExpressionRestParameter(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionRestParameter was not overloaded by native module initialization") + } + _ETSParameterExpressionInitializerConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionInitializerConst was not overloaded by native module initialization") + } + _ETSParameterExpressionInitializer(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionInitializer was not overloaded by native module initialization") + } + _ETSParameterExpressionSetLexerSaved(context: KNativePointer, receiver: KNativePointer, s: KStringPtr): void { + throw new Error("'ETSParameterExpressionSetLexerSaved was not overloaded by native module initialization") + } + _ETSParameterExpressionLexerSavedConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ETSParameterExpressionLexerSavedConst was not overloaded by native module initialization") + } + _ETSParameterExpressionTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionTypeAnnotationConst was not overloaded by native module initialization") + } + _ETSParameterExpressionTypeAnnotation(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionTypeAnnotation was not overloaded by native module initialization") + } + _ETSParameterExpressionSetTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeNode: KNativePointer): void { + throw new Error("'ETSParameterExpressionSetTypeAnnotation was not overloaded by native module initialization") + } + _ETSParameterExpressionIsOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSParameterExpressionIsOptionalConst was not overloaded by native module initialization") + } + _ETSParameterExpressionSetOptional(context: KNativePointer, receiver: KNativePointer, value: KBoolean): void { + throw new Error("'ETSParameterExpressionSetOptional was not overloaded by native module initialization") + } + _ETSParameterExpressionSetInitializer(context: KNativePointer, receiver: KNativePointer, initExpr: KNativePointer): void { + throw new Error("'ETSParameterExpressionSetInitializer was not overloaded by native module initialization") + } + _ETSParameterExpressionIsRestParameterConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSParameterExpressionIsRestParameterConst was not overloaded by native module initialization") + } + _ETSParameterExpressionGetRequiredParamsConst(context: KNativePointer, receiver: KNativePointer): KUInt { + throw new Error("'ETSParameterExpressionGetRequiredParamsConst was not overloaded by native module initialization") + } + _ETSParameterExpressionSetRequiredParams(context: KNativePointer, receiver: KNativePointer, value: KUInt): void { + throw new Error("'ETSParameterExpressionSetRequiredParams was not overloaded by native module initialization") + } + _ETSParameterExpressionAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionAnnotations was not overloaded by native module initialization") + } + _ETSParameterExpressionAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSParameterExpressionAnnotationsConst was not overloaded by native module initialization") + } + _ETSParameterExpressionSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'ETSParameterExpressionSetAnnotations was not overloaded by native module initialization") + } + _CreateTSTypeParameterInstantiation(context: KNativePointer, params: BigUint64Array, paramsSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateTSTypeParameterInstantiation was not overloaded by native module initialization") + } + _UpdateTSTypeParameterInstantiation(context: KNativePointer, original: KNativePointer, params: BigUint64Array, paramsSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateTSTypeParameterInstantiation was not overloaded by native module initialization") + } + _TSTypeParameterInstantiationParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterInstantiationParamsConst was not overloaded by native module initialization") + } + _CreateNullLiteral(context: KNativePointer): KNativePointer { + throw new Error("'CreateNullLiteral was not overloaded by native module initialization") + } + _UpdateNullLiteral(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateNullLiteral was not overloaded by native module initialization") + } + _CreateTSInferType(context: KNativePointer, typeParam: KNativePointer): KNativePointer { + throw new Error("'CreateTSInferType was not overloaded by native module initialization") + } + _UpdateTSInferType(context: KNativePointer, original: KNativePointer, typeParam: KNativePointer): KNativePointer { + throw new Error("'UpdateTSInferType was not overloaded by native module initialization") + } + _TSInferTypeTypeParamConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInferTypeTypeParamConst was not overloaded by native module initialization") + } + _CreateSwitchCaseStatement(context: KNativePointer, test: KNativePointer, consequent: BigUint64Array, consequentSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateSwitchCaseStatement was not overloaded by native module initialization") + } + _UpdateSwitchCaseStatement(context: KNativePointer, original: KNativePointer, test: KNativePointer, consequent: BigUint64Array, consequentSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateSwitchCaseStatement was not overloaded by native module initialization") + } + _SwitchCaseStatementTest(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SwitchCaseStatementTest was not overloaded by native module initialization") + } + _SwitchCaseStatementTestConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SwitchCaseStatementTestConst was not overloaded by native module initialization") + } + _SwitchCaseStatementConsequentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SwitchCaseStatementConsequentConst was not overloaded by native module initialization") + } + _CreateYieldExpression(context: KNativePointer, argument: KNativePointer, isDelegate: KBoolean): KNativePointer { + throw new Error("'CreateYieldExpression was not overloaded by native module initialization") + } + _UpdateYieldExpression(context: KNativePointer, original: KNativePointer, argument: KNativePointer, isDelegate: KBoolean): KNativePointer { + throw new Error("'UpdateYieldExpression was not overloaded by native module initialization") + } + _YieldExpressionHasDelegateConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'YieldExpressionHasDelegateConst was not overloaded by native module initialization") + } + _YieldExpressionArgumentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'YieldExpressionArgumentConst was not overloaded by native module initialization") + } + _CreateTSImportEqualsDeclaration(context: KNativePointer, id: KNativePointer, moduleReference: KNativePointer, isExport: KBoolean): KNativePointer { + throw new Error("'CreateTSImportEqualsDeclaration was not overloaded by native module initialization") + } + _UpdateTSImportEqualsDeclaration(context: KNativePointer, original: KNativePointer, id: KNativePointer, moduleReference: KNativePointer, isExport: KBoolean): KNativePointer { + throw new Error("'UpdateTSImportEqualsDeclaration was not overloaded by native module initialization") + } + _TSImportEqualsDeclarationIdConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSImportEqualsDeclarationIdConst was not overloaded by native module initialization") + } + _TSImportEqualsDeclarationModuleReferenceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSImportEqualsDeclarationModuleReferenceConst was not overloaded by native module initialization") + } + _TSImportEqualsDeclarationIsExportConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSImportEqualsDeclarationIsExportConst was not overloaded by native module initialization") + } + _CreateBooleanLiteral(context: KNativePointer, value: KBoolean): KNativePointer { + throw new Error("'CreateBooleanLiteral was not overloaded by native module initialization") + } + _UpdateBooleanLiteral(context: KNativePointer, original: KNativePointer, value: KBoolean): KNativePointer { + throw new Error("'UpdateBooleanLiteral was not overloaded by native module initialization") + } + _BooleanLiteralValueConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'BooleanLiteralValueConst was not overloaded by native module initialization") + } + _CreateTSNumberKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSNumberKeyword was not overloaded by native module initialization") + } + _UpdateTSNumberKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSNumberKeyword was not overloaded by native module initialization") + } + _CreateClassStaticBlock(context: KNativePointer, value: KNativePointer): KNativePointer { + throw new Error("'CreateClassStaticBlock was not overloaded by native module initialization") + } + _UpdateClassStaticBlock(context: KNativePointer, original: KNativePointer, value: KNativePointer): KNativePointer { + throw new Error("'UpdateClassStaticBlock was not overloaded by native module initialization") + } + _ClassStaticBlockFunction(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassStaticBlockFunction was not overloaded by native module initialization") + } + _ClassStaticBlockFunctionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassStaticBlockFunctionConst was not overloaded by native module initialization") + } + _ClassStaticBlockNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ClassStaticBlockNameConst was not overloaded by native module initialization") + } + _CreateTSNonNullExpression(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateTSNonNullExpression was not overloaded by native module initialization") + } + _UpdateTSNonNullExpression(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateTSNonNullExpression was not overloaded by native module initialization") + } + _TSNonNullExpressionExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSNonNullExpressionExprConst was not overloaded by native module initialization") + } + _TSNonNullExpressionExpr(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSNonNullExpressionExpr was not overloaded by native module initialization") + } + _TSNonNullExpressionSetExpr(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'TSNonNullExpressionSetExpr was not overloaded by native module initialization") + } + _CreatePrefixAssertionExpression(context: KNativePointer, expr: KNativePointer, type: KNativePointer): KNativePointer { + throw new Error("'CreatePrefixAssertionExpression was not overloaded by native module initialization") + } + _UpdatePrefixAssertionExpression(context: KNativePointer, original: KNativePointer, expr: KNativePointer, type: KNativePointer): KNativePointer { + throw new Error("'UpdatePrefixAssertionExpression was not overloaded by native module initialization") + } + _PrefixAssertionExpressionExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'PrefixAssertionExpressionExprConst was not overloaded by native module initialization") + } + _PrefixAssertionExpressionTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'PrefixAssertionExpressionTypeConst was not overloaded by native module initialization") + } + _CreateClassExpression(context: KNativePointer, def: KNativePointer): KNativePointer { + throw new Error("'CreateClassExpression was not overloaded by native module initialization") + } + _UpdateClassExpression(context: KNativePointer, original: KNativePointer, def: KNativePointer): KNativePointer { + throw new Error("'UpdateClassExpression was not overloaded by native module initialization") + } + _ClassExpressionDefinitionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassExpressionDefinitionConst was not overloaded by native module initialization") + } + _CreateForOfStatement(context: KNativePointer, left: KNativePointer, right: KNativePointer, body: KNativePointer, isAwait: KBoolean): KNativePointer { + throw new Error("'CreateForOfStatement was not overloaded by native module initialization") + } + _UpdateForOfStatement(context: KNativePointer, original: KNativePointer, left: KNativePointer, right: KNativePointer, body: KNativePointer, isAwait: KBoolean): KNativePointer { + throw new Error("'UpdateForOfStatement was not overloaded by native module initialization") + } + _ForOfStatementLeft(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForOfStatementLeft was not overloaded by native module initialization") + } + _ForOfStatementLeftConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForOfStatementLeftConst was not overloaded by native module initialization") + } + _ForOfStatementRight(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForOfStatementRight was not overloaded by native module initialization") + } + _ForOfStatementRightConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForOfStatementRightConst was not overloaded by native module initialization") + } + _ForOfStatementBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForOfStatementBody was not overloaded by native module initialization") + } + _ForOfStatementBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForOfStatementBodyConst was not overloaded by native module initialization") + } + _ForOfStatementIsAwaitConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ForOfStatementIsAwaitConst was not overloaded by native module initialization") + } + _CreateTemplateLiteral(context: KNativePointer, quasis: BigUint64Array, quasisSequenceLength: KUInt, expressions: BigUint64Array, expressionsSequenceLength: KUInt, multilineString: KStringPtr): KNativePointer { + throw new Error("'CreateTemplateLiteral was not overloaded by native module initialization") + } + _UpdateTemplateLiteral(context: KNativePointer, original: KNativePointer, quasis: BigUint64Array, quasisSequenceLength: KUInt, expressions: BigUint64Array, expressionsSequenceLength: KUInt, multilineString: KStringPtr): KNativePointer { + throw new Error("'UpdateTemplateLiteral was not overloaded by native module initialization") + } + _TemplateLiteralQuasisConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TemplateLiteralQuasisConst was not overloaded by native module initialization") + } + _TemplateLiteralExpressionsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TemplateLiteralExpressionsConst was not overloaded by native module initialization") + } + _TemplateLiteralGetMultilineStringConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'TemplateLiteralGetMultilineStringConst was not overloaded by native module initialization") + } + _CreateTSUnionType(context: KNativePointer, types: BigUint64Array, typesSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateTSUnionType was not overloaded by native module initialization") + } + _UpdateTSUnionType(context: KNativePointer, original: KNativePointer, types: BigUint64Array, typesSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateTSUnionType was not overloaded by native module initialization") + } + _TSUnionTypeTypesConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSUnionTypeTypesConst was not overloaded by native module initialization") + } + _CreateTSUnknownKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSUnknownKeyword was not overloaded by native module initialization") + } + _UpdateTSUnknownKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSUnknownKeyword was not overloaded by native module initialization") + } + _CreateIdentifier(context: KNativePointer): KNativePointer { + throw new Error("'CreateIdentifier was not overloaded by native module initialization") + } + _UpdateIdentifier(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateIdentifier was not overloaded by native module initialization") + } + _CreateIdentifier1(context: KNativePointer, name: KStringPtr): KNativePointer { + throw new Error("'CreateIdentifier1 was not overloaded by native module initialization") + } + _UpdateIdentifier1(context: KNativePointer, original: KNativePointer, name: KStringPtr): KNativePointer { + throw new Error("'UpdateIdentifier1 was not overloaded by native module initialization") + } + _CreateIdentifier2(context: KNativePointer, name: KStringPtr, typeAnnotation: KNativePointer): KNativePointer { + throw new Error("'CreateIdentifier2 was not overloaded by native module initialization") + } + _UpdateIdentifier2(context: KNativePointer, original: KNativePointer, name: KStringPtr, typeAnnotation: KNativePointer): KNativePointer { + throw new Error("'UpdateIdentifier2 was not overloaded by native module initialization") + } + _IdentifierNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'IdentifierNameConst was not overloaded by native module initialization") + } + _IdentifierName(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'IdentifierName was not overloaded by native module initialization") + } + _IdentifierSetName(context: KNativePointer, receiver: KNativePointer, newName: KStringPtr): void { + throw new Error("'IdentifierSetName was not overloaded by native module initialization") + } + _IdentifierDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IdentifierDecoratorsConst was not overloaded by native module initialization") + } + _IdentifierIsErrorPlaceHolderConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsErrorPlaceHolderConst was not overloaded by native module initialization") + } + _IdentifierIsOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsOptionalConst was not overloaded by native module initialization") + } + _IdentifierSetOptional(context: KNativePointer, receiver: KNativePointer, optional_arg: KBoolean): void { + throw new Error("'IdentifierSetOptional was not overloaded by native module initialization") + } + _IdentifierIsReferenceConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsReferenceConst was not overloaded by native module initialization") + } + _IdentifierIsTdzConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsTdzConst was not overloaded by native module initialization") + } + _IdentifierSetTdz(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'IdentifierSetTdz was not overloaded by native module initialization") + } + _IdentifierSetAccessor(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'IdentifierSetAccessor was not overloaded by native module initialization") + } + _IdentifierIsAccessorConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsAccessorConst was not overloaded by native module initialization") + } + _IdentifierSetMutator(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'IdentifierSetMutator was not overloaded by native module initialization") + } + _IdentifierIsMutatorConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsMutatorConst was not overloaded by native module initialization") + } + _IdentifierIsReceiverConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsReceiverConst was not overloaded by native module initialization") + } + _IdentifierIsPrivateIdentConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsPrivateIdentConst was not overloaded by native module initialization") + } + _IdentifierSetPrivate(context: KNativePointer, receiver: KNativePointer, isPrivate: KBoolean): void { + throw new Error("'IdentifierSetPrivate was not overloaded by native module initialization") + } + _IdentifierIsIgnoreBoxConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsIgnoreBoxConst was not overloaded by native module initialization") + } + _IdentifierSetIgnoreBox(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'IdentifierSetIgnoreBox was not overloaded by native module initialization") + } + _IdentifierIsAnnotationDeclConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsAnnotationDeclConst was not overloaded by native module initialization") + } + _IdentifierSetAnnotationDecl(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'IdentifierSetAnnotationDecl was not overloaded by native module initialization") + } + _IdentifierIsAnnotationUsageConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'IdentifierIsAnnotationUsageConst was not overloaded by native module initialization") + } + _IdentifierSetAnnotationUsage(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'IdentifierSetAnnotationUsage was not overloaded by native module initialization") + } + _IdentifierCloneReference(context: KNativePointer, receiver: KNativePointer, parent: KNativePointer): KNativePointer { + throw new Error("'IdentifierCloneReference was not overloaded by native module initialization") + } + _IdentifierValidateExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IdentifierValidateExpression was not overloaded by native module initialization") + } + _IdentifierTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'IdentifierTypeAnnotationConst was not overloaded by native module initialization") + } + _IdentifierSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'IdentifierSetTsTypeAnnotation was not overloaded by native module initialization") + } + _CreateOpaqueTypeNode1(context: KNativePointer): KNativePointer { + throw new Error("'CreateOpaqueTypeNode1 was not overloaded by native module initialization") + } + _UpdateOpaqueTypeNode1(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateOpaqueTypeNode1 was not overloaded by native module initialization") + } + _CreateBlockStatement(context: KNativePointer, statementList: BigUint64Array, statementListSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateBlockStatement was not overloaded by native module initialization") + } + _UpdateBlockStatement(context: KNativePointer, original: KNativePointer, statementList: BigUint64Array, statementListSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateBlockStatement was not overloaded by native module initialization") + } + _BlockStatementStatementsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BlockStatementStatementsConst was not overloaded by native module initialization") + } + _BlockStatementStatements(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BlockStatementStatements was not overloaded by native module initialization") + } + _BlockStatementSetStatements(context: KNativePointer, receiver: KNativePointer, statementList: BigUint64Array, statementListSequenceLength: KUInt): void { + throw new Error("'BlockStatementSetStatements was not overloaded by native module initialization") + } + _BlockStatementAddTrailingBlock(context: KNativePointer, receiver: KNativePointer, stmt: KNativePointer, trailingBlock: KNativePointer): void { + throw new Error("'BlockStatementAddTrailingBlock was not overloaded by native module initialization") + } + _CreateDirectEvalExpression(context: KNativePointer, callee: KNativePointer, _arguments: BigUint64Array, _argumentsSequenceLength: KUInt, typeParams: KNativePointer, optional_arg: KBoolean, parserStatus: KUInt): KNativePointer { + throw new Error("'CreateDirectEvalExpression was not overloaded by native module initialization") + } + _UpdateDirectEvalExpression(context: KNativePointer, original: KNativePointer, callee: KNativePointer, _arguments: BigUint64Array, _argumentsSequenceLength: KUInt, typeParams: KNativePointer, optional_arg: KBoolean, parserStatus: KUInt): KNativePointer { + throw new Error("'UpdateDirectEvalExpression was not overloaded by native module initialization") + } + _CreateTSTypeParameterDeclaration(context: KNativePointer, params: BigUint64Array, paramsSequenceLength: KUInt, requiredParams: KUInt): KNativePointer { + throw new Error("'CreateTSTypeParameterDeclaration was not overloaded by native module initialization") + } + _UpdateTSTypeParameterDeclaration(context: KNativePointer, original: KNativePointer, params: BigUint64Array, paramsSequenceLength: KUInt, requiredParams: KUInt): KNativePointer { + throw new Error("'UpdateTSTypeParameterDeclaration was not overloaded by native module initialization") + } + _TSTypeParameterDeclarationParamsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSTypeParameterDeclarationParamsConst was not overloaded by native module initialization") + } + _TSTypeParameterDeclarationAddParam(context: KNativePointer, receiver: KNativePointer, param: KNativePointer): void { + throw new Error("'TSTypeParameterDeclarationAddParam was not overloaded by native module initialization") + } + _TSTypeParameterDeclarationRequiredParamsConst(context: KNativePointer, receiver: KNativePointer): KUInt { + throw new Error("'TSTypeParameterDeclarationRequiredParamsConst was not overloaded by native module initialization") + } + _CreateMethodDefinition(context: KNativePointer, kind: KInt, key: KNativePointer, value: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer { + throw new Error("'CreateMethodDefinition was not overloaded by native module initialization") + } + _UpdateMethodDefinition(context: KNativePointer, original: KNativePointer, kind: KInt, key: KNativePointer, value: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer { + throw new Error("'UpdateMethodDefinition was not overloaded by native module initialization") + } + _MethodDefinitionKindConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'MethodDefinitionKindConst was not overloaded by native module initialization") + } + _MethodDefinitionIsConstructorConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'MethodDefinitionIsConstructorConst was not overloaded by native module initialization") + } + _MethodDefinitionIsExtensionMethodConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'MethodDefinitionIsExtensionMethodConst was not overloaded by native module initialization") + } + _MethodDefinitionOverloadsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MethodDefinitionOverloadsConst was not overloaded by native module initialization") + } + _MethodDefinitionBaseOverloadMethodConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MethodDefinitionBaseOverloadMethodConst was not overloaded by native module initialization") + } + _MethodDefinitionBaseOverloadMethod(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MethodDefinitionBaseOverloadMethod was not overloaded by native module initialization") + } + _MethodDefinitionAsyncPairMethodConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MethodDefinitionAsyncPairMethodConst was not overloaded by native module initialization") + } + _MethodDefinitionAsyncPairMethod(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MethodDefinitionAsyncPairMethod was not overloaded by native module initialization") + } + _MethodDefinitionSetOverloads(context: KNativePointer, receiver: KNativePointer, overloads: BigUint64Array, overloadsSequenceLength: KUInt): void { + throw new Error("'MethodDefinitionSetOverloads was not overloaded by native module initialization") + } + _MethodDefinitionClearOverloads(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'MethodDefinitionClearOverloads was not overloaded by native module initialization") + } + _MethodDefinitionAddOverload(context: KNativePointer, receiver: KNativePointer, overload: KNativePointer): void { + throw new Error("'MethodDefinitionAddOverload was not overloaded by native module initialization") + } + _MethodDefinitionSetBaseOverloadMethod(context: KNativePointer, receiver: KNativePointer, baseOverloadMethod: KNativePointer): void { + throw new Error("'MethodDefinitionSetBaseOverloadMethod was not overloaded by native module initialization") + } + _MethodDefinitionSetAsyncPairMethod(context: KNativePointer, receiver: KNativePointer, method: KNativePointer): void { + throw new Error("'MethodDefinitionSetAsyncPairMethod was not overloaded by native module initialization") + } + _MethodDefinitionHasOverload(context: KNativePointer, receiver: KNativePointer, overload: KNativePointer): KBoolean { + throw new Error("'MethodDefinitionHasOverload was not overloaded by native module initialization") + } + _MethodDefinitionFunction(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MethodDefinitionFunction was not overloaded by native module initialization") + } + _MethodDefinitionFunctionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'MethodDefinitionFunctionConst was not overloaded by native module initialization") + } + _CreateTSNullKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSNullKeyword was not overloaded by native module initialization") + } + _UpdateTSNullKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSNullKeyword was not overloaded by native module initialization") + } + _CreateTSInterfaceHeritage(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateTSInterfaceHeritage was not overloaded by native module initialization") + } + _UpdateTSInterfaceHeritage(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateTSInterfaceHeritage was not overloaded by native module initialization") + } + _TSInterfaceHeritageExpr(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceHeritageExpr was not overloaded by native module initialization") + } + _TSInterfaceHeritageExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSInterfaceHeritageExprConst was not overloaded by native module initialization") + } + _ExpressionIsGroupedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ExpressionIsGroupedConst was not overloaded by native module initialization") + } + _ExpressionSetGrouped(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'ExpressionSetGrouped was not overloaded by native module initialization") + } + _ExpressionAsLiteralConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExpressionAsLiteralConst was not overloaded by native module initialization") + } + _ExpressionAsLiteral(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExpressionAsLiteral was not overloaded by native module initialization") + } + _ExpressionIsLiteralConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ExpressionIsLiteralConst was not overloaded by native module initialization") + } + _ExpressionIsTypeNodeConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ExpressionIsTypeNodeConst was not overloaded by native module initialization") + } + _ExpressionIsAnnotatedExpressionConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ExpressionIsAnnotatedExpressionConst was not overloaded by native module initialization") + } + _ExpressionAsTypeNode(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExpressionAsTypeNode was not overloaded by native module initialization") + } + _ExpressionAsTypeNodeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExpressionAsTypeNodeConst was not overloaded by native module initialization") + } + _ExpressionAsAnnotatedExpression(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExpressionAsAnnotatedExpression was not overloaded by native module initialization") + } + _ExpressionAsAnnotatedExpressionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ExpressionAsAnnotatedExpressionConst was not overloaded by native module initialization") + } + _ExpressionIsBrokenExpressionConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ExpressionIsBrokenExpressionConst was not overloaded by native module initialization") + } + _ExpressionToStringConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ExpressionToStringConst was not overloaded by native module initialization") + } + _AnnotatedExpressionTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AnnotatedExpressionTypeAnnotationConst was not overloaded by native module initialization") + } + _AnnotatedExpressionSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'AnnotatedExpressionSetTsTypeAnnotation was not overloaded by native module initialization") + } + _MaybeOptionalExpressionIsOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'MaybeOptionalExpressionIsOptionalConst was not overloaded by native module initialization") + } + _MaybeOptionalExpressionClearOptional(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'MaybeOptionalExpressionClearOptional was not overloaded by native module initialization") + } + _CreateSrcDumper(context: KNativePointer, node: KNativePointer): KNativePointer { + throw new Error("'CreateSrcDumper was not overloaded by native module initialization") + } + _SrcDumperAdd(context: KNativePointer, receiver: KNativePointer, str: KStringPtr): void { + throw new Error("'SrcDumperAdd was not overloaded by native module initialization") + } + _SrcDumperAdd1(context: KNativePointer, receiver: KNativePointer, i: KInt): void { + throw new Error("'SrcDumperAdd1 was not overloaded by native module initialization") + } + _SrcDumperAdd2(context: KNativePointer, receiver: KNativePointer, l: KLong): void { + throw new Error("'SrcDumperAdd2 was not overloaded by native module initialization") + } + _SrcDumperAdd3(context: KNativePointer, receiver: KNativePointer, f: KFloat): void { + throw new Error("'SrcDumperAdd3 was not overloaded by native module initialization") + } + _SrcDumperAdd4(context: KNativePointer, receiver: KNativePointer, d: KDouble): void { + throw new Error("'SrcDumperAdd4 was not overloaded by native module initialization") + } + _SrcDumperStrConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'SrcDumperStrConst was not overloaded by native module initialization") + } + _SrcDumperIncrIndent(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'SrcDumperIncrIndent was not overloaded by native module initialization") + } + _SrcDumperDecrIndent(context: KNativePointer, receiver: KNativePointer): void { + throw new Error("'SrcDumperDecrIndent was not overloaded by native module initialization") + } + _SrcDumperEndl(context: KNativePointer, receiver: KNativePointer, num: KUInt): void { + throw new Error("'SrcDumperEndl was not overloaded by native module initialization") + } + _CreateETSClassLiteral(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateETSClassLiteral was not overloaded by native module initialization") + } + _UpdateETSClassLiteral(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateETSClassLiteral was not overloaded by native module initialization") + } + _ETSClassLiteralExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSClassLiteralExprConst was not overloaded by native module initialization") + } + _CreateBreakStatement(context: KNativePointer): KNativePointer { + throw new Error("'CreateBreakStatement was not overloaded by native module initialization") + } + _UpdateBreakStatement(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateBreakStatement was not overloaded by native module initialization") + } + _CreateBreakStatement1(context: KNativePointer, ident: KNativePointer): KNativePointer { + throw new Error("'CreateBreakStatement1 was not overloaded by native module initialization") + } + _UpdateBreakStatement1(context: KNativePointer, original: KNativePointer, ident: KNativePointer): KNativePointer { + throw new Error("'UpdateBreakStatement1 was not overloaded by native module initialization") + } + _BreakStatementIdentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BreakStatementIdentConst was not overloaded by native module initialization") + } + _BreakStatementIdent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BreakStatementIdent was not overloaded by native module initialization") + } + _BreakStatementTargetConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'BreakStatementTargetConst was not overloaded by native module initialization") + } + _BreakStatementSetTarget(context: KNativePointer, receiver: KNativePointer, target: KNativePointer): void { + throw new Error("'BreakStatementSetTarget was not overloaded by native module initialization") + } + _CreateRegExpLiteral(context: KNativePointer, pattern: KStringPtr, flags: KInt, flagsStr: KStringPtr): KNativePointer { + throw new Error("'CreateRegExpLiteral was not overloaded by native module initialization") + } + _UpdateRegExpLiteral(context: KNativePointer, original: KNativePointer, pattern: KStringPtr, flags: KInt, flagsStr: KStringPtr): KNativePointer { + throw new Error("'UpdateRegExpLiteral was not overloaded by native module initialization") + } + _RegExpLiteralPatternConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'RegExpLiteralPatternConst was not overloaded by native module initialization") + } + _RegExpLiteralFlagsConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'RegExpLiteralFlagsConst was not overloaded by native module initialization") + } + _CreateTSMappedType(context: KNativePointer, typeParameter: KNativePointer, typeAnnotation: KNativePointer, readonly_arg: KInt, optional_arg: KInt): KNativePointer { + throw new Error("'CreateTSMappedType was not overloaded by native module initialization") + } + _UpdateTSMappedType(context: KNativePointer, original: KNativePointer, typeParameter: KNativePointer, typeAnnotation: KNativePointer, readonly_arg: KInt, optional_arg: KInt): KNativePointer { + throw new Error("'UpdateTSMappedType was not overloaded by native module initialization") + } + _TSMappedTypeTypeParameter(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMappedTypeTypeParameter was not overloaded by native module initialization") + } + _TSMappedTypeTypeAnnotation(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSMappedTypeTypeAnnotation was not overloaded by native module initialization") + } + _TSMappedTypeReadonly(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'TSMappedTypeReadonly was not overloaded by native module initialization") + } + _TSMappedTypeOptional(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'TSMappedTypeOptional was not overloaded by native module initialization") + } + _CreateTSAnyKeyword(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSAnyKeyword was not overloaded by native module initialization") + } + _UpdateTSAnyKeyword(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSAnyKeyword was not overloaded by native module initialization") + } + _CreateClassDeclaration(context: KNativePointer, def: KNativePointer): KNativePointer { + throw new Error("'CreateClassDeclaration was not overloaded by native module initialization") + } + _UpdateClassDeclaration(context: KNativePointer, original: KNativePointer, def: KNativePointer): KNativePointer { + throw new Error("'UpdateClassDeclaration was not overloaded by native module initialization") + } + _ClassDeclarationDefinition(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDeclarationDefinition was not overloaded by native module initialization") + } + _ClassDeclarationDefinitionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDeclarationDefinitionConst was not overloaded by native module initialization") + } + _ClassDeclarationDecoratorsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ClassDeclarationDecoratorsConst was not overloaded by native module initialization") + } + _CreateTSIndexedAccessType(context: KNativePointer, objectType: KNativePointer, indexType: KNativePointer): KNativePointer { + throw new Error("'CreateTSIndexedAccessType was not overloaded by native module initialization") + } + _UpdateTSIndexedAccessType(context: KNativePointer, original: KNativePointer, objectType: KNativePointer, indexType: KNativePointer): KNativePointer { + throw new Error("'UpdateTSIndexedAccessType was not overloaded by native module initialization") + } + _TSIndexedAccessTypeObjectTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSIndexedAccessTypeObjectTypeConst was not overloaded by native module initialization") + } + _TSIndexedAccessTypeIndexTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSIndexedAccessTypeIndexTypeConst was not overloaded by native module initialization") + } + _CreateTSQualifiedName(context: KNativePointer, left: KNativePointer, right: KNativePointer): KNativePointer { + throw new Error("'CreateTSQualifiedName was not overloaded by native module initialization") + } + _UpdateTSQualifiedName(context: KNativePointer, original: KNativePointer, left: KNativePointer, right: KNativePointer): KNativePointer { + throw new Error("'UpdateTSQualifiedName was not overloaded by native module initialization") + } + _TSQualifiedNameLeftConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSQualifiedNameLeftConst was not overloaded by native module initialization") + } + _TSQualifiedNameLeft(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSQualifiedNameLeft was not overloaded by native module initialization") + } + _TSQualifiedNameRightConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSQualifiedNameRightConst was not overloaded by native module initialization") + } + _TSQualifiedNameRight(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSQualifiedNameRight was not overloaded by native module initialization") + } + _TSQualifiedNameNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'TSQualifiedNameNameConst was not overloaded by native module initialization") + } + _TSQualifiedNameResolveLeftMostQualifiedName(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSQualifiedNameResolveLeftMostQualifiedName was not overloaded by native module initialization") + } + _TSQualifiedNameResolveLeftMostQualifiedNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSQualifiedNameResolveLeftMostQualifiedNameConst was not overloaded by native module initialization") + } + _CreateAwaitExpression(context: KNativePointer, argument: KNativePointer): KNativePointer { + throw new Error("'CreateAwaitExpression was not overloaded by native module initialization") + } + _UpdateAwaitExpression(context: KNativePointer, original: KNativePointer, argument: KNativePointer): KNativePointer { + throw new Error("'UpdateAwaitExpression was not overloaded by native module initialization") + } + _AwaitExpressionArgumentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'AwaitExpressionArgumentConst was not overloaded by native module initialization") + } + _CreateValidationInfo(context: KNativePointer): KNativePointer { + throw new Error("'CreateValidationInfo was not overloaded by native module initialization") + } + _ValidationInfoFailConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ValidationInfoFailConst was not overloaded by native module initialization") + } + _CreateContinueStatement(context: KNativePointer): KNativePointer { + throw new Error("'CreateContinueStatement was not overloaded by native module initialization") + } + _UpdateContinueStatement(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateContinueStatement was not overloaded by native module initialization") + } + _CreateContinueStatement1(context: KNativePointer, ident: KNativePointer): KNativePointer { + throw new Error("'CreateContinueStatement1 was not overloaded by native module initialization") + } + _UpdateContinueStatement1(context: KNativePointer, original: KNativePointer, ident: KNativePointer): KNativePointer { + throw new Error("'UpdateContinueStatement1 was not overloaded by native module initialization") + } + _ContinueStatementIdentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ContinueStatementIdentConst was not overloaded by native module initialization") + } + _ContinueStatementIdent(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ContinueStatementIdent was not overloaded by native module initialization") + } + _ContinueStatementTargetConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ContinueStatementTargetConst was not overloaded by native module initialization") + } + _ContinueStatementSetTarget(context: KNativePointer, receiver: KNativePointer, target: KNativePointer): void { + throw new Error("'ContinueStatementSetTarget was not overloaded by native module initialization") + } + _CreateETSNewMultiDimArrayInstanceExpression(context: KNativePointer, typeReference: KNativePointer, dimensions: BigUint64Array, dimensionsSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateETSNewMultiDimArrayInstanceExpression was not overloaded by native module initialization") + } + _UpdateETSNewMultiDimArrayInstanceExpression(context: KNativePointer, original: KNativePointer, typeReference: KNativePointer, dimensions: BigUint64Array, dimensionsSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateETSNewMultiDimArrayInstanceExpression was not overloaded by native module initialization") + } + _CreateETSNewMultiDimArrayInstanceExpression1(context: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'CreateETSNewMultiDimArrayInstanceExpression1 was not overloaded by native module initialization") + } + _UpdateETSNewMultiDimArrayInstanceExpression1(context: KNativePointer, original: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'UpdateETSNewMultiDimArrayInstanceExpression1 was not overloaded by native module initialization") + } + _ETSNewMultiDimArrayInstanceExpressionTypeReference(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewMultiDimArrayInstanceExpressionTypeReference was not overloaded by native module initialization") + } + _ETSNewMultiDimArrayInstanceExpressionTypeReferenceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewMultiDimArrayInstanceExpressionTypeReferenceConst was not overloaded by native module initialization") + } + _ETSNewMultiDimArrayInstanceExpressionDimensions(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewMultiDimArrayInstanceExpressionDimensions was not overloaded by native module initialization") + } + _ETSNewMultiDimArrayInstanceExpressionDimensionsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewMultiDimArrayInstanceExpressionDimensionsConst was not overloaded by native module initialization") + } + _CreateTSNamedTupleMember(context: KNativePointer, label: KNativePointer, elementType: KNativePointer, optional_arg: KBoolean): KNativePointer { + throw new Error("'CreateTSNamedTupleMember was not overloaded by native module initialization") + } + _UpdateTSNamedTupleMember(context: KNativePointer, original: KNativePointer, label: KNativePointer, elementType: KNativePointer, optional_arg: KBoolean): KNativePointer { + throw new Error("'UpdateTSNamedTupleMember was not overloaded by native module initialization") + } + _TSNamedTupleMemberLabelConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSNamedTupleMemberLabelConst was not overloaded by native module initialization") + } + _TSNamedTupleMemberElementType(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSNamedTupleMemberElementType was not overloaded by native module initialization") + } + _TSNamedTupleMemberElementTypeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSNamedTupleMemberElementTypeConst was not overloaded by native module initialization") + } + _TSNamedTupleMemberIsOptionalConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSNamedTupleMemberIsOptionalConst was not overloaded by native module initialization") + } + _CreateImportExpression(context: KNativePointer, source: KNativePointer): KNativePointer { + throw new Error("'CreateImportExpression was not overloaded by native module initialization") + } + _UpdateImportExpression(context: KNativePointer, original: KNativePointer, source: KNativePointer): KNativePointer { + throw new Error("'UpdateImportExpression was not overloaded by native module initialization") + } + _ImportExpressionSource(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportExpressionSource was not overloaded by native module initialization") + } + _ImportExpressionSourceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ImportExpressionSourceConst was not overloaded by native module initialization") + } + _CreateAstDumper(context: KNativePointer, node: KNativePointer, sourceCode: KStringPtr): KNativePointer { + throw new Error("'CreateAstDumper was not overloaded by native module initialization") + } + _AstDumperModifierToString(context: KNativePointer, receiver: KNativePointer, flags: KInt): KStringPtr { + throw new Error("'AstDumperModifierToString was not overloaded by native module initialization") + } + _AstDumperTypeOperatorToString(context: KNativePointer, receiver: KNativePointer, operatorType: KInt): KStringPtr { + throw new Error("'AstDumperTypeOperatorToString was not overloaded by native module initialization") + } + _AstDumperStrConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'AstDumperStrConst was not overloaded by native module initialization") + } + _CreateETSNullTypeIr(context: KNativePointer): KNativePointer { + throw new Error("'CreateETSNullTypeIr was not overloaded by native module initialization") + } + _UpdateETSNullTypeIr(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateETSNullTypeIr was not overloaded by native module initialization") + } + _CreateETSUndefinedTypeIr(context: KNativePointer): KNativePointer { + throw new Error("'CreateETSUndefinedTypeIr was not overloaded by native module initialization") + } + _UpdateETSUndefinedTypeIr(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateETSUndefinedTypeIr was not overloaded by native module initialization") + } + _CreateTypeofExpression(context: KNativePointer, argument: KNativePointer): KNativePointer { + throw new Error("'CreateTypeofExpression was not overloaded by native module initialization") + } + _UpdateTypeofExpression(context: KNativePointer, original: KNativePointer, argument: KNativePointer): KNativePointer { + throw new Error("'UpdateTypeofExpression was not overloaded by native module initialization") + } + _TypeofExpressionArgumentConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TypeofExpressionArgumentConst was not overloaded by native module initialization") + } + _CreateTSEnumMember(context: KNativePointer, key: KNativePointer, init: KNativePointer): KNativePointer { + throw new Error("'CreateTSEnumMember was not overloaded by native module initialization") + } + _UpdateTSEnumMember(context: KNativePointer, original: KNativePointer, key: KNativePointer, init: KNativePointer): KNativePointer { + throw new Error("'UpdateTSEnumMember was not overloaded by native module initialization") + } + _CreateTSEnumMember1(context: KNativePointer, key: KNativePointer, init: KNativePointer, isGenerated: KBoolean): KNativePointer { + throw new Error("'CreateTSEnumMember1 was not overloaded by native module initialization") + } + _UpdateTSEnumMember1(context: KNativePointer, original: KNativePointer, key: KNativePointer, init: KNativePointer, isGenerated: KBoolean): KNativePointer { + throw new Error("'UpdateTSEnumMember1 was not overloaded by native module initialization") + } + _TSEnumMemberKeyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumMemberKeyConst was not overloaded by native module initialization") + } + _TSEnumMemberKey(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumMemberKey was not overloaded by native module initialization") + } + _TSEnumMemberInitConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumMemberInitConst was not overloaded by native module initialization") + } + _TSEnumMemberInit(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSEnumMemberInit was not overloaded by native module initialization") + } + _TSEnumMemberIsGeneratedConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSEnumMemberIsGeneratedConst was not overloaded by native module initialization") + } + _TSEnumMemberNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'TSEnumMemberNameConst was not overloaded by native module initialization") + } + _CreateSwitchStatement(context: KNativePointer, discriminant: KNativePointer, cases: BigUint64Array, casesSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateSwitchStatement was not overloaded by native module initialization") + } + _UpdateSwitchStatement(context: KNativePointer, original: KNativePointer, discriminant: KNativePointer, cases: BigUint64Array, casesSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateSwitchStatement was not overloaded by native module initialization") + } + _SwitchStatementDiscriminantConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SwitchStatementDiscriminantConst was not overloaded by native module initialization") + } + _SwitchStatementDiscriminant(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SwitchStatementDiscriminant was not overloaded by native module initialization") + } + _SwitchStatementCasesConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SwitchStatementCasesConst was not overloaded by native module initialization") + } + _SwitchStatementCases(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SwitchStatementCases was not overloaded by native module initialization") + } + _CreateDoWhileStatement(context: KNativePointer, body: KNativePointer, test: KNativePointer): KNativePointer { + throw new Error("'CreateDoWhileStatement was not overloaded by native module initialization") + } + _UpdateDoWhileStatement(context: KNativePointer, original: KNativePointer, body: KNativePointer, test: KNativePointer): KNativePointer { + throw new Error("'UpdateDoWhileStatement was not overloaded by native module initialization") + } + _DoWhileStatementBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'DoWhileStatementBodyConst was not overloaded by native module initialization") + } + _DoWhileStatementBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'DoWhileStatementBody was not overloaded by native module initialization") + } + _DoWhileStatementTestConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'DoWhileStatementTestConst was not overloaded by native module initialization") + } + _DoWhileStatementTest(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'DoWhileStatementTest was not overloaded by native module initialization") + } + _CreateCatchClause(context: KNativePointer, param: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'CreateCatchClause was not overloaded by native module initialization") + } + _UpdateCatchClause(context: KNativePointer, original: KNativePointer, param: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'UpdateCatchClause was not overloaded by native module initialization") + } + _CatchClauseParam(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CatchClauseParam was not overloaded by native module initialization") + } + _CatchClauseParamConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CatchClauseParamConst was not overloaded by native module initialization") + } + _CatchClauseBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CatchClauseBody was not overloaded by native module initialization") + } + _CatchClauseBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'CatchClauseBodyConst was not overloaded by native module initialization") + } + _CatchClauseIsDefaultCatchClauseConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'CatchClauseIsDefaultCatchClauseConst was not overloaded by native module initialization") + } + _CreateSequenceExpression(context: KNativePointer, sequence_arg: BigUint64Array, sequence_argSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateSequenceExpression was not overloaded by native module initialization") + } + _UpdateSequenceExpression(context: KNativePointer, original: KNativePointer, sequence_arg: BigUint64Array, sequence_argSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateSequenceExpression was not overloaded by native module initialization") + } + _SequenceExpressionSequenceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SequenceExpressionSequenceConst was not overloaded by native module initialization") + } + _SequenceExpressionSequence(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'SequenceExpressionSequence was not overloaded by native module initialization") + } + _CreateArrowFunctionExpression(context: KNativePointer, func: KNativePointer): KNativePointer { + throw new Error("'CreateArrowFunctionExpression was not overloaded by native module initialization") + } + _UpdateArrowFunctionExpression(context: KNativePointer, original: KNativePointer, func: KNativePointer): KNativePointer { + throw new Error("'UpdateArrowFunctionExpression was not overloaded by native module initialization") + } + _CreateArrowFunctionExpression1(context: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'CreateArrowFunctionExpression1 was not overloaded by native module initialization") + } + _UpdateArrowFunctionExpression1(context: KNativePointer, original: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'UpdateArrowFunctionExpression1 was not overloaded by native module initialization") + } + _ArrowFunctionExpressionFunctionConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrowFunctionExpressionFunctionConst was not overloaded by native module initialization") + } + _ArrowFunctionExpressionFunction(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrowFunctionExpressionFunction was not overloaded by native module initialization") + } + _ArrowFunctionExpressionCreateTypeAnnotation(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrowFunctionExpressionCreateTypeAnnotation was not overloaded by native module initialization") + } + _ArrowFunctionExpressionAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrowFunctionExpressionAnnotations was not overloaded by native module initialization") + } + _ArrowFunctionExpressionAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ArrowFunctionExpressionAnnotationsConst was not overloaded by native module initialization") + } + _ArrowFunctionExpressionSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'ArrowFunctionExpressionSetAnnotations was not overloaded by native module initialization") + } + _CreateOmittedExpression(context: KNativePointer): KNativePointer { + throw new Error("'CreateOmittedExpression was not overloaded by native module initialization") + } + _UpdateOmittedExpression(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateOmittedExpression was not overloaded by native module initialization") + } + _CreateETSNewClassInstanceExpression(context: KNativePointer, typeReference: KNativePointer, _arguments: BigUint64Array, _argumentsSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateETSNewClassInstanceExpression was not overloaded by native module initialization") + } + _UpdateETSNewClassInstanceExpression(context: KNativePointer, original: KNativePointer, typeReference: KNativePointer, _arguments: BigUint64Array, _argumentsSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateETSNewClassInstanceExpression was not overloaded by native module initialization") + } + _CreateETSNewClassInstanceExpression1(context: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'CreateETSNewClassInstanceExpression1 was not overloaded by native module initialization") + } + _UpdateETSNewClassInstanceExpression1(context: KNativePointer, original: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'UpdateETSNewClassInstanceExpression1 was not overloaded by native module initialization") + } + _ETSNewClassInstanceExpressionGetTypeRefConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewClassInstanceExpressionGetTypeRefConst was not overloaded by native module initialization") + } + _ETSNewClassInstanceExpressionGetArguments(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewClassInstanceExpressionGetArguments was not overloaded by native module initialization") + } + _ETSNewClassInstanceExpressionGetArgumentsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSNewClassInstanceExpressionGetArgumentsConst was not overloaded by native module initialization") + } + _ETSNewClassInstanceExpressionSetArguments(context: KNativePointer, receiver: KNativePointer, _arguments: BigUint64Array, _argumentsSequenceLength: KUInt): void { + throw new Error("'ETSNewClassInstanceExpressionSetArguments was not overloaded by native module initialization") + } + _ETSNewClassInstanceExpressionAddToArgumentsFront(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'ETSNewClassInstanceExpressionAddToArgumentsFront was not overloaded by native module initialization") + } + _CreateTSAsExpression(context: KNativePointer, expression: KNativePointer, typeAnnotation: KNativePointer, isConst: KBoolean): KNativePointer { + throw new Error("'CreateTSAsExpression was not overloaded by native module initialization") + } + _UpdateTSAsExpression(context: KNativePointer, original: KNativePointer, expression: KNativePointer, typeAnnotation: KNativePointer, isConst: KBoolean): KNativePointer { + throw new Error("'UpdateTSAsExpression was not overloaded by native module initialization") + } + _TSAsExpressionExprConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSAsExpressionExprConst was not overloaded by native module initialization") + } + _TSAsExpressionExpr(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSAsExpressionExpr was not overloaded by native module initialization") + } + _TSAsExpressionSetExpr(context: KNativePointer, receiver: KNativePointer, expr: KNativePointer): void { + throw new Error("'TSAsExpressionSetExpr was not overloaded by native module initialization") + } + _TSAsExpressionIsConstConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSAsExpressionIsConstConst was not overloaded by native module initialization") + } + _TSAsExpressionSetUncheckedCast(context: KNativePointer, receiver: KNativePointer, isUncheckedCast: KBoolean): void { + throw new Error("'TSAsExpressionSetUncheckedCast was not overloaded by native module initialization") + } + _TSAsExpressionTypeAnnotationConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSAsExpressionTypeAnnotationConst was not overloaded by native module initialization") + } + _TSAsExpressionSetTsTypeAnnotation(context: KNativePointer, receiver: KNativePointer, typeAnnotation: KNativePointer): void { + throw new Error("'TSAsExpressionSetTsTypeAnnotation was not overloaded by native module initialization") + } + _CreateForUpdateStatement(context: KNativePointer, init: KNativePointer, test: KNativePointer, update: KNativePointer, body: KNativePointer): KNativePointer { + throw new Error("'CreateForUpdateStatement was not overloaded by native module initialization") + } + _ForUpdateStatementInit(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForUpdateStatementInit was not overloaded by native module initialization") + } + _ForUpdateStatementInitConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForUpdateStatementInitConst was not overloaded by native module initialization") + } + _ForUpdateStatementTest(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForUpdateStatementTest was not overloaded by native module initialization") + } + _ForUpdateStatementTestConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForUpdateStatementTestConst was not overloaded by native module initialization") + } + _ForUpdateStatementUpdateConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForUpdateStatementUpdateConst was not overloaded by native module initialization") + } + _ForUpdateStatementBody(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForUpdateStatementBody was not overloaded by native module initialization") + } + _ForUpdateStatementBodyConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ForUpdateStatementBodyConst was not overloaded by native module initialization") + } + _CreateETSTypeReferencePart(context: KNativePointer, name: KNativePointer, typeParams: KNativePointer, prev: KNativePointer): KNativePointer { + throw new Error("'CreateETSTypeReferencePart was not overloaded by native module initialization") + } + _UpdateETSTypeReferencePart(context: KNativePointer, original: KNativePointer, name: KNativePointer, typeParams: KNativePointer, prev: KNativePointer): KNativePointer { + throw new Error("'UpdateETSTypeReferencePart was not overloaded by native module initialization") + } + _CreateETSTypeReferencePart1(context: KNativePointer, name: KNativePointer): KNativePointer { + throw new Error("'CreateETSTypeReferencePart1 was not overloaded by native module initialization") + } + _UpdateETSTypeReferencePart1(context: KNativePointer, original: KNativePointer, name: KNativePointer): KNativePointer { + throw new Error("'UpdateETSTypeReferencePart1 was not overloaded by native module initialization") + } + _ETSTypeReferencePartPrevious(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTypeReferencePartPrevious was not overloaded by native module initialization") + } + _ETSTypeReferencePartPreviousConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTypeReferencePartPreviousConst was not overloaded by native module initialization") + } + _ETSTypeReferencePartName(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTypeReferencePartName was not overloaded by native module initialization") + } + _ETSTypeReferencePartTypeParams(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTypeReferencePartTypeParams was not overloaded by native module initialization") + } + _ETSTypeReferencePartNameConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSTypeReferencePartNameConst was not overloaded by native module initialization") + } + _ETSReExportDeclarationGetETSImportDeclarationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSReExportDeclarationGetETSImportDeclarationsConst was not overloaded by native module initialization") + } + _ETSReExportDeclarationGetETSImportDeclarations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSReExportDeclarationGetETSImportDeclarations was not overloaded by native module initialization") + } + _ETSReExportDeclarationGetProgramPathConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { + throw new Error("'ETSReExportDeclarationGetProgramPathConst was not overloaded by native module initialization") + } + _CreateETSPrimitiveType(context: KNativePointer, type: KInt): KNativePointer { + throw new Error("'CreateETSPrimitiveType was not overloaded by native module initialization") + } + _UpdateETSPrimitiveType(context: KNativePointer, original: KNativePointer, type: KInt): KNativePointer { + throw new Error("'UpdateETSPrimitiveType was not overloaded by native module initialization") + } + _ETSPrimitiveTypeGetPrimitiveTypeConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'ETSPrimitiveTypeGetPrimitiveTypeConst was not overloaded by native module initialization") + } + _TypeNodeAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TypeNodeAnnotations was not overloaded by native module initialization") + } + _TypeNodeAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TypeNodeAnnotationsConst was not overloaded by native module initialization") + } + _TypeNodeSetAnnotations(context: KNativePointer, receiver: KNativePointer, annotations: BigUint64Array, annotationsSequenceLength: KUInt): void { + throw new Error("'TypeNodeSetAnnotations was not overloaded by native module initialization") + } + _CreateNewExpression(context: KNativePointer, callee: KNativePointer, _arguments: BigUint64Array, _argumentsSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateNewExpression was not overloaded by native module initialization") + } + _UpdateNewExpression(context: KNativePointer, original: KNativePointer, callee: KNativePointer, _arguments: BigUint64Array, _argumentsSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateNewExpression was not overloaded by native module initialization") + } + _NewExpressionCalleeConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'NewExpressionCalleeConst was not overloaded by native module initialization") + } + _NewExpressionArgumentsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'NewExpressionArgumentsConst was not overloaded by native module initialization") + } + _CreateTSParameterProperty(context: KNativePointer, accessibility: KInt, parameter: KNativePointer, readonly_arg: KBoolean, isStatic: KBoolean, isExport: KBoolean): KNativePointer { + throw new Error("'CreateTSParameterProperty was not overloaded by native module initialization") + } + _UpdateTSParameterProperty(context: KNativePointer, original: KNativePointer, accessibility: KInt, parameter: KNativePointer, readonly_arg: KBoolean, isStatic: KBoolean, isExport: KBoolean): KNativePointer { + throw new Error("'UpdateTSParameterProperty was not overloaded by native module initialization") + } + _TSParameterPropertyAccessibilityConst(context: KNativePointer, receiver: KNativePointer): KInt { + throw new Error("'TSParameterPropertyAccessibilityConst was not overloaded by native module initialization") + } + _TSParameterPropertyReadonlyConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSParameterPropertyReadonlyConst was not overloaded by native module initialization") + } + _TSParameterPropertyIsStaticConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSParameterPropertyIsStaticConst was not overloaded by native module initialization") + } + _TSParameterPropertyIsExportConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'TSParameterPropertyIsExportConst was not overloaded by native module initialization") + } + _TSParameterPropertyParameterConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'TSParameterPropertyParameterConst was not overloaded by native module initialization") + } + _CreateETSWildcardType(context: KNativePointer, typeReference: KNativePointer, flags: KInt): KNativePointer { + throw new Error("'CreateETSWildcardType was not overloaded by native module initialization") + } + _UpdateETSWildcardType(context: KNativePointer, original: KNativePointer, typeReference: KNativePointer, flags: KInt): KNativePointer { + throw new Error("'UpdateETSWildcardType was not overloaded by native module initialization") + } + _ETSWildcardTypeTypeReference(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSWildcardTypeTypeReference was not overloaded by native module initialization") + } + _ETSWildcardTypeTypeReferenceConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSWildcardTypeTypeReferenceConst was not overloaded by native module initialization") + } + _CreateTSThisType(context: KNativePointer): KNativePointer { + throw new Error("'CreateTSThisType was not overloaded by native module initialization") + } + _UpdateTSThisType(context: KNativePointer, original: KNativePointer): KNativePointer { + throw new Error("'UpdateTSThisType was not overloaded by native module initialization") + } + _CreateInterfaceDecl(context: KNativePointer, name: KStringPtr): KNativePointer { + throw new Error("'CreateInterfaceDecl was not overloaded by native module initialization") + } + _CreateInterfaceDecl1(context: KNativePointer, name: KStringPtr, declNode: KNativePointer): KNativePointer { + throw new Error("'CreateInterfaceDecl1 was not overloaded by native module initialization") + } + _CreateFunctionDecl(context: KNativePointer, name: KStringPtr, node: KNativePointer): KNativePointer { + throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + } +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/index.ts b/koala-wrapper/src/generated/index.ts new file mode 100644 index 000000000..4b9ae3fc2 --- /dev/null +++ b/koala-wrapper/src/generated/index.ts @@ -0,0 +1,192 @@ +/* + * 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. + */ + +export * from "./peers/TypedAstNode" +export * from "./peers/AnnotatedAstNode" +export * from "./peers/TypedStatement" +export * from "./peers/AnnotatedStatement" +export * from "./peers/LabelledStatement" +export * from "./peers/ThrowStatement" +export * from "./peers/ClassProperty" +export * from "./peers/TSVoidKeyword" +export * from "./peers/ETSFunctionType" +export * from "./peers/TSTypeOperator" +export * from "./peers/IfStatement" +export * from "./peers/TSConstructorType" +export * from "./peers/Decorator" +export * from "./peers/TSEnumDeclaration" +export * from "./peers/TSNeverKeyword" +export * from "./peers/ImportDefaultSpecifier" +export * from "./peers/ObjectExpression" +export * from "./peers/ImportSpecifier" +export * from "./peers/ConditionalExpression" +export * from "./peers/CallExpression" +export * from "./peers/BigIntLiteral" +export * from "./peers/ClassElement" +export * from "./peers/TSImportType" +export * from "./peers/TaggedTemplateExpression" +export * from "./peers/FunctionDeclaration" +export * from "./peers/ETSTypeReference" +export * from "./peers/TSTypeReference" +export * from "./peers/ImportSource" +export * from "./peers/NamedType" +export * from "./peers/NumberLiteral" +export * from "./peers/TSFunctionType" +export * from "./peers/TemplateElement" +export * from "./peers/TSInterfaceDeclaration" +export * from "./peers/VariableDeclaration" +export * from "./peers/UndefinedLiteral" +export * from "./peers/MemberExpression" +export * from "./peers/TSClassImplements" +export * from "./peers/TSObjectKeyword" +export * from "./peers/ETSUnionType" +export * from "./peers/TSPropertySignature" +export * from "./peers/TSConditionalType" +export * from "./peers/TSLiteralType" +export * from "./peers/TSTypeAliasDeclaration" +export * from "./peers/DebuggerStatement" +export * from "./peers/ReturnStatement" +export * from "./peers/ExportDefaultDeclaration" +export * from "./peers/ScriptFunction" +export * from "./peers/ClassDefinition" +export * from "./peers/ArrayExpression" +export * from "./peers/TSInterfaceBody" +export * from "./peers/TSTypeQuery" +export * from "./peers/TSBigintKeyword" +export * from "./peers/Property" +export * from "./peers/VariableDeclarator" +export * from "./peers/StringLiteral" +export * from "./peers/TSTypeAssertion" +export * from "./peers/TSExternalModuleReference" +export * from "./peers/TSUndefinedKeyword" +export * from "./peers/ETSTuple" +export * from "./peers/TryStatement" +export * from "./peers/UnaryExpression" +export * from "./peers/ForInStatement" +export * from "./peers/ThisExpression" +export * from "./peers/TSMethodSignature" +export * from "./peers/BinaryExpression" +export * from "./peers/SuperExpression" +export * from "./peers/AssertStatement" +export * from "./peers/TSStringKeyword" +export * from "./peers/AssignmentExpression" +export * from "./peers/ExpressionStatement" +export * from "./peers/ETSModule" +export * from "./peers/MetaProperty" +export * from "./peers/TSArrayType" +export * from "./peers/TSSignatureDeclaration" +export * from "./peers/ExportAllDeclaration" +export * from "./peers/ExportSpecifier" +export * from "./peers/TSTupleType" +export * from "./peers/FunctionExpression" +export * from "./peers/TSIndexSignature" +export * from "./peers/TSModuleDeclaration" +export * from "./peers/ImportDeclaration" +export * from "./peers/TSParenthesizedType" +export * from "./peers/Literal" +export * from "./peers/CharLiteral" +export * from "./peers/ETSPackageDeclaration" +export * from "./peers/ETSImportDeclaration" +export * from "./peers/ETSStructDeclaration" +export * from "./peers/TSModuleBlock" +export * from "./peers/ETSNewArrayInstanceExpression" +export * from "./peers/LoopStatement" +export * from "./peers/AnnotationDeclaration" +export * from "./peers/AnnotationUsage" +export * from "./peers/EmptyStatement" +export * from "./peers/ETSLaunchExpression" +export * from "./peers/WhileStatement" +export * from "./peers/FunctionSignature" +export * from "./peers/ChainExpression" +export * from "./peers/TSIntersectionType" +export * from "./peers/UpdateExpression" +export * from "./peers/BlockExpression" +export * from "./peers/TSTypeLiteral" +export * from "./peers/TSTypeParameter" +export * from "./peers/TSBooleanKeyword" +export * from "./peers/SpreadElement" +export * from "./peers/TSTypePredicate" +export * from "./peers/ImportNamespaceSpecifier" +export * from "./peers/ExportNamedDeclaration" +export * from "./peers/ETSParameterExpression" +export * from "./peers/TSTypeParameterInstantiation" +export * from "./peers/NullLiteral" +export * from "./peers/TSInferType" +export * from "./peers/SwitchCaseStatement" +export * from "./peers/YieldExpression" +export * from "./peers/TSImportEqualsDeclaration" +export * from "./peers/BooleanLiteral" +export * from "./peers/TSNumberKeyword" +export * from "./peers/ClassStaticBlock" +export * from "./peers/TSNonNullExpression" +export * from "./peers/PrefixAssertionExpression" +export * from "./peers/ClassExpression" +export * from "./peers/ForOfStatement" +export * from "./peers/TemplateLiteral" +export * from "./peers/TSUnionType" +export * from "./peers/TSUnknownKeyword" +export * from "./peers/Identifier" +export * from "./peers/OpaqueTypeNode" +export * from "./peers/BlockStatement" +export * from "./peers/Statement" +export * from "./peers/DirectEvalExpression" +export * from "./peers/TSTypeParameterDeclaration" +export * from "./peers/MethodDefinition" +export * from "./peers/TSNullKeyword" +export * from "./peers/TSInterfaceHeritage" +export * from "./peers/Expression" +export * from "./peers/AnnotatedExpression" +export * from "./peers/MaybeOptionalExpression" +export * from "./peers/SrcDumper" +export * from "./peers/ETSClassLiteral" +export * from "./peers/BreakStatement" +export * from "./peers/RegExpLiteral" +export * from "./peers/TSMappedType" +export * from "./peers/TSAnyKeyword" +export * from "./peers/ClassDeclaration" +export * from "./peers/TSIndexedAccessType" +export * from "./peers/TSQualifiedName" +export * from "./peers/AwaitExpression" +export * from "./peers/ValidationInfo" +export * from "./peers/ContinueStatement" +export * from "./peers/ETSNewMultiDimArrayInstanceExpression" +export * from "./peers/TSNamedTupleMember" +export * from "./peers/ImportExpression" +export * from "./peers/AstDumper" +export * from "./peers/ETSNullType" +export * from "./peers/ETSUndefinedType" +export * from "./peers/TypeofExpression" +export * from "./peers/TSEnumMember" +export * from "./peers/SwitchStatement" +export * from "./peers/DoWhileStatement" +export * from "./peers/CatchClause" +export * from "./peers/SequenceExpression" +export * from "./peers/ArrowFunctionExpression" +export * from "./peers/OmittedExpression" +export * from "./peers/ETSNewClassInstanceExpression" +export * from "./peers/TSAsExpression" +export * from "./peers/ForUpdateStatement" +export * from "./peers/ETSTypeReferencePart" +export * from "./peers/ETSReExportDeclaration" +export * from "./peers/ETSPrimitiveType" +export * from "./peers/TypeNode" +export * from "./peers/NewExpression" +export * from "./peers/TSParameterProperty" +export * from "./peers/ETSWildcardType" +export * from "./peers/TSThisType" +export * from "./peers/ETSDynamicFunctionType" +export * from "./peers/InterfaceDecl" +export * from "./peers/FunctionDecl" +export * from "./peers/Context" \ No newline at end of file diff --git a/koala-wrapper/src/generated/node-map.ts b/koala-wrapper/src/generated/node-map.ts new file mode 100644 index 000000000..c8d894039 --- /dev/null +++ b/koala-wrapper/src/generated/node-map.ts @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + unpackNonNullableNode, + Es2pandaMemberExpressionKind, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer +} from "../reexport-for-generated" + +import * as peers from "./index" + +export const nodes = new Map([ + [44, peers.LabelledStatement], + [146, peers.ThrowStatement], + [17, peers.ClassProperty], + [94, peers.TSVoidKeyword], + [66, peers.ETSFunctionType], + [117, peers.TSTypeOperator], + [38, peers.IfStatement], + [126, peers.TSConstructorType], + [22, peers.Decorator], + [87, peers.TSEnumDeclaration], + [99, peers.TSNeverKeyword], + [41, peers.ImportDefaultSpecifier], + [43, peers.ImportSpecifier], + [19, peers.ConditionalExpression], + [10, peers.CallExpression], + [5, peers.BigIntLiteral], + [112, peers.TSImportType], + [141, peers.TaggedTemplateExpression], + [34, peers.FunctionDeclaration], + [71, peers.ETSTypeReference], + [128, peers.TSTypeReference], + [48, peers.NamedType], + [52, peers.NumberLiteral], + [125, peers.TSFunctionType], + [142, peers.TemplateElement], + [131, peers.TSInterfaceDeclaration], + [150, peers.VariableDeclaration], + [51, peers.UndefinedLiteral], + [45, peers.MemberExpression], + [139, peers.TSClassImplements], + [97, peers.TSObjectKeyword], + [73, peers.ETSUnionType], + [105, peers.TSPropertySignature], + [111, peers.TSConditionalType], + [109, peers.TSLiteralType], + [127, peers.TSTypeAliasDeclaration], + [21, peers.DebuggerStatement], + [58, peers.ReturnStatement], + [27, peers.ExportDefaultDeclaration], + [59, peers.ScriptFunction], + [14, peers.ClassDefinition], + [132, peers.TSInterfaceBody], + [137, peers.TSTypeQuery], + [98, peers.TSBigintKeyword], + [55, peers.Property], + [151, peers.VariableDeclarator], + [61, peers.StringLiteral], + [140, peers.TSTypeAssertion], + [89, peers.TSExternalModuleReference], + [95, peers.TSUndefinedKeyword], + [81, peers.ETSTuple], + [147, peers.TryStatement], + [148, peers.UnaryExpression], + [31, peers.ForInStatement], + [144, peers.ThisExpression], + [106, peers.TSMethodSignature], + [6, peers.BinaryExpression], + [83, peers.SuperExpression], + [3, peers.AssertStatement], + [92, peers.TSStringKeyword], + [30, peers.ExpressionStatement], + [82, peers.ETSModule], + [46, peers.MetaProperty], + [102, peers.TSArrayType], + [107, peers.TSSignatureDeclaration], + [26, peers.ExportAllDeclaration], + [29, peers.ExportSpecifier], + [134, peers.TSTupleType], + [35, peers.FunctionExpression], + [136, peers.TSIndexSignature], + [123, peers.TSModuleDeclaration], + [39, peers.ImportDeclaration], + [108, peers.TSParenthesizedType], + [13, peers.CharLiteral], + [69, peers.ETSPackageDeclaration], + [79, peers.ETSImportDeclaration], + [84, peers.ETSStructDeclaration], + [115, peers.TSModuleBlock], + [76, peers.ETSNewArrayInstanceExpression], + [1, peers.AnnotationDeclaration], + [2, peers.AnnotationUsage], + [25, peers.EmptyStatement], + [75, peers.ETSLaunchExpression], + [152, peers.WhileStatement], + [12, peers.ChainExpression], + [113, peers.TSIntersectionType], + [149, peers.UpdateExpression], + [155, peers.BlockExpression], + [104, peers.TSTypeLiteral], + [118, peers.TSTypeParameter], + [93, peers.TSBooleanKeyword], + [121, peers.TSTypePredicate], + [42, peers.ImportNamespaceSpecifier], + [28, peers.ExportNamedDeclaration], + [80, peers.ETSParameterExpression], + [120, peers.TSTypeParameterInstantiation], + [50, peers.NullLiteral], + [110, peers.TSInferType], + [85, peers.SwitchCaseStatement], + [153, peers.YieldExpression], + [124, peers.TSImportEqualsDeclaration], + [8, peers.BooleanLiteral], + [90, peers.TSNumberKeyword], + [18, peers.ClassStaticBlock], + [100, peers.TSNonNullExpression], + [54, peers.PrefixAssertionExpression], + [16, peers.ClassExpression], + [32, peers.ForOfStatement], + [143, peers.TemplateLiteral], + [103, peers.TSUnionType], + [96, peers.TSUnknownKeyword], + [36, peers.Identifier], + [154, peers.OpaqueTypeNode], + [7, peers.BlockStatement], + [23, peers.DirectEvalExpression], + [119, peers.TSTypeParameterDeclaration], + [47, peers.MethodDefinition], + [101, peers.TSNullKeyword], + [133, peers.TSInterfaceHeritage], + [70, peers.ETSClassLiteral], + [9, peers.BreakStatement], + [56, peers.RegExpLiteral], + [114, peers.TSMappedType], + [91, peers.TSAnyKeyword], + [15, peers.ClassDeclaration], + [130, peers.TSIndexedAccessType], + [129, peers.TSQualifiedName], + [4, peers.AwaitExpression], + [20, peers.ContinueStatement], + [77, peers.ETSNewMultiDimArrayInstanceExpression], + [135, peers.TSNamedTupleMember], + [40, peers.ImportExpression], + [62, peers.ETSNullType], + [63, peers.ETSUndefinedType], + [145, peers.TypeofExpression], + [88, peers.TSEnumMember], + [86, peers.SwitchStatement], + [24, peers.DoWhileStatement], + [11, peers.CatchClause], + [60, peers.SequenceExpression], + [0, peers.ArrowFunctionExpression], + [53, peers.OmittedExpression], + [78, peers.ETSNewClassInstanceExpression], + [138, peers.TSAsExpression], + [33, peers.ForUpdateStatement], + [72, peers.ETSTypeReferencePart], + [57, peers.ETSReExportDeclaration], + [68, peers.ETSPrimitiveType], + [49, peers.NewExpression], + [122, peers.TSParameterProperty], + [67, peers.ETSWildcardType], + [116, peers.TSThisType], +]) \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AnnotatedAstNode.ts b/koala-wrapper/src/generated/peers/AnnotatedAstNode.ts new file mode 100644 index 000000000..f1199de4d --- /dev/null +++ b/koala-wrapper/src/generated/peers/AnnotatedAstNode.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +export class AnnotatedAstNode extends AstNode { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isAnnotatedAstNode(node: AstNode): node is AnnotatedAstNode { + return node instanceof AnnotatedAstNode +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AnnotatedExpression.ts b/koala-wrapper/src/generated/peers/AnnotatedExpression.ts new file mode 100644 index 000000000..2a5924eb9 --- /dev/null +++ b/koala-wrapper/src/generated/peers/AnnotatedExpression.ts @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class AnnotatedExpression extends Expression { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._AnnotatedExpressionTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._AnnotatedExpressionSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } +} +export function isAnnotatedExpression(node: AstNode): node is AnnotatedExpression { + return node instanceof AnnotatedExpression +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AnnotatedStatement.ts b/koala-wrapper/src/generated/peers/AnnotatedStatement.ts new file mode 100644 index 000000000..64f91f5cf --- /dev/null +++ b/koala-wrapper/src/generated/peers/AnnotatedStatement.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +export class AnnotatedStatement extends Statement { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isAnnotatedStatement(node: AstNode): node is AnnotatedStatement { + return node instanceof AnnotatedStatement +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AnnotationDeclaration.ts b/koala-wrapper/src/generated/peers/AnnotationDeclaration.ts new file mode 100644 index 000000000..135f8ac73 --- /dev/null +++ b/koala-wrapper/src/generated/peers/AnnotationDeclaration.ts @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +import { Identifier } from "./Identifier" +import { AnnotationUsage } from "./AnnotationUsage" +export class AnnotationDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 1) + super(pointer) + + } + static createAnnotationDeclaration(expr?: Expression): AnnotationDeclaration { + return new AnnotationDeclaration(global.generatedEs2panda._CreateAnnotationDeclaration(global.context, passNode(expr))) + } + static updateAnnotationDeclaration(original?: AnnotationDeclaration, expr?: Expression): AnnotationDeclaration { + return new AnnotationDeclaration(global.generatedEs2panda._UpdateAnnotationDeclaration(global.context, passNode(original), passNode(expr))) + } + static create1AnnotationDeclaration(expr: Expression | undefined, properties: readonly AstNode[]): AnnotationDeclaration { + return new AnnotationDeclaration(global.generatedEs2panda._CreateAnnotationDeclaration1(global.context, passNode(expr), passNodeArray(properties), properties.length)) + } + static update1AnnotationDeclaration(original: AnnotationDeclaration | undefined, expr: Expression | undefined, properties: readonly AstNode[]): AnnotationDeclaration { + return new AnnotationDeclaration(global.generatedEs2panda._UpdateAnnotationDeclaration1(global.context, passNode(original), passNode(expr), passNodeArray(properties), properties.length)) + } + get internalName(): string { + return unpackString(global.generatedEs2panda._AnnotationDeclarationInternalNameConst(global.context, this.peer)) + } + /** @deprecated */ + setInternalName(internalName: string): this { + global.generatedEs2panda._AnnotationDeclarationSetInternalName(global.context, this.peer, internalName) + return this + } + get expr(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AnnotationDeclarationExprConst(global.context, this.peer)) + } + get properties(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._AnnotationDeclarationPropertiesConst(global.context, this.peer)) + } + get propertiesPtr(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._AnnotationDeclarationPropertiesPtrConst(global.context, this.peer)) + } + /** @deprecated */ + addProperties(properties: readonly AstNode[]): this { + global.generatedEs2panda._AnnotationDeclarationAddProperties(global.context, this.peer, passNodeArray(properties), properties.length) + return this + } + get isSourceRetention(): boolean { + return global.generatedEs2panda._AnnotationDeclarationIsSourceRetentionConst(global.context, this.peer) + } + get isBytecodeRetention(): boolean { + return global.generatedEs2panda._AnnotationDeclarationIsBytecodeRetentionConst(global.context, this.peer) + } + get isRuntimeRetention(): boolean { + return global.generatedEs2panda._AnnotationDeclarationIsRuntimeRetentionConst(global.context, this.peer) + } + /** @deprecated */ + setSourceRetention(): this { + global.generatedEs2panda._AnnotationDeclarationSetSourceRetention(global.context, this.peer) + return this + } + /** @deprecated */ + setBytecodeRetention(): this { + global.generatedEs2panda._AnnotationDeclarationSetBytecodeRetention(global.context, this.peer) + return this + } + /** @deprecated */ + setRuntimeRetention(): this { + global.generatedEs2panda._AnnotationDeclarationSetRuntimeRetention(global.context, this.peer) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._AnnotationDeclarationAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._AnnotationDeclarationSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isAnnotationDeclaration(node: AstNode): node is AnnotationDeclaration { + return node instanceof AnnotationDeclaration +} +if (!nodeByType.has(1)) { + nodeByType.set(1, AnnotationDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AnnotationUsage.ts b/koala-wrapper/src/generated/peers/AnnotationUsage.ts new file mode 100644 index 000000000..1ee1f98b7 --- /dev/null +++ b/koala-wrapper/src/generated/peers/AnnotationUsage.ts @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +import { Identifier } from "./Identifier" +export class AnnotationUsage extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 2) + super(pointer) + + } + static createAnnotationUsage(expr?: Expression): AnnotationUsage { + return new AnnotationUsage(global.generatedEs2panda._CreateAnnotationUsageIr(global.context, passNode(expr))) + } + static updateAnnotationUsage(original?: AnnotationUsage, expr?: Expression): AnnotationUsage { + return new AnnotationUsage(global.generatedEs2panda._UpdateAnnotationUsageIr(global.context, passNode(original), passNode(expr))) + } + static create1AnnotationUsage(expr: Expression | undefined, properties: readonly AstNode[]): AnnotationUsage { + return new AnnotationUsage(global.generatedEs2panda._CreateAnnotationUsageIr1(global.context, passNode(expr), passNodeArray(properties), properties.length)) + } + static update1AnnotationUsage(original: AnnotationUsage | undefined, expr: Expression | undefined, properties: readonly AstNode[]): AnnotationUsage { + return new AnnotationUsage(global.generatedEs2panda._UpdateAnnotationUsageIr1(global.context, passNode(original), passNode(expr), passNodeArray(properties), properties.length)) + } + get expr(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AnnotationUsageIrExpr(global.context, this.peer)) + } + get properties(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._AnnotationUsageIrPropertiesConst(global.context, this.peer)) + } + get propertiesPtr(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._AnnotationUsageIrPropertiesPtrConst(global.context, this.peer)) + } + /** @deprecated */ + addProperty(property: AstNode): this { + global.generatedEs2panda._AnnotationUsageIrAddProperty(global.context, this.peer, passNode(property)) + return this + } + /** @deprecated */ + setProperties(properties: readonly AstNode[]): this { + global.generatedEs2panda._AnnotationUsageIrSetProperties(global.context, this.peer, passNodeArray(properties), properties.length) + return this + } +} +export function isAnnotationUsage(node: AstNode): node is AnnotationUsage { + return node instanceof AnnotationUsage +} +if (!nodeByType.has(2)) { + nodeByType.set(2, AnnotationUsage) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ArrayExpression.ts b/koala-wrapper/src/generated/peers/ArrayExpression.ts new file mode 100644 index 000000000..200648cdb --- /dev/null +++ b/koala-wrapper/src/generated/peers/ArrayExpression.ts @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { AnnotatedExpression } from "./AnnotatedExpression" +import { Expression } from "./Expression" +import { Decorator } from "./Decorator" +import { ValidationInfo } from "./ValidationInfo" +import { TypeNode } from "./TypeNode" +export class ArrayExpression extends AnnotatedExpression { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get elements(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._ArrayExpressionElementsConst(global.context, this.peer)) + } + /** @deprecated */ + setElements(elements: readonly Expression[]): this { + global.generatedEs2panda._ArrayExpressionSetElements(global.context, this.peer, passNodeArray(elements), elements.length) + return this + } + get isDeclaration(): boolean { + return global.generatedEs2panda._ArrayExpressionIsDeclarationConst(global.context, this.peer) + } + get isOptional(): boolean { + return global.generatedEs2panda._ArrayExpressionIsOptionalConst(global.context, this.peer) + } + /** @deprecated */ + setDeclaration(): this { + global.generatedEs2panda._ArrayExpressionSetDeclaration(global.context, this.peer) + return this + } + /** @deprecated */ + setOptional(optional_arg: boolean): this { + global.generatedEs2panda._ArrayExpressionSetOptional(global.context, this.peer, optional_arg) + return this + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._ArrayExpressionDecoratorsConst(global.context, this.peer)) + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._ArrayExpressionTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._ArrayExpressionSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } +} +export function isArrayExpression(node: AstNode): node is ArrayExpression { + return node instanceof ArrayExpression +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts b/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts new file mode 100644 index 000000000..7c8ca00f5 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { ScriptFunction } from "./ScriptFunction" +import { TypeNode } from "./TypeNode" +import { AnnotationUsage } from "./AnnotationUsage" +export class ArrowFunctionExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 0) + super(pointer) + + } + static createArrowFunctionExpression(func?: ScriptFunction): ArrowFunctionExpression { + return new ArrowFunctionExpression(global.generatedEs2panda._CreateArrowFunctionExpression(global.context, passNode(func))) + } + static updateArrowFunctionExpression(original?: ArrowFunctionExpression, func?: ScriptFunction): ArrowFunctionExpression { + return new ArrowFunctionExpression(global.generatedEs2panda._UpdateArrowFunctionExpression(global.context, passNode(original), passNode(func))) + } + static create1ArrowFunctionExpression(other?: ArrowFunctionExpression): ArrowFunctionExpression { + return new ArrowFunctionExpression(global.generatedEs2panda._CreateArrowFunctionExpression1(global.context, passNode(other))) + } + static update1ArrowFunctionExpression(original?: ArrowFunctionExpression, other?: ArrowFunctionExpression): ArrowFunctionExpression { + return new ArrowFunctionExpression(global.generatedEs2panda._UpdateArrowFunctionExpression1(global.context, passNode(original), passNode(other))) + } + get function(): ScriptFunction | undefined { + return unpackNode(global.generatedEs2panda._ArrowFunctionExpressionFunctionConst(global.context, this.peer)) + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._ArrowFunctionExpressionAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._ArrowFunctionExpressionSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isArrowFunctionExpression(node: AstNode): node is ArrowFunctionExpression { + return node instanceof ArrowFunctionExpression +} +if (!nodeByType.has(0)) { + nodeByType.set(0, ArrowFunctionExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AssertStatement.ts b/koala-wrapper/src/generated/peers/AssertStatement.ts new file mode 100644 index 000000000..0d2dcfe05 --- /dev/null +++ b/koala-wrapper/src/generated/peers/AssertStatement.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class AssertStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 3) + super(pointer) + + } + static createAssertStatement(test?: Expression, second?: Expression): AssertStatement { + return new AssertStatement(global.generatedEs2panda._CreateAssertStatement(global.context, passNode(test), passNode(second))) + } + static updateAssertStatement(original?: AssertStatement, test?: Expression, second?: Expression): AssertStatement { + return new AssertStatement(global.generatedEs2panda._UpdateAssertStatement(global.context, passNode(original), passNode(test), passNode(second))) + } + get test(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AssertStatementTestConst(global.context, this.peer)) + } + get second(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AssertStatementSecondConst(global.context, this.peer)) + } +} +export function isAssertStatement(node: AstNode): node is AssertStatement { + return node instanceof AssertStatement +} +if (!nodeByType.has(3)) { + nodeByType.set(3, AssertStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AssignmentExpression.ts b/koala-wrapper/src/generated/peers/AssignmentExpression.ts new file mode 100644 index 000000000..687fbd853 --- /dev/null +++ b/koala-wrapper/src/generated/peers/AssignmentExpression.ts @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Es2pandaTokenType } from "./../Es2pandaEnums" +export class AssignmentExpression extends Expression { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get left(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AssignmentExpressionLeftConst(global.context, this.peer)) + } + get right(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AssignmentExpressionRightConst(global.context, this.peer)) + } + /** @deprecated */ + setRight(expr: Expression): this { + global.generatedEs2panda._AssignmentExpressionSetRight(global.context, this.peer, passNode(expr)) + return this + } + /** @deprecated */ + setLeft(expr: Expression): this { + global.generatedEs2panda._AssignmentExpressionSetLeft(global.context, this.peer, passNode(expr)) + return this + } + get result(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AssignmentExpressionResultConst(global.context, this.peer)) + } + get operatorType(): Es2pandaTokenType { + return global.generatedEs2panda._AssignmentExpressionOperatorTypeConst(global.context, this.peer) + } + /** @deprecated */ + setResult(expr: Expression): this { + global.generatedEs2panda._AssignmentExpressionSetResult(global.context, this.peer, passNode(expr)) + return this + } + get isLogicalExtended(): boolean { + return global.generatedEs2panda._AssignmentExpressionIsLogicalExtendedConst(global.context, this.peer) + } + /** @deprecated */ + setIgnoreConstAssign(): this { + global.generatedEs2panda._AssignmentExpressionSetIgnoreConstAssign(global.context, this.peer) + return this + } + get isIgnoreConstAssign(): boolean { + return global.generatedEs2panda._AssignmentExpressionIsIgnoreConstAssignConst(global.context, this.peer) + } +} +export function isAssignmentExpression(node: AstNode): node is AssignmentExpression { + return node instanceof AssignmentExpression +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AstDumper.ts b/koala-wrapper/src/generated/peers/AstDumper.ts new file mode 100644 index 000000000..dc62ec347 --- /dev/null +++ b/koala-wrapper/src/generated/peers/AstDumper.ts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Es2pandaModifierFlags } from "./../Es2pandaEnums" +import { Es2pandaTSOperatorType } from "./../Es2pandaEnums" +export class AstDumper extends ArktsObject { + constructor(pointer: KNativePointer) { + super(pointer) + + } + static createAstDumper(node: AstNode | undefined, sourceCode: string): AstDumper { + return new AstDumper(global.generatedEs2panda._CreateAstDumper(global.context, passNode(node), sourceCode)) + } + get str(): string { + return unpackString(global.generatedEs2panda._AstDumperStrConst(global.context, this.peer)) + } +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AwaitExpression.ts b/koala-wrapper/src/generated/peers/AwaitExpression.ts new file mode 100644 index 000000000..1e5520228 --- /dev/null +++ b/koala-wrapper/src/generated/peers/AwaitExpression.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class AwaitExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 4) + super(pointer) + + } + static createAwaitExpression(argument?: Expression): AwaitExpression { + return new AwaitExpression(global.generatedEs2panda._CreateAwaitExpression(global.context, passNode(argument))) + } + static updateAwaitExpression(original?: AwaitExpression, argument?: Expression): AwaitExpression { + return new AwaitExpression(global.generatedEs2panda._UpdateAwaitExpression(global.context, passNode(original), passNode(argument))) + } + get argument(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AwaitExpressionArgumentConst(global.context, this.peer)) + } +} +export function isAwaitExpression(node: AstNode): node is AwaitExpression { + return node instanceof AwaitExpression +} +if (!nodeByType.has(4)) { + nodeByType.set(4, AwaitExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BigIntLiteral.ts b/koala-wrapper/src/generated/peers/BigIntLiteral.ts new file mode 100644 index 000000000..9d390c0c4 --- /dev/null +++ b/koala-wrapper/src/generated/peers/BigIntLiteral.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Literal } from "./Literal" +export class BigIntLiteral extends Literal { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 5) + super(pointer) + + } + static createBigIntLiteral(src: string): BigIntLiteral { + return new BigIntLiteral(global.generatedEs2panda._CreateBigIntLiteral(global.context, src)) + } + static updateBigIntLiteral(original: BigIntLiteral | undefined, src: string): BigIntLiteral { + return new BigIntLiteral(global.generatedEs2panda._UpdateBigIntLiteral(global.context, passNode(original), src)) + } + get str(): string { + return unpackString(global.generatedEs2panda._BigIntLiteralStrConst(global.context, this.peer)) + } +} +export function isBigIntLiteral(node: AstNode): node is BigIntLiteral { + return node instanceof BigIntLiteral +} +if (!nodeByType.has(5)) { + nodeByType.set(5, BigIntLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BinaryExpression.ts b/koala-wrapper/src/generated/peers/BinaryExpression.ts new file mode 100644 index 000000000..c524075b1 --- /dev/null +++ b/koala-wrapper/src/generated/peers/BinaryExpression.ts @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Es2pandaTokenType } from "./../Es2pandaEnums" +export class BinaryExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 6) + super(pointer) + + } + static createBinaryExpression(left: Expression | undefined, right: Expression | undefined, operatorType: Es2pandaTokenType): BinaryExpression { + return new BinaryExpression(global.generatedEs2panda._CreateBinaryExpression(global.context, passNode(left), passNode(right), operatorType)) + } + static updateBinaryExpression(original: BinaryExpression | undefined, left: Expression | undefined, right: Expression | undefined, operatorType: Es2pandaTokenType): BinaryExpression { + return new BinaryExpression(global.generatedEs2panda._UpdateBinaryExpression(global.context, passNode(original), passNode(left), passNode(right), operatorType)) + } + get left(): Expression | undefined { + return unpackNode(global.generatedEs2panda._BinaryExpressionLeftConst(global.context, this.peer)) + } + get right(): Expression | undefined { + return unpackNode(global.generatedEs2panda._BinaryExpressionRightConst(global.context, this.peer)) + } + get result(): Expression | undefined { + return unpackNode(global.generatedEs2panda._BinaryExpressionResultConst(global.context, this.peer)) + } + get operatorType(): Es2pandaTokenType { + return global.generatedEs2panda._BinaryExpressionOperatorTypeConst(global.context, this.peer) + } + get isLogical(): boolean { + return global.generatedEs2panda._BinaryExpressionIsLogicalConst(global.context, this.peer) + } + get isLogicalExtended(): boolean { + return global.generatedEs2panda._BinaryExpressionIsLogicalExtendedConst(global.context, this.peer) + } + get isBitwise(): boolean { + return global.generatedEs2panda._BinaryExpressionIsBitwiseConst(global.context, this.peer) + } + get isArithmetic(): boolean { + return global.generatedEs2panda._BinaryExpressionIsArithmeticConst(global.context, this.peer) + } + /** @deprecated */ + setLeft(expr: Expression): this { + global.generatedEs2panda._BinaryExpressionSetLeft(global.context, this.peer, passNode(expr)) + return this + } + /** @deprecated */ + setRight(expr: Expression): this { + global.generatedEs2panda._BinaryExpressionSetRight(global.context, this.peer, passNode(expr)) + return this + } + /** @deprecated */ + setResult(expr: Expression): this { + global.generatedEs2panda._BinaryExpressionSetResult(global.context, this.peer, passNode(expr)) + return this + } + /** @deprecated */ + setOperator(operatorType: Es2pandaTokenType): this { + global.generatedEs2panda._BinaryExpressionSetOperator(global.context, this.peer, operatorType) + return this + } +} +export function isBinaryExpression(node: AstNode): node is BinaryExpression { + return node instanceof BinaryExpression +} +if (!nodeByType.has(6)) { + nodeByType.set(6, BinaryExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BlockExpression.ts b/koala-wrapper/src/generated/peers/BlockExpression.ts new file mode 100644 index 000000000..7e22eef67 --- /dev/null +++ b/koala-wrapper/src/generated/peers/BlockExpression.ts @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Statement } from "./Statement" +export class BlockExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 155) + super(pointer) + + } + static createBlockExpression(statements: readonly Statement[]): BlockExpression { + return new BlockExpression(global.generatedEs2panda._CreateBlockExpression(global.context, passNodeArray(statements), statements.length)) + } + static updateBlockExpression(original: BlockExpression | undefined, statements: readonly Statement[]): BlockExpression { + return new BlockExpression(global.generatedEs2panda._UpdateBlockExpression(global.context, passNode(original), passNodeArray(statements), statements.length)) + } + get statements(): readonly Statement[] { + return unpackNodeArray(global.generatedEs2panda._BlockExpressionStatementsConst(global.context, this.peer)) + } + /** @deprecated */ + addStatements(statements: readonly Statement[]): this { + global.generatedEs2panda._BlockExpressionAddStatements(global.context, this.peer, passNodeArray(statements), statements.length) + return this + } + /** @deprecated */ + addStatement(statement: Statement): this { + global.generatedEs2panda._BlockExpressionAddStatement(global.context, this.peer, passNode(statement)) + return this + } +} +export function isBlockExpression(node: AstNode): node is BlockExpression { + return node instanceof BlockExpression +} +if (!nodeByType.has(155)) { + nodeByType.set(155, BlockExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BlockStatement.ts b/koala-wrapper/src/generated/peers/BlockStatement.ts new file mode 100644 index 000000000..8d8ddf9fa --- /dev/null +++ b/koala-wrapper/src/generated/peers/BlockStatement.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +export class BlockStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 7) + super(pointer) + + } + static createBlockStatement(statementList: readonly Statement[]): BlockStatement { + return new BlockStatement(global.generatedEs2panda._CreateBlockStatement(global.context, passNodeArray(statementList), statementList.length)) + } + static updateBlockStatement(original: BlockStatement | undefined, statementList: readonly Statement[]): BlockStatement { + return new BlockStatement(global.generatedEs2panda._UpdateBlockStatement(global.context, passNode(original), passNodeArray(statementList), statementList.length)) + } + get statements(): readonly Statement[] { + return unpackNodeArray(global.generatedEs2panda._BlockStatementStatementsConst(global.context, this.peer)) + } + /** @deprecated */ + setStatements(statementList: readonly Statement[]): this { + global.generatedEs2panda._BlockStatementSetStatements(global.context, this.peer, passNodeArray(statementList), statementList.length) + return this + } + /** @deprecated */ + addTrailingBlock(stmt: AstNode, trailingBlock: BlockStatement): this { + global.generatedEs2panda._BlockStatementAddTrailingBlock(global.context, this.peer, passNode(stmt), passNode(trailingBlock)) + return this + } +} +export function isBlockStatement(node: AstNode): node is BlockStatement { + return node instanceof BlockStatement +} +if (!nodeByType.has(7)) { + nodeByType.set(7, BlockStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BooleanLiteral.ts b/koala-wrapper/src/generated/peers/BooleanLiteral.ts new file mode 100644 index 000000000..9995a9f89 --- /dev/null +++ b/koala-wrapper/src/generated/peers/BooleanLiteral.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Literal } from "./Literal" +export class BooleanLiteral extends Literal { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 8) + super(pointer) + + } + static createBooleanLiteral(value: boolean): BooleanLiteral { + return new BooleanLiteral(global.generatedEs2panda._CreateBooleanLiteral(global.context, value)) + } + static updateBooleanLiteral(original: BooleanLiteral | undefined, value: boolean): BooleanLiteral { + return new BooleanLiteral(global.generatedEs2panda._UpdateBooleanLiteral(global.context, passNode(original), value)) + } + get value(): boolean { + return global.generatedEs2panda._BooleanLiteralValueConst(global.context, this.peer) + } +} +export function isBooleanLiteral(node: AstNode): node is BooleanLiteral { + return node instanceof BooleanLiteral +} +if (!nodeByType.has(8)) { + nodeByType.set(8, BooleanLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BreakStatement.ts b/koala-wrapper/src/generated/peers/BreakStatement.ts new file mode 100644 index 000000000..e293ddf59 --- /dev/null +++ b/koala-wrapper/src/generated/peers/BreakStatement.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Identifier } from "./Identifier" +export class BreakStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 9) + super(pointer) + + } + static createBreakStatement(): BreakStatement { + return new BreakStatement(global.generatedEs2panda._CreateBreakStatement(global.context)) + } + static updateBreakStatement(original?: BreakStatement): BreakStatement { + return new BreakStatement(global.generatedEs2panda._UpdateBreakStatement(global.context, passNode(original))) + } + static create1BreakStatement(ident?: Identifier): BreakStatement { + return new BreakStatement(global.generatedEs2panda._CreateBreakStatement1(global.context, passNode(ident))) + } + static update1BreakStatement(original?: BreakStatement, ident?: Identifier): BreakStatement { + return new BreakStatement(global.generatedEs2panda._UpdateBreakStatement1(global.context, passNode(original), passNode(ident))) + } + get ident(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._BreakStatementIdentConst(global.context, this.peer)) + } + get target(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._BreakStatementTargetConst(global.context, this.peer)) + } + /** @deprecated */ + setTarget(target: AstNode): this { + global.generatedEs2panda._BreakStatementSetTarget(global.context, this.peer, passNode(target)) + return this + } +} +export function isBreakStatement(node: AstNode): node is BreakStatement { + return node instanceof BreakStatement +} +if (!nodeByType.has(9)) { + nodeByType.set(9, BreakStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/CallExpression.ts b/koala-wrapper/src/generated/peers/CallExpression.ts new file mode 100644 index 000000000..3a61208f9 --- /dev/null +++ b/koala-wrapper/src/generated/peers/CallExpression.ts @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { MaybeOptionalExpression } from "./MaybeOptionalExpression" +import { Expression } from "./Expression" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +import { BlockStatement } from "./BlockStatement" +export class CallExpression extends MaybeOptionalExpression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 10) + super(pointer) + + } + static createCallExpression(callee: Expression | undefined, _arguments: readonly Expression[], typeParams: TSTypeParameterInstantiation | undefined, optional_arg: boolean, trailingComma: boolean): CallExpression { + return new CallExpression(global.generatedEs2panda._CreateCallExpression(global.context, passNode(callee), passNodeArray(_arguments), _arguments.length, passNode(typeParams), optional_arg, trailingComma)) + } + static create1CallExpression(other?: CallExpression): CallExpression { + return new CallExpression(global.generatedEs2panda._CreateCallExpression1(global.context, passNode(other))) + } + static update1CallExpression(original?: CallExpression, other?: CallExpression): CallExpression { + return new CallExpression(global.generatedEs2panda._UpdateCallExpression1(global.context, passNode(original), passNode(other))) + } + get callee(): Expression | undefined { + return unpackNode(global.generatedEs2panda._CallExpressionCalleeConst(global.context, this.peer)) + } + /** @deprecated */ + setCallee(callee: Expression): this { + global.generatedEs2panda._CallExpressionSetCallee(global.context, this.peer, passNode(callee)) + return this + } + get typeParams(): TSTypeParameterInstantiation | undefined { + return unpackNode(global.generatedEs2panda._CallExpressionTypeParamsConst(global.context, this.peer)) + } + get arguments(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._CallExpressionArgumentsConst(global.context, this.peer)) + } + get hasTrailingComma(): boolean { + return global.generatedEs2panda._CallExpressionHasTrailingCommaConst(global.context, this.peer) + } + /** @deprecated */ + setTypeParams(typeParams: TSTypeParameterInstantiation): this { + global.generatedEs2panda._CallExpressionSetTypeParams(global.context, this.peer, passNode(typeParams)) + return this + } + /** @deprecated */ + setTrailingBlock(block: BlockStatement): this { + global.generatedEs2panda._CallExpressionSetTrailingBlock(global.context, this.peer, passNode(block)) + return this + } + get trailingBlock(): BlockStatement | undefined { + return unpackNode(global.generatedEs2panda._CallExpressionTrailingBlockConst(global.context, this.peer)) + } + /** @deprecated */ + setIsTrailingBlockInNewLine(isNewLine: boolean): this { + global.generatedEs2panda._CallExpressionSetIsTrailingBlockInNewLine(global.context, this.peer, isNewLine) + return this + } + get isTrailingBlockInNewLine(): boolean { + return global.generatedEs2panda._CallExpressionIsTrailingBlockInNewLineConst(global.context, this.peer) + } + get isETSConstructorCall(): boolean { + return global.generatedEs2panda._CallExpressionIsETSConstructorCallConst(global.context, this.peer) + } +} +export function isCallExpression(node: AstNode): node is CallExpression { + return node instanceof CallExpression +} +if (!nodeByType.has(10)) { + nodeByType.set(10, CallExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/CatchClause.ts b/koala-wrapper/src/generated/peers/CatchClause.ts new file mode 100644 index 000000000..068b1dd80 --- /dev/null +++ b/koala-wrapper/src/generated/peers/CatchClause.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedStatement } from "./TypedStatement" +import { Expression } from "./Expression" +import { BlockStatement } from "./BlockStatement" +export class CatchClause extends TypedStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 11) + super(pointer) + + } + static createCatchClause(param?: Expression, body?: BlockStatement): CatchClause { + return new CatchClause(global.generatedEs2panda._CreateCatchClause(global.context, passNode(param), passNode(body))) + } + static updateCatchClause(original?: CatchClause, param?: Expression, body?: BlockStatement): CatchClause { + return new CatchClause(global.generatedEs2panda._UpdateCatchClause(global.context, passNode(original), passNode(param), passNode(body))) + } + get param(): Expression | undefined { + return unpackNode(global.generatedEs2panda._CatchClauseParamConst(global.context, this.peer)) + } + get body(): BlockStatement | undefined { + return unpackNode(global.generatedEs2panda._CatchClauseBodyConst(global.context, this.peer)) + } +} +export function isCatchClause(node: AstNode): node is CatchClause { + return node instanceof CatchClause +} +if (!nodeByType.has(11)) { + nodeByType.set(11, CatchClause) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ChainExpression.ts b/koala-wrapper/src/generated/peers/ChainExpression.ts new file mode 100644 index 000000000..ae76f46e0 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ChainExpression.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class ChainExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 12) + super(pointer) + + } + static createChainExpression(expression?: Expression): ChainExpression { + return new ChainExpression(global.generatedEs2panda._CreateChainExpression(global.context, passNode(expression))) + } + static updateChainExpression(original?: ChainExpression, expression?: Expression): ChainExpression { + return new ChainExpression(global.generatedEs2panda._UpdateChainExpression(global.context, passNode(original), passNode(expression))) + } + get getExpression(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ChainExpressionGetExpressionConst(global.context, this.peer)) + } +} +export function isChainExpression(node: AstNode): node is ChainExpression { + return node instanceof ChainExpression +} +if (!nodeByType.has(12)) { + nodeByType.set(12, ChainExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/CharLiteral.ts b/koala-wrapper/src/generated/peers/CharLiteral.ts new file mode 100644 index 000000000..7dbceda4c --- /dev/null +++ b/koala-wrapper/src/generated/peers/CharLiteral.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Literal } from "./Literal" +export class CharLiteral extends Literal { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 13) + super(pointer) + + } + static createCharLiteral(): CharLiteral { + return new CharLiteral(global.generatedEs2panda._CreateCharLiteral(global.context)) + } + static updateCharLiteral(original?: CharLiteral): CharLiteral { + return new CharLiteral(global.generatedEs2panda._UpdateCharLiteral(global.context, passNode(original))) + } +} +export function isCharLiteral(node: AstNode): node is CharLiteral { + return node instanceof CharLiteral +} +if (!nodeByType.has(13)) { + nodeByType.set(13, CharLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassDeclaration.ts b/koala-wrapper/src/generated/peers/ClassDeclaration.ts new file mode 100644 index 000000000..1af101f1c --- /dev/null +++ b/koala-wrapper/src/generated/peers/ClassDeclaration.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { ClassDefinition } from "./ClassDefinition" +import { Decorator } from "./Decorator" +export class ClassDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 15) + super(pointer) + + } + static createClassDeclaration(def?: ClassDefinition): ClassDeclaration { + return new ClassDeclaration(global.generatedEs2panda._CreateClassDeclaration(global.context, passNode(def))) + } + static updateClassDeclaration(original?: ClassDeclaration, def?: ClassDefinition): ClassDeclaration { + return new ClassDeclaration(global.generatedEs2panda._UpdateClassDeclaration(global.context, passNode(original), passNode(def))) + } + get definition(): ClassDefinition | undefined { + return unpackNode(global.generatedEs2panda._ClassDeclarationDefinitionConst(global.context, this.peer)) + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._ClassDeclarationDecoratorsConst(global.context, this.peer)) + } +} +export function isClassDeclaration(node: AstNode): node is ClassDeclaration { + return node instanceof ClassDeclaration +} +if (!nodeByType.has(15)) { + nodeByType.set(15, ClassDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassDefinition.ts b/koala-wrapper/src/generated/peers/ClassDefinition.ts new file mode 100644 index 000000000..f1187001d --- /dev/null +++ b/koala-wrapper/src/generated/peers/ClassDefinition.ts @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedAstNode } from "./TypedAstNode" +import { Identifier } from "./Identifier" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +import { TSClassImplements } from "./TSClassImplements" +import { MethodDefinition } from "./MethodDefinition" +import { Expression } from "./Expression" +import { Es2pandaClassDefinitionModifiers } from "./../Es2pandaEnums" +import { Es2pandaModifierFlags } from "./../Es2pandaEnums" +import { TSEnumDeclaration } from "./TSEnumDeclaration" +import { ClassDeclaration } from "./ClassDeclaration" +import { FunctionExpression } from "./FunctionExpression" +import { AnnotationUsage } from "./AnnotationUsage" +export class ClassDefinition extends TypedAstNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 14) + super(pointer) + + } + static createClassDefinition(ident: Identifier | undefined, typeParams: TSTypeParameterDeclaration | undefined, superTypeParams: TSTypeParameterInstantiation | undefined, _implements: readonly TSClassImplements[], ctor: MethodDefinition | undefined, superClass: Expression | undefined, body: readonly AstNode[], modifiers: Es2pandaClassDefinitionModifiers, flags: Es2pandaModifierFlags): ClassDefinition { + return new ClassDefinition(global.generatedEs2panda._CreateClassDefinition(global.context, passNode(ident), passNode(typeParams), passNode(superTypeParams), passNodeArray(_implements), _implements.length, passNode(ctor), passNode(superClass), passNodeArray(body), body.length, modifiers, flags)) + } + static updateClassDefinition(original: ClassDefinition | undefined, ident: Identifier | undefined, typeParams: TSTypeParameterDeclaration | undefined, superTypeParams: TSTypeParameterInstantiation | undefined, _implements: readonly TSClassImplements[], ctor: MethodDefinition | undefined, superClass: Expression | undefined, body: readonly AstNode[], modifiers: Es2pandaClassDefinitionModifiers, flags: Es2pandaModifierFlags): ClassDefinition { + return new ClassDefinition(global.generatedEs2panda._UpdateClassDefinition(global.context, passNode(original), passNode(ident), passNode(typeParams), passNode(superTypeParams), passNodeArray(_implements), _implements.length, passNode(ctor), passNode(superClass), passNodeArray(body), body.length, modifiers, flags)) + } + static create1ClassDefinition(ident: Identifier | undefined, body: readonly AstNode[], modifiers: Es2pandaClassDefinitionModifiers, flags: Es2pandaModifierFlags): ClassDefinition { + return new ClassDefinition(global.generatedEs2panda._CreateClassDefinition1(global.context, passNode(ident), passNodeArray(body), body.length, modifiers, flags)) + } + static update1ClassDefinition(original: ClassDefinition | undefined, ident: Identifier | undefined, body: readonly AstNode[], modifiers: Es2pandaClassDefinitionModifiers, flags: Es2pandaModifierFlags): ClassDefinition { + return new ClassDefinition(global.generatedEs2panda._UpdateClassDefinition1(global.context, passNode(original), passNode(ident), passNodeArray(body), body.length, modifiers, flags)) + } + static create2ClassDefinition(ident: Identifier | undefined, modifiers: Es2pandaClassDefinitionModifiers, flags: Es2pandaModifierFlags): ClassDefinition { + return new ClassDefinition(global.generatedEs2panda._CreateClassDefinition2(global.context, passNode(ident), modifiers, flags)) + } + static update2ClassDefinition(original: ClassDefinition | undefined, ident: Identifier | undefined, modifiers: Es2pandaClassDefinitionModifiers, flags: Es2pandaModifierFlags): ClassDefinition { + return new ClassDefinition(global.generatedEs2panda._UpdateClassDefinition2(global.context, passNode(original), passNode(ident), modifiers, flags)) + } + get ident(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ClassDefinitionIdentConst(global.context, this.peer)) + } + /** @deprecated */ + setIdent(ident: Identifier): this { + global.generatedEs2panda._ClassDefinitionSetIdent(global.context, this.peer, passNode(ident)) + return this + } + get internalName(): string { + return unpackString(global.generatedEs2panda._ClassDefinitionInternalNameConst(global.context, this.peer)) + } + /** @deprecated */ + setInternalName(internalName: string): this { + global.generatedEs2panda._ClassDefinitionSetInternalName(global.context, this.peer, internalName) + return this + } + get super(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ClassDefinitionSuperConst(global.context, this.peer)) + } + /** @deprecated */ + setSuper(superClass: Expression): this { + global.generatedEs2panda._ClassDefinitionSetSuper(global.context, this.peer, passNode(superClass)) + return this + } + get isGlobal(): boolean { + return global.generatedEs2panda._ClassDefinitionIsGlobalConst(global.context, this.peer) + } + get isLocal(): boolean { + return global.generatedEs2panda._ClassDefinitionIsLocalConst(global.context, this.peer) + } + get isExtern(): boolean { + return global.generatedEs2panda._ClassDefinitionIsExternConst(global.context, this.peer) + } + get isFromExternal(): boolean { + return global.generatedEs2panda._ClassDefinitionIsFromExternalConst(global.context, this.peer) + } + get isInner(): boolean { + return global.generatedEs2panda._ClassDefinitionIsInnerConst(global.context, this.peer) + } + get isGlobalInitialized(): boolean { + return global.generatedEs2panda._ClassDefinitionIsGlobalInitializedConst(global.context, this.peer) + } + get isClassDefinitionChecked(): boolean { + return global.generatedEs2panda._ClassDefinitionIsClassDefinitionCheckedConst(global.context, this.peer) + } + get isAnonymous(): boolean { + return global.generatedEs2panda._ClassDefinitionIsAnonymousConst(global.context, this.peer) + } + get isNamespaceTransformed(): boolean { + return global.generatedEs2panda._ClassDefinitionIsNamespaceTransformedConst(global.context, this.peer) + } + get isModule(): boolean { + return global.generatedEs2panda._ClassDefinitionIsModuleConst(global.context, this.peer) + } + /** @deprecated */ + setGlobalInitialized(): this { + global.generatedEs2panda._ClassDefinitionSetGlobalInitialized(global.context, this.peer) + return this + } + /** @deprecated */ + setInnerModifier(): this { + global.generatedEs2panda._ClassDefinitionSetInnerModifier(global.context, this.peer) + return this + } + /** @deprecated */ + setClassDefinitionChecked(): this { + global.generatedEs2panda._ClassDefinitionSetClassDefinitionChecked(global.context, this.peer) + return this + } + /** @deprecated */ + setAnonymousModifier(): this { + global.generatedEs2panda._ClassDefinitionSetAnonymousModifier(global.context, this.peer) + return this + } + /** @deprecated */ + setNamespaceTransformed(): this { + global.generatedEs2panda._ClassDefinitionSetNamespaceTransformed(global.context, this.peer) + return this + } + get modifiers(): Es2pandaClassDefinitionModifiers { + return global.generatedEs2panda._ClassDefinitionModifiersConst(global.context, this.peer) + } + /** @deprecated */ + setModifiers(modifiers: Es2pandaClassDefinitionModifiers): this { + global.generatedEs2panda._ClassDefinitionSetModifiers(global.context, this.peer, modifiers) + return this + } + /** @deprecated */ + addProperties(body: readonly AstNode[]): this { + global.generatedEs2panda._ClassDefinitionAddProperties(global.context, this.peer, passNodeArray(body), body.length) + return this + } + get body(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._ClassDefinitionBodyConst(global.context, this.peer)) + } + /** @deprecated */ + setCtor(ctor: MethodDefinition): this { + global.generatedEs2panda._ClassDefinitionSetCtor(global.context, this.peer, passNode(ctor)) + return this + } + get implements(): readonly TSClassImplements[] { + return unpackNodeArray(global.generatedEs2panda._ClassDefinitionImplementsConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._ClassDefinitionTypeParamsConst(global.context, this.peer)) + } + /** @deprecated */ + setTypeParams(typeParams: TSTypeParameterDeclaration): this { + global.generatedEs2panda._ClassDefinitionSetTypeParams(global.context, this.peer, passNode(typeParams)) + return this + } + get superTypeParams(): TSTypeParameterInstantiation | undefined { + return unpackNode(global.generatedEs2panda._ClassDefinitionSuperTypeParamsConst(global.context, this.peer)) + } + get localTypeCounter(): number { + return global.generatedEs2panda._ClassDefinitionLocalTypeCounter(global.context, this.peer) + } + get localIndex(): number { + return global.generatedEs2panda._ClassDefinitionLocalIndexConst(global.context, this.peer) + } + get localPrefix(): string { + return unpackString(global.generatedEs2panda._ClassDefinitionLocalPrefixConst(global.context, this.peer)) + } + /** @deprecated */ + setOrigEnumDecl(enumDecl: TSEnumDeclaration): this { + global.generatedEs2panda._ClassDefinitionSetOrigEnumDecl(global.context, this.peer, passNode(enumDecl)) + return this + } + get origEnumDecl(): TSEnumDeclaration | undefined { + return unpackNode(global.generatedEs2panda._ClassDefinitionOrigEnumDeclConst(global.context, this.peer)) + } + get getAnonClass(): ClassDeclaration | undefined { + return unpackNode(global.generatedEs2panda._ClassDefinitionGetAnonClass(global.context, this.peer)) + } + /** @deprecated */ + setAnonClass(anonClass: ClassDeclaration): this { + global.generatedEs2panda._ClassDefinitionSetAnonClass(global.context, this.peer, passNode(anonClass)) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._ClassDefinitionAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._ClassDefinitionSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isClassDefinition(node: AstNode): node is ClassDefinition { + return node instanceof ClassDefinition +} +if (!nodeByType.has(14)) { + nodeByType.set(14, ClassDefinition) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassElement.ts b/koala-wrapper/src/generated/peers/ClassElement.ts new file mode 100644 index 000000000..2299f192f --- /dev/null +++ b/koala-wrapper/src/generated/peers/ClassElement.ts @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedStatement } from "./TypedStatement" +import { Identifier } from "./Identifier" +import { Expression } from "./Expression" +import { Decorator } from "./Decorator" +import { Es2pandaPrivateFieldKind } from "./../Es2pandaEnums" +export class ClassElement extends TypedStatement { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get key(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ClassElementKeyConst(global.context, this.peer)) + } + /** @deprecated */ + setValue(value: Expression): this { + global.generatedEs2panda._ClassElementSetValue(global.context, this.peer, passNode(value)) + return this + } + get value(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ClassElementValueConst(global.context, this.peer)) + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._ClassElementDecoratorsConst(global.context, this.peer)) + } + get isComputed(): boolean { + return global.generatedEs2panda._ClassElementIsComputedConst(global.context, this.peer) + } + /** @deprecated */ + addDecorator(decorator: Decorator): this { + global.generatedEs2panda._ClassElementAddDecorator(global.context, this.peer, passNode(decorator)) + return this + } +} +export function isClassElement(node: AstNode): node is ClassElement { + return node instanceof ClassElement +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassExpression.ts b/koala-wrapper/src/generated/peers/ClassExpression.ts new file mode 100644 index 000000000..9b2f05b2e --- /dev/null +++ b/koala-wrapper/src/generated/peers/ClassExpression.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { ClassDefinition } from "./ClassDefinition" +export class ClassExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 16) + super(pointer) + + } + static createClassExpression(def?: ClassDefinition): ClassExpression { + return new ClassExpression(global.generatedEs2panda._CreateClassExpression(global.context, passNode(def))) + } + static updateClassExpression(original?: ClassExpression, def?: ClassDefinition): ClassExpression { + return new ClassExpression(global.generatedEs2panda._UpdateClassExpression(global.context, passNode(original), passNode(def))) + } + get definition(): ClassDefinition | undefined { + return unpackNode(global.generatedEs2panda._ClassExpressionDefinitionConst(global.context, this.peer)) + } +} +export function isClassExpression(node: AstNode): node is ClassExpression { + return node instanceof ClassExpression +} +if (!nodeByType.has(16)) { + nodeByType.set(16, ClassExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassProperty.ts b/koala-wrapper/src/generated/peers/ClassProperty.ts new file mode 100644 index 000000000..cac674bfb --- /dev/null +++ b/koala-wrapper/src/generated/peers/ClassProperty.ts @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { ClassElement } from "./ClassElement" +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +import { Es2pandaModifierFlags } from "./../Es2pandaEnums" +import { AnnotationUsage } from "./AnnotationUsage" +export class ClassProperty extends ClassElement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 17) + super(pointer) + + } + static createClassProperty(key: Expression | undefined, value: Expression | undefined, typeAnnotation: TypeNode | undefined, modifiers: Es2pandaModifierFlags, isComputed: boolean): ClassProperty { + return new ClassProperty(global.generatedEs2panda._CreateClassProperty(global.context, passNode(key), passNode(value), passNode(typeAnnotation), modifiers, isComputed)) + } + static updateClassProperty(original: ClassProperty | undefined, key: Expression | undefined, value: Expression | undefined, typeAnnotation: TypeNode | undefined, modifiers: Es2pandaModifierFlags, isComputed: boolean): ClassProperty { + return new ClassProperty(global.generatedEs2panda._UpdateClassProperty(global.context, passNode(original), passNode(key), passNode(value), passNode(typeAnnotation), modifiers, isComputed)) + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._ClassPropertyTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._ClassPropertySetTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._ClassPropertyAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._ClassPropertySetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isClassProperty(node: AstNode): node is ClassProperty { + return node instanceof ClassProperty +} +if (!nodeByType.has(17)) { + nodeByType.set(17, ClassProperty) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassStaticBlock.ts b/koala-wrapper/src/generated/peers/ClassStaticBlock.ts new file mode 100644 index 000000000..92ff36429 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ClassStaticBlock.ts @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { ClassElement } from "./ClassElement" +import { Expression } from "./Expression" +import { ScriptFunction } from "./ScriptFunction" +export class ClassStaticBlock extends ClassElement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 18) + super(pointer) + + } + static createClassStaticBlock(value?: Expression): ClassStaticBlock { + return new ClassStaticBlock(global.generatedEs2panda._CreateClassStaticBlock(global.context, passNode(value))) + } + static updateClassStaticBlock(original?: ClassStaticBlock, value?: Expression): ClassStaticBlock { + return new ClassStaticBlock(global.generatedEs2panda._UpdateClassStaticBlock(global.context, passNode(original), passNode(value))) + } +} +export function isClassStaticBlock(node: AstNode): node is ClassStaticBlock { + return node instanceof ClassStaticBlock +} +if (!nodeByType.has(18)) { + nodeByType.set(18, ClassStaticBlock) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ConditionalExpression.ts b/koala-wrapper/src/generated/peers/ConditionalExpression.ts new file mode 100644 index 000000000..20ab3b028 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ConditionalExpression.ts @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class ConditionalExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 19) + super(pointer) + + } + static createConditionalExpression(test?: Expression, consequent?: Expression, alternate?: Expression): ConditionalExpression { + return new ConditionalExpression(global.generatedEs2panda._CreateConditionalExpression(global.context, passNode(test), passNode(consequent), passNode(alternate))) + } + static updateConditionalExpression(original?: ConditionalExpression, test?: Expression, consequent?: Expression, alternate?: Expression): ConditionalExpression { + return new ConditionalExpression(global.generatedEs2panda._UpdateConditionalExpression(global.context, passNode(original), passNode(test), passNode(consequent), passNode(alternate))) + } + get test(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ConditionalExpressionTestConst(global.context, this.peer)) + } + /** @deprecated */ + setTest(expr: Expression): this { + global.generatedEs2panda._ConditionalExpressionSetTest(global.context, this.peer, passNode(expr)) + return this + } + get consequent(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ConditionalExpressionConsequentConst(global.context, this.peer)) + } + /** @deprecated */ + setConsequent(expr: Expression): this { + global.generatedEs2panda._ConditionalExpressionSetConsequent(global.context, this.peer, passNode(expr)) + return this + } + get alternate(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ConditionalExpressionAlternateConst(global.context, this.peer)) + } + /** @deprecated */ + setAlternate(expr: Expression): this { + global.generatedEs2panda._ConditionalExpressionSetAlternate(global.context, this.peer, passNode(expr)) + return this + } +} +export function isConditionalExpression(node: AstNode): node is ConditionalExpression { + return node instanceof ConditionalExpression +} +if (!nodeByType.has(19)) { + nodeByType.set(19, ConditionalExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Context.ts b/koala-wrapper/src/generated/peers/Context.ts new file mode 100644 index 000000000..b34fc3981 --- /dev/null +++ b/koala-wrapper/src/generated/peers/Context.ts @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +export class Context extends ArktsObject { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ContinueStatement.ts b/koala-wrapper/src/generated/peers/ContinueStatement.ts new file mode 100644 index 000000000..6d9f8a42e --- /dev/null +++ b/koala-wrapper/src/generated/peers/ContinueStatement.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Identifier } from "./Identifier" +export class ContinueStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 20) + super(pointer) + + } + static createContinueStatement(): ContinueStatement { + return new ContinueStatement(global.generatedEs2panda._CreateContinueStatement(global.context)) + } + static updateContinueStatement(original?: ContinueStatement): ContinueStatement { + return new ContinueStatement(global.generatedEs2panda._UpdateContinueStatement(global.context, passNode(original))) + } + static create1ContinueStatement(ident?: Identifier): ContinueStatement { + return new ContinueStatement(global.generatedEs2panda._CreateContinueStatement1(global.context, passNode(ident))) + } + static update1ContinueStatement(original?: ContinueStatement, ident?: Identifier): ContinueStatement { + return new ContinueStatement(global.generatedEs2panda._UpdateContinueStatement1(global.context, passNode(original), passNode(ident))) + } + get ident(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ContinueStatementIdentConst(global.context, this.peer)) + } + get target(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._ContinueStatementTargetConst(global.context, this.peer)) + } + /** @deprecated */ + setTarget(target: AstNode): this { + global.generatedEs2panda._ContinueStatementSetTarget(global.context, this.peer, passNode(target)) + return this + } +} +export function isContinueStatement(node: AstNode): node is ContinueStatement { + return node instanceof ContinueStatement +} +if (!nodeByType.has(20)) { + nodeByType.set(20, ContinueStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/DebuggerStatement.ts b/koala-wrapper/src/generated/peers/DebuggerStatement.ts new file mode 100644 index 000000000..e74c35108 --- /dev/null +++ b/koala-wrapper/src/generated/peers/DebuggerStatement.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +export class DebuggerStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 21) + super(pointer) + + } + static createDebuggerStatement(): DebuggerStatement { + return new DebuggerStatement(global.generatedEs2panda._CreateDebuggerStatement(global.context)) + } + static updateDebuggerStatement(original?: DebuggerStatement): DebuggerStatement { + return new DebuggerStatement(global.generatedEs2panda._UpdateDebuggerStatement(global.context, passNode(original))) + } +} +export function isDebuggerStatement(node: AstNode): node is DebuggerStatement { + return node instanceof DebuggerStatement +} +if (!nodeByType.has(21)) { + nodeByType.set(21, DebuggerStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Decorator.ts b/koala-wrapper/src/generated/peers/Decorator.ts new file mode 100644 index 000000000..de635c11e --- /dev/null +++ b/koala-wrapper/src/generated/peers/Decorator.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class Decorator extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 22) + super(pointer) + + } + static createDecorator(expr?: Expression): Decorator { + return new Decorator(global.generatedEs2panda._CreateDecorator(global.context, passNode(expr))) + } + static updateDecorator(original?: Decorator, expr?: Expression): Decorator { + return new Decorator(global.generatedEs2panda._UpdateDecorator(global.context, passNode(original), passNode(expr))) + } + get expr(): Expression | undefined { + return unpackNode(global.generatedEs2panda._DecoratorExprConst(global.context, this.peer)) + } +} +export function isDecorator(node: AstNode): node is Decorator { + return node instanceof Decorator +} +if (!nodeByType.has(22)) { + nodeByType.set(22, Decorator) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/DirectEvalExpression.ts b/koala-wrapper/src/generated/peers/DirectEvalExpression.ts new file mode 100644 index 000000000..d432f9f0d --- /dev/null +++ b/koala-wrapper/src/generated/peers/DirectEvalExpression.ts @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { CallExpression } from "./CallExpression" +import { Expression } from "./Expression" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +export class DirectEvalExpression extends CallExpression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 23) + super(pointer) + + } + static createDirectEvalExpression(callee: Expression | undefined, _arguments: readonly Expression[], typeParams: TSTypeParameterInstantiation | undefined, optional_arg: boolean, parserStatus: number): DirectEvalExpression { + return new DirectEvalExpression(global.generatedEs2panda._CreateDirectEvalExpression(global.context, passNode(callee), passNodeArray(_arguments), _arguments.length, passNode(typeParams), optional_arg, parserStatus)) + } + static updateDirectEvalExpression(original: DirectEvalExpression | undefined, callee: Expression | undefined, _arguments: readonly Expression[], typeParams: TSTypeParameterInstantiation | undefined, optional_arg: boolean, parserStatus: number): DirectEvalExpression { + return new DirectEvalExpression(global.generatedEs2panda._UpdateDirectEvalExpression(global.context, passNode(original), passNode(callee), passNodeArray(_arguments), _arguments.length, passNode(typeParams), optional_arg, parserStatus)) + } +} +export function isDirectEvalExpression(node: AstNode): node is DirectEvalExpression { + return node instanceof DirectEvalExpression +} +if (!nodeByType.has(23)) { + nodeByType.set(23, DirectEvalExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/DoWhileStatement.ts b/koala-wrapper/src/generated/peers/DoWhileStatement.ts new file mode 100644 index 000000000..c6ce8c8cd --- /dev/null +++ b/koala-wrapper/src/generated/peers/DoWhileStatement.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { LoopStatement } from "./LoopStatement" +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class DoWhileStatement extends LoopStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 24) + super(pointer) + + } + static createDoWhileStatement(body?: Statement, test?: Expression): DoWhileStatement { + return new DoWhileStatement(global.generatedEs2panda._CreateDoWhileStatement(global.context, passNode(body), passNode(test))) + } + static updateDoWhileStatement(original?: DoWhileStatement, body?: Statement, test?: Expression): DoWhileStatement { + return new DoWhileStatement(global.generatedEs2panda._UpdateDoWhileStatement(global.context, passNode(original), passNode(body), passNode(test))) + } + get body(): Statement | undefined { + return unpackNode(global.generatedEs2panda._DoWhileStatementBodyConst(global.context, this.peer)) + } + get test(): Expression | undefined { + return unpackNode(global.generatedEs2panda._DoWhileStatementTestConst(global.context, this.peer)) + } +} +export function isDoWhileStatement(node: AstNode): node is DoWhileStatement { + return node instanceof DoWhileStatement +} +if (!nodeByType.has(24)) { + nodeByType.set(24, DoWhileStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSClassLiteral.ts b/koala-wrapper/src/generated/peers/ETSClassLiteral.ts new file mode 100644 index 000000000..d78af3b90 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSClassLiteral.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class ETSClassLiteral extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 70) + super(pointer) + + } + static createETSClassLiteral(expr?: TypeNode): ETSClassLiteral { + return new ETSClassLiteral(global.generatedEs2panda._CreateETSClassLiteral(global.context, passNode(expr))) + } + static updateETSClassLiteral(original?: ETSClassLiteral, expr?: TypeNode): ETSClassLiteral { + return new ETSClassLiteral(global.generatedEs2panda._UpdateETSClassLiteral(global.context, passNode(original), passNode(expr))) + } + get expr(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._ETSClassLiteralExprConst(global.context, this.peer)) + } +} +export function isETSClassLiteral(node: AstNode): node is ETSClassLiteral { + return node instanceof ETSClassLiteral +} +if (!nodeByType.has(70)) { + nodeByType.set(70, ETSClassLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSDynamicFunctionType.ts b/koala-wrapper/src/generated/peers/ETSDynamicFunctionType.ts new file mode 100644 index 000000000..8b9b32069 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSDynamicFunctionType.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { ETSFunctionType } from "./ETSFunctionType" +export class ETSDynamicFunctionType extends ETSFunctionType { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isETSDynamicFunctionType(node: AstNode): node is ETSDynamicFunctionType { + return node instanceof ETSDynamicFunctionType +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSFunctionType.ts b/koala-wrapper/src/generated/peers/ETSFunctionType.ts new file mode 100644 index 000000000..5354546f8 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSFunctionType.ts @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { FunctionSignature } from "./FunctionSignature" +import { Es2pandaScriptFunctionFlags } from "./../Es2pandaEnums" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { Expression } from "./Expression" +import { TSInterfaceDeclaration } from "./TSInterfaceDeclaration" +export class ETSFunctionType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 66) + super(pointer) + + } + static createETSFunctionType(signature: FunctionSignature | undefined, funcFlags: Es2pandaScriptFunctionFlags): ETSFunctionType { + return new ETSFunctionType(global.generatedEs2panda._CreateETSFunctionTypeIr(global.context, passNode(signature), funcFlags)) + } + static updateETSFunctionType(original: ETSFunctionType | undefined, signature: FunctionSignature | undefined, funcFlags: Es2pandaScriptFunctionFlags): ETSFunctionType { + return new ETSFunctionType(global.generatedEs2panda._UpdateETSFunctionTypeIr(global.context, passNode(original), passNode(signature), funcFlags)) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._ETSFunctionTypeIrTypeParamsConst(global.context, this.peer)) + } + get params(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._ETSFunctionTypeIrParamsConst(global.context, this.peer)) + } + get returnType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._ETSFunctionTypeIrReturnTypeConst(global.context, this.peer)) + } + get functionalInterface(): TSInterfaceDeclaration | undefined { + return unpackNode(global.generatedEs2panda._ETSFunctionTypeIrFunctionalInterfaceConst(global.context, this.peer)) + } + /** @deprecated */ + setFunctionalInterface(functionalInterface: TSInterfaceDeclaration): this { + global.generatedEs2panda._ETSFunctionTypeIrSetFunctionalInterface(global.context, this.peer, passNode(functionalInterface)) + return this + } + get flags(): Es2pandaScriptFunctionFlags { + return global.generatedEs2panda._ETSFunctionTypeIrFlags(global.context, this.peer) + } + get isThrowing(): boolean { + return global.generatedEs2panda._ETSFunctionTypeIrIsThrowingConst(global.context, this.peer) + } + get isRethrowing(): boolean { + return global.generatedEs2panda._ETSFunctionTypeIrIsRethrowingConst(global.context, this.peer) + } + get isExtensionFunction(): boolean { + return global.generatedEs2panda._ETSFunctionTypeIrIsExtensionFunctionConst(global.context, this.peer) + } +} +export function isETSFunctionType(node: AstNode): node is ETSFunctionType { + return node instanceof ETSFunctionType +} +if (!nodeByType.has(66)) { + nodeByType.set(66, ETSFunctionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts b/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts new file mode 100644 index 000000000..9261c82c6 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { ImportDeclaration } from "./ImportDeclaration" +import { ImportSource } from "./ImportSource" +import { Es2pandaImportKinds } from "./../Es2pandaEnums" +import { StringLiteral } from "./StringLiteral" +export class ETSImportDeclaration extends ImportDeclaration { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 79) + super(pointer) + + } + static createETSImportDeclaration(source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds): ETSImportDeclaration { + return new ETSImportDeclaration(global.generatedEs2panda._CreateETSImportDeclaration(global.context, passNode(source), passNodeArray(specifiers), specifiers.length, importKind)) + } + static updateETSImportDeclaration(original: ETSImportDeclaration | undefined, source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds): ETSImportDeclaration { + return new ETSImportDeclaration(global.generatedEs2panda._UpdateETSImportDeclaration(global.context, passNode(original), passNode(source), passNodeArray(specifiers), specifiers.length, importKind)) + } + get hasDecl(): boolean { + return global.generatedEs2panda._ETSImportDeclarationHasDeclConst(global.context, this.peer) + } + get isPureDynamic(): boolean { + return global.generatedEs2panda._ETSImportDeclarationIsPureDynamicConst(global.context, this.peer) + } + get assemblerName(): string { + return unpackString(global.generatedEs2panda._ETSImportDeclarationAssemblerNameConst(global.context, this.peer)) + } + // get source(): StringLiteral | undefined { + // return unpackNode(global.generatedEs2panda._ETSImportDeclarationSourceConst(global.context, this.peer)) + // } + get resolvedSource(): StringLiteral | undefined { + return unpackNode(global.generatedEs2panda._ETSImportDeclarationResolvedSourceConst(global.context, this.peer)) + } +} +export function isETSImportDeclaration(node: AstNode): node is ETSImportDeclaration { + return node instanceof ETSImportDeclaration +} +if (!nodeByType.has(79)) { + nodeByType.set(79, ETSImportDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSLaunchExpression.ts b/koala-wrapper/src/generated/peers/ETSLaunchExpression.ts new file mode 100644 index 000000000..39a42bcc6 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSLaunchExpression.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { CallExpression } from "./CallExpression" +export class ETSLaunchExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 75) + super(pointer) + + } + static createETSLaunchExpression(expr?: CallExpression): ETSLaunchExpression { + return new ETSLaunchExpression(global.generatedEs2panda._CreateETSLaunchExpression(global.context, passNode(expr))) + } + static updateETSLaunchExpression(original?: ETSLaunchExpression, expr?: CallExpression): ETSLaunchExpression { + return new ETSLaunchExpression(global.generatedEs2panda._UpdateETSLaunchExpression(global.context, passNode(original), passNode(expr))) + } + get call(): CallExpression | undefined { + return unpackNode(global.generatedEs2panda._ETSLaunchExpressionCallConst(global.context, this.peer)) + } +} +export function isETSLaunchExpression(node: AstNode): node is ETSLaunchExpression { + return node instanceof ETSLaunchExpression +} +if (!nodeByType.has(75)) { + nodeByType.set(75, ETSLaunchExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSModule.ts b/koala-wrapper/src/generated/peers/ETSModule.ts new file mode 100644 index 000000000..df693d3b1 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSModule.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { BlockStatement } from "./BlockStatement" +import { Identifier } from "./Identifier" +import { AnnotationUsage } from "./AnnotationUsage" +export class ETSModule extends BlockStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 82) + super(pointer) + + } + get ident(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ETSModuleIdentConst(global.context, this.peer)) + } + get isETSScript(): boolean { + return global.generatedEs2panda._ETSModuleIsETSScriptConst(global.context, this.peer) + } + get isNamespace(): boolean { + return global.generatedEs2panda._ETSModuleIsNamespaceConst(global.context, this.peer) + } + get isNamespaceChainLastNode(): boolean { + return global.generatedEs2panda._ETSModuleIsNamespaceChainLastNodeConst(global.context, this.peer) + } + /** @deprecated */ + setNamespaceChainLastNode(): this { + global.generatedEs2panda._ETSModuleSetNamespaceChainLastNode(global.context, this.peer) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._ETSModuleAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._ETSModuleSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isETSModule(node: AstNode): node is ETSModule { + return node instanceof ETSModule +} +if (!nodeByType.has(82)) { + nodeByType.set(82, ETSModule) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts new file mode 100644 index 000000000..05135647e --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class ETSNewArrayInstanceExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 76) + super(pointer) + + } + static createETSNewArrayInstanceExpression(typeReference?: TypeNode, dimension?: Expression): ETSNewArrayInstanceExpression { + return new ETSNewArrayInstanceExpression(global.generatedEs2panda._CreateETSNewArrayInstanceExpression(global.context, passNode(typeReference), passNode(dimension))) + } + static updateETSNewArrayInstanceExpression(original?: ETSNewArrayInstanceExpression, typeReference?: TypeNode, dimension?: Expression): ETSNewArrayInstanceExpression { + return new ETSNewArrayInstanceExpression(global.generatedEs2panda._UpdateETSNewArrayInstanceExpression(global.context, passNode(original), passNode(typeReference), passNode(dimension))) + } + get typeReference(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._ETSNewArrayInstanceExpressionTypeReferenceConst(global.context, this.peer)) + } + get dimension(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ETSNewArrayInstanceExpressionDimensionConst(global.context, this.peer)) + } + /** @deprecated */ + setDimension(dimension: Expression): this { + global.generatedEs2panda._ETSNewArrayInstanceExpressionSetDimension(global.context, this.peer, passNode(dimension)) + return this + } +} +export function isETSNewArrayInstanceExpression(node: AstNode): node is ETSNewArrayInstanceExpression { + return node instanceof ETSNewArrayInstanceExpression +} +if (!nodeByType.has(76)) { + nodeByType.set(76, ETSNewArrayInstanceExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts new file mode 100644 index 000000000..7e0bb389b --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class ETSNewClassInstanceExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 78) + super(pointer) + + } + static createETSNewClassInstanceExpression(typeReference: Expression | undefined, _arguments: readonly Expression[]): ETSNewClassInstanceExpression { + return new ETSNewClassInstanceExpression(global.generatedEs2panda._CreateETSNewClassInstanceExpression(global.context, passNode(typeReference), passNodeArray(_arguments), _arguments.length)) + } + static updateETSNewClassInstanceExpression(original: ETSNewClassInstanceExpression | undefined, typeReference: Expression | undefined, _arguments: readonly Expression[]): ETSNewClassInstanceExpression { + return new ETSNewClassInstanceExpression(global.generatedEs2panda._UpdateETSNewClassInstanceExpression(global.context, passNode(original), passNode(typeReference), passNodeArray(_arguments), _arguments.length)) + } + static create1ETSNewClassInstanceExpression(other?: ETSNewClassInstanceExpression): ETSNewClassInstanceExpression { + return new ETSNewClassInstanceExpression(global.generatedEs2panda._CreateETSNewClassInstanceExpression1(global.context, passNode(other))) + } + static update1ETSNewClassInstanceExpression(original?: ETSNewClassInstanceExpression, other?: ETSNewClassInstanceExpression): ETSNewClassInstanceExpression { + return new ETSNewClassInstanceExpression(global.generatedEs2panda._UpdateETSNewClassInstanceExpression1(global.context, passNode(original), passNode(other))) + } + get getTypeRef(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ETSNewClassInstanceExpressionGetTypeRefConst(global.context, this.peer)) + } + get getArguments(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._ETSNewClassInstanceExpressionGetArgumentsConst(global.context, this.peer)) + } + /** @deprecated */ + setArguments(_arguments: readonly Expression[]): this { + global.generatedEs2panda._ETSNewClassInstanceExpressionSetArguments(global.context, this.peer, passNodeArray(_arguments), _arguments.length) + return this + } + /** @deprecated */ + addToArgumentsFront(expr: Expression): this { + global.generatedEs2panda._ETSNewClassInstanceExpressionAddToArgumentsFront(global.context, this.peer, passNode(expr)) + return this + } +} +export function isETSNewClassInstanceExpression(node: AstNode): node is ETSNewClassInstanceExpression { + return node instanceof ETSNewClassInstanceExpression +} +if (!nodeByType.has(78)) { + nodeByType.set(78, ETSNewClassInstanceExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts new file mode 100644 index 000000000..e99e3ed42 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class ETSNewMultiDimArrayInstanceExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 77) + super(pointer) + + } + static createETSNewMultiDimArrayInstanceExpression(typeReference: TypeNode | undefined, dimensions: readonly Expression[]): ETSNewMultiDimArrayInstanceExpression { + return new ETSNewMultiDimArrayInstanceExpression(global.generatedEs2panda._CreateETSNewMultiDimArrayInstanceExpression(global.context, passNode(typeReference), passNodeArray(dimensions), dimensions.length)) + } + static updateETSNewMultiDimArrayInstanceExpression(original: ETSNewMultiDimArrayInstanceExpression | undefined, typeReference: TypeNode | undefined, dimensions: readonly Expression[]): ETSNewMultiDimArrayInstanceExpression { + return new ETSNewMultiDimArrayInstanceExpression(global.generatedEs2panda._UpdateETSNewMultiDimArrayInstanceExpression(global.context, passNode(original), passNode(typeReference), passNodeArray(dimensions), dimensions.length)) + } + static create1ETSNewMultiDimArrayInstanceExpression(other?: ETSNewMultiDimArrayInstanceExpression): ETSNewMultiDimArrayInstanceExpression { + return new ETSNewMultiDimArrayInstanceExpression(global.generatedEs2panda._CreateETSNewMultiDimArrayInstanceExpression1(global.context, passNode(other))) + } + static update1ETSNewMultiDimArrayInstanceExpression(original?: ETSNewMultiDimArrayInstanceExpression, other?: ETSNewMultiDimArrayInstanceExpression): ETSNewMultiDimArrayInstanceExpression { + return new ETSNewMultiDimArrayInstanceExpression(global.generatedEs2panda._UpdateETSNewMultiDimArrayInstanceExpression1(global.context, passNode(original), passNode(other))) + } + get typeReference(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._ETSNewMultiDimArrayInstanceExpressionTypeReferenceConst(global.context, this.peer)) + } + get dimensions(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._ETSNewMultiDimArrayInstanceExpressionDimensionsConst(global.context, this.peer)) + } +} +export function isETSNewMultiDimArrayInstanceExpression(node: AstNode): node is ETSNewMultiDimArrayInstanceExpression { + return node instanceof ETSNewMultiDimArrayInstanceExpression +} +if (!nodeByType.has(77)) { + nodeByType.set(77, ETSNewMultiDimArrayInstanceExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSNullType.ts b/koala-wrapper/src/generated/peers/ETSNullType.ts new file mode 100644 index 000000000..edf561cf1 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSNullType.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class ETSNullType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 62) + super(pointer) + + } + static createETSNullType(): ETSNullType { + return new ETSNullType(global.generatedEs2panda._CreateETSNullTypeIr(global.context)) + } + static updateETSNullType(original?: ETSNullType): ETSNullType { + return new ETSNullType(global.generatedEs2panda._UpdateETSNullTypeIr(global.context, passNode(original))) + } +} +export function isETSNullType(node: AstNode): node is ETSNullType { + return node instanceof ETSNullType +} +if (!nodeByType.has(62)) { + nodeByType.set(62, ETSNullType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts b/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts new file mode 100644 index 000000000..1148df88e --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class ETSPackageDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 69) + super(pointer) + + } + static createETSPackageDeclaration(name?: Expression): ETSPackageDeclaration { + return new ETSPackageDeclaration(global.generatedEs2panda._CreateETSPackageDeclaration(global.context, passNode(name))) + } + static updateETSPackageDeclaration(original?: ETSPackageDeclaration, name?: Expression): ETSPackageDeclaration { + return new ETSPackageDeclaration(global.generatedEs2panda._UpdateETSPackageDeclaration(global.context, passNode(original), passNode(name))) + } +} +export function isETSPackageDeclaration(node: AstNode): node is ETSPackageDeclaration { + return node instanceof ETSPackageDeclaration +} +if (!nodeByType.has(69)) { + nodeByType.set(69, ETSPackageDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSParameterExpression.ts b/koala-wrapper/src/generated/peers/ETSParameterExpression.ts new file mode 100644 index 000000000..3b8c76a41 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSParameterExpression.ts @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { AnnotatedExpression } from "./AnnotatedExpression" +import { Identifier } from "./Identifier" +import { SpreadElement } from "./SpreadElement" +import { TypeNode } from "./TypeNode" +import { AnnotationUsage } from "./AnnotationUsage" +export class ETSParameterExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 80) + super(pointer) + + } + static createETSParameterExpression(identOrSpread: AnnotatedExpression | undefined, isOptional: boolean): ETSParameterExpression { + return new ETSParameterExpression(global.generatedEs2panda._CreateETSParameterExpression(global.context, passNode(identOrSpread), isOptional)) + } + static updateETSParameterExpression(original: ETSParameterExpression | undefined, identOrSpread: AnnotatedExpression | undefined, isOptional: boolean): ETSParameterExpression { + return new ETSParameterExpression(global.generatedEs2panda._UpdateETSParameterExpression(global.context, passNode(original), passNode(identOrSpread), isOptional)) + } + static create1ETSParameterExpression(identOrSpread?: AnnotatedExpression, initializer?: Expression): ETSParameterExpression { + return new ETSParameterExpression(global.generatedEs2panda._CreateETSParameterExpression1(global.context, passNode(identOrSpread), passNode(initializer))) + } + static update1ETSParameterExpression(original?: ETSParameterExpression, identOrSpread?: AnnotatedExpression, initializer?: Expression): ETSParameterExpression { + return new ETSParameterExpression(global.generatedEs2panda._UpdateETSParameterExpression1(global.context, passNode(original), passNode(identOrSpread), passNode(initializer))) + } + /** @deprecated */ + setIdent(ident: Identifier): this { + global.generatedEs2panda._ETSParameterExpressionSetIdent(global.context, this.peer, passNode(ident)) + return this + } + /** @deprecated */ + setLexerSaved(s: string): this { + global.generatedEs2panda._ETSParameterExpressionSetLexerSaved(global.context, this.peer, s) + return this + } + /** @deprecated */ + setTypeAnnotation(typeNode: TypeNode): this { + global.generatedEs2panda._ETSParameterExpressionSetTypeAnnotation(global.context, this.peer, passNode(typeNode)) + return this + } + get isOptional(): boolean { + return global.generatedEs2panda._ETSParameterExpressionIsOptionalConst(global.context, this.peer) + } + /** @deprecated */ + setOptional(value: boolean): this { + global.generatedEs2panda._ETSParameterExpressionSetOptional(global.context, this.peer, value) + return this + } + /** @deprecated */ + setInitializer(initExpr: Expression): this { + global.generatedEs2panda._ETSParameterExpressionSetInitializer(global.context, this.peer, passNode(initExpr)) + return this + } + get isRestParameter(): boolean { + return global.generatedEs2panda._ETSParameterExpressionIsRestParameterConst(global.context, this.peer) + } + get getRequiredParams(): number { + return global.generatedEs2panda._ETSParameterExpressionGetRequiredParamsConst(global.context, this.peer) + } + /** @deprecated */ + setRequiredParams(value: number): this { + global.generatedEs2panda._ETSParameterExpressionSetRequiredParams(global.context, this.peer, value) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._ETSParameterExpressionAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._ETSParameterExpressionSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isETSParameterExpression(node: AstNode): node is ETSParameterExpression { + return node instanceof ETSParameterExpression +} +if (!nodeByType.has(80)) { + nodeByType.set(80, ETSParameterExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts b/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts new file mode 100644 index 000000000..82713f44b --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Es2pandaPrimitiveType } from "./../Es2pandaEnums" +export class ETSPrimitiveType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 68) + super(pointer) + + } + static createETSPrimitiveType(type: Es2pandaPrimitiveType): ETSPrimitiveType { + return new ETSPrimitiveType(global.generatedEs2panda._CreateETSPrimitiveType(global.context, type)) + } + static updateETSPrimitiveType(original: ETSPrimitiveType | undefined, type: Es2pandaPrimitiveType): ETSPrimitiveType { + return new ETSPrimitiveType(global.generatedEs2panda._UpdateETSPrimitiveType(global.context, passNode(original), type)) + } + get getPrimitiveType(): Es2pandaPrimitiveType { + return global.generatedEs2panda._ETSPrimitiveTypeGetPrimitiveTypeConst(global.context, this.peer) + } +} +export function isETSPrimitiveType(node: AstNode): node is ETSPrimitiveType { + return node instanceof ETSPrimitiveType +} +if (!nodeByType.has(68)) { + nodeByType.set(68, ETSPrimitiveType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts b/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts new file mode 100644 index 000000000..6e33931db --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { ETSImportDeclaration } from "./ETSImportDeclaration" +export class ETSReExportDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 57) + super(pointer) + + } + get getETSImportDeclarations(): ETSImportDeclaration | undefined { + return unpackNode(global.generatedEs2panda._ETSReExportDeclarationGetETSImportDeclarationsConst(global.context, this.peer)) + } + get getProgramPath(): string { + return unpackString(global.generatedEs2panda._ETSReExportDeclarationGetProgramPathConst(global.context, this.peer)) + } +} +export function isETSReExportDeclaration(node: AstNode): node is ETSReExportDeclaration { + return node instanceof ETSReExportDeclaration +} +if (!nodeByType.has(57)) { + nodeByType.set(57, ETSReExportDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts b/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts new file mode 100644 index 000000000..9a060fdce --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { ClassDeclaration } from "./ClassDeclaration" +import { ClassDefinition } from "./ClassDefinition" +export class ETSStructDeclaration extends ClassDeclaration { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 84) + super(pointer) + + } + static createETSStructDeclaration(def?: ClassDefinition): ETSStructDeclaration { + return new ETSStructDeclaration(global.generatedEs2panda._CreateETSStructDeclaration(global.context, passNode(def))) + } + static updateETSStructDeclaration(original?: ETSStructDeclaration, def?: ClassDefinition): ETSStructDeclaration { + return new ETSStructDeclaration(global.generatedEs2panda._UpdateETSStructDeclaration(global.context, passNode(original), passNode(def))) + } +} +export function isETSStructDeclaration(node: AstNode): node is ETSStructDeclaration { + return node instanceof ETSStructDeclaration +} +if (!nodeByType.has(84)) { + nodeByType.set(84, ETSStructDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSTuple.ts b/koala-wrapper/src/generated/peers/ETSTuple.ts new file mode 100644 index 000000000..158eee3f8 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSTuple.ts @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class ETSTuple extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 81) + super(pointer) + + } + static createETSTuple(): ETSTuple { + return new ETSTuple(global.generatedEs2panda._CreateETSTuple(global.context)) + } + static updateETSTuple(original?: ETSTuple): ETSTuple { + return new ETSTuple(global.generatedEs2panda._UpdateETSTuple(global.context, passNode(original))) + } + static create1ETSTuple(size: number): ETSTuple { + return new ETSTuple(global.generatedEs2panda._CreateETSTuple1(global.context, size)) + } + static update1ETSTuple(original: ETSTuple | undefined, size: number): ETSTuple { + return new ETSTuple(global.generatedEs2panda._UpdateETSTuple1(global.context, passNode(original), size)) + } + static create2ETSTuple(typeList: readonly TypeNode[]): ETSTuple { + return new ETSTuple(global.generatedEs2panda._CreateETSTuple2(global.context, passNodeArray(typeList), typeList.length)) + } + static update2ETSTuple(original: ETSTuple | undefined, typeList: readonly TypeNode[]): ETSTuple { + return new ETSTuple(global.generatedEs2panda._UpdateETSTuple2(global.context, passNode(original), passNodeArray(typeList), typeList.length)) + } + get getTupleSize(): number { + return global.generatedEs2panda._ETSTupleGetTupleSizeConst(global.context, this.peer) + } + get getTupleTypeAnnotationsList(): readonly TypeNode[] { + return unpackNodeArray(global.generatedEs2panda._ETSTupleGetTupleTypeAnnotationsListConst(global.context, this.peer)) + } + get hasSpreadType(): boolean { + return global.generatedEs2panda._ETSTupleHasSpreadTypeConst(global.context, this.peer) + } + /** @deprecated */ + setSpreadType(newSpreadType: TypeNode): this { + global.generatedEs2panda._ETSTupleSetSpreadType(global.context, this.peer, passNode(newSpreadType)) + return this + } + /** @deprecated */ + setTypeAnnotationsList(typeNodeList: readonly TypeNode[]): this { + global.generatedEs2panda._ETSTupleSetTypeAnnotationsList(global.context, this.peer, passNodeArray(typeNodeList), typeNodeList.length) + return this + } +} +export function isETSTuple(node: AstNode): node is ETSTuple { + return node instanceof ETSTuple +} +if (!nodeByType.has(81)) { + nodeByType.set(81, ETSTuple) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSTypeReference.ts b/koala-wrapper/src/generated/peers/ETSTypeReference.ts new file mode 100644 index 000000000..f18f4c8b3 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSTypeReference.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { ETSTypeReferencePart } from "./ETSTypeReferencePart" +import { Identifier } from "./Identifier" +export class ETSTypeReference extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 71) + super(pointer) + + } + static createETSTypeReference(part?: ETSTypeReferencePart): ETSTypeReference { + return new ETSTypeReference(global.generatedEs2panda._CreateETSTypeReference(global.context, passNode(part))) + } + static updateETSTypeReference(original?: ETSTypeReference, part?: ETSTypeReferencePart): ETSTypeReference { + return new ETSTypeReference(global.generatedEs2panda._UpdateETSTypeReference(global.context, passNode(original), passNode(part))) + } + get part(): ETSTypeReferencePart | undefined { + return unpackNode(global.generatedEs2panda._ETSTypeReferencePartConst(global.context, this.peer)) + } +} +export function isETSTypeReference(node: AstNode): node is ETSTypeReference { + return node instanceof ETSTypeReference +} +if (!nodeByType.has(71)) { + nodeByType.set(71, ETSTypeReference) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts b/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts new file mode 100644 index 000000000..804642d30 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +export class ETSTypeReferencePart extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 72) + super(pointer) + + } + static createETSTypeReferencePart(name?: Expression, typeParams?: TSTypeParameterInstantiation, prev?: ETSTypeReferencePart): ETSTypeReferencePart { + return new ETSTypeReferencePart(global.generatedEs2panda._CreateETSTypeReferencePart(global.context, passNode(name), passNode(typeParams), passNode(prev))) + } + static updateETSTypeReferencePart(original?: ETSTypeReferencePart, name?: Expression, typeParams?: TSTypeParameterInstantiation, prev?: ETSTypeReferencePart): ETSTypeReferencePart { + return new ETSTypeReferencePart(global.generatedEs2panda._UpdateETSTypeReferencePart(global.context, passNode(original), passNode(name), passNode(typeParams), passNode(prev))) + } + static create1ETSTypeReferencePart(name?: Expression): ETSTypeReferencePart { + return new ETSTypeReferencePart(global.generatedEs2panda._CreateETSTypeReferencePart1(global.context, passNode(name))) + } + static update1ETSTypeReferencePart(original?: ETSTypeReferencePart, name?: Expression): ETSTypeReferencePart { + return new ETSTypeReferencePart(global.generatedEs2panda._UpdateETSTypeReferencePart1(global.context, passNode(original), passNode(name))) + } + get previous(): ETSTypeReferencePart | undefined { + return unpackNode(global.generatedEs2panda._ETSTypeReferencePartPreviousConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterInstantiation | undefined { + return unpackNode(global.generatedEs2panda._ETSTypeReferencePartTypeParams(global.context, this.peer)) + } + get name(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ETSTypeReferencePartNameConst(global.context, this.peer)) + } +} +export function isETSTypeReferencePart(node: AstNode): node is ETSTypeReferencePart { + return node instanceof ETSTypeReferencePart +} +if (!nodeByType.has(72)) { + nodeByType.set(72, ETSTypeReferencePart) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSUndefinedType.ts b/koala-wrapper/src/generated/peers/ETSUndefinedType.ts new file mode 100644 index 000000000..6f44b6a87 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSUndefinedType.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class ETSUndefinedType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 63) + super(pointer) + + } + static createETSUndefinedType(): ETSUndefinedType { + return new ETSUndefinedType(global.generatedEs2panda._CreateETSUndefinedTypeIr(global.context)) + } + static updateETSUndefinedType(original?: ETSUndefinedType): ETSUndefinedType { + return new ETSUndefinedType(global.generatedEs2panda._UpdateETSUndefinedTypeIr(global.context, passNode(original))) + } +} +export function isETSUndefinedType(node: AstNode): node is ETSUndefinedType { + return node instanceof ETSUndefinedType +} +if (!nodeByType.has(63)) { + nodeByType.set(63, ETSUndefinedType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSUnionType.ts b/koala-wrapper/src/generated/peers/ETSUnionType.ts new file mode 100644 index 000000000..18ea1f142 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSUnionType.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class ETSUnionType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 73) + super(pointer) + + } + static createETSUnionType(types: readonly TypeNode[]): ETSUnionType { + return new ETSUnionType(global.generatedEs2panda._CreateETSUnionTypeIr(global.context, passNodeArray(types), types.length)) + } + static updateETSUnionType(original: ETSUnionType | undefined, types: readonly TypeNode[]): ETSUnionType { + return new ETSUnionType(global.generatedEs2panda._UpdateETSUnionTypeIr(global.context, passNode(original), passNodeArray(types), types.length)) + } + get types(): readonly TypeNode[] { + return unpackNodeArray(global.generatedEs2panda._ETSUnionTypeIrTypesConst(global.context, this.peer)) + } +} +export function isETSUnionType(node: AstNode): node is ETSUnionType { + return node instanceof ETSUnionType +} +if (!nodeByType.has(73)) { + nodeByType.set(73, ETSUnionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSWildcardType.ts b/koala-wrapper/src/generated/peers/ETSWildcardType.ts new file mode 100644 index 000000000..7dd790f55 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ETSWildcardType.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { ETSTypeReference } from "./ETSTypeReference" +import { Es2pandaModifierFlags } from "./../Es2pandaEnums" +export class ETSWildcardType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 67) + super(pointer) + + } + static createETSWildcardType(typeReference: ETSTypeReference | undefined, flags: Es2pandaModifierFlags): ETSWildcardType { + return new ETSWildcardType(global.generatedEs2panda._CreateETSWildcardType(global.context, passNode(typeReference), flags)) + } + static updateETSWildcardType(original: ETSWildcardType | undefined, typeReference: ETSTypeReference | undefined, flags: Es2pandaModifierFlags): ETSWildcardType { + return new ETSWildcardType(global.generatedEs2panda._UpdateETSWildcardType(global.context, passNode(original), passNode(typeReference), flags)) + } + get typeReference(): ETSTypeReference | undefined { + return unpackNode(global.generatedEs2panda._ETSWildcardTypeTypeReferenceConst(global.context, this.peer)) + } +} +export function isETSWildcardType(node: AstNode): node is ETSWildcardType { + return node instanceof ETSWildcardType +} +if (!nodeByType.has(67)) { + nodeByType.set(67, ETSWildcardType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/EmptyStatement.ts b/koala-wrapper/src/generated/peers/EmptyStatement.ts new file mode 100644 index 000000000..9e3e61706 --- /dev/null +++ b/koala-wrapper/src/generated/peers/EmptyStatement.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +export class EmptyStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 25) + super(pointer) + + } + static createEmptyStatement(): EmptyStatement { + return new EmptyStatement(global.generatedEs2panda._CreateEmptyStatement(global.context)) + } + static updateEmptyStatement(original?: EmptyStatement): EmptyStatement { + return new EmptyStatement(global.generatedEs2panda._UpdateEmptyStatement(global.context, passNode(original))) + } +} +export function isEmptyStatement(node: AstNode): node is EmptyStatement { + return node instanceof EmptyStatement +} +if (!nodeByType.has(25)) { + nodeByType.set(25, EmptyStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts b/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts new file mode 100644 index 000000000..631cdc354 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { StringLiteral } from "./StringLiteral" +import { Identifier } from "./Identifier" +export class ExportAllDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 26) + super(pointer) + + } + static createExportAllDeclaration(source?: StringLiteral, exported?: Identifier): ExportAllDeclaration { + return new ExportAllDeclaration(global.generatedEs2panda._CreateExportAllDeclaration(global.context, passNode(source), passNode(exported))) + } + static updateExportAllDeclaration(original?: ExportAllDeclaration, source?: StringLiteral, exported?: Identifier): ExportAllDeclaration { + return new ExportAllDeclaration(global.generatedEs2panda._UpdateExportAllDeclaration(global.context, passNode(original), passNode(source), passNode(exported))) + } + get source(): StringLiteral | undefined { + return unpackNode(global.generatedEs2panda._ExportAllDeclarationSourceConst(global.context, this.peer)) + } + get exported(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ExportAllDeclarationExportedConst(global.context, this.peer)) + } +} +export function isExportAllDeclaration(node: AstNode): node is ExportAllDeclaration { + return node instanceof ExportAllDeclaration +} +if (!nodeByType.has(26)) { + nodeByType.set(26, ExportAllDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts b/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts new file mode 100644 index 000000000..d4f07bb62 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +export class ExportDefaultDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 27) + super(pointer) + + } + static createExportDefaultDeclaration(decl: AstNode | undefined, exportEquals: boolean): ExportDefaultDeclaration { + return new ExportDefaultDeclaration(global.generatedEs2panda._CreateExportDefaultDeclaration(global.context, passNode(decl), exportEquals)) + } + static updateExportDefaultDeclaration(original: ExportDefaultDeclaration | undefined, decl: AstNode | undefined, exportEquals: boolean): ExportDefaultDeclaration { + return new ExportDefaultDeclaration(global.generatedEs2panda._UpdateExportDefaultDeclaration(global.context, passNode(original), passNode(decl), exportEquals)) + } + get decl(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._ExportDefaultDeclarationDeclConst(global.context, this.peer)) + } + get isExportEquals(): boolean { + return global.generatedEs2panda._ExportDefaultDeclarationIsExportEqualsConst(global.context, this.peer) + } +} +export function isExportDefaultDeclaration(node: AstNode): node is ExportDefaultDeclaration { + return node instanceof ExportDefaultDeclaration +} +if (!nodeByType.has(27)) { + nodeByType.set(27, ExportDefaultDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts b/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts new file mode 100644 index 000000000..d7f82f76a --- /dev/null +++ b/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { StringLiteral } from "./StringLiteral" +import { ExportSpecifier } from "./ExportSpecifier" +export class ExportNamedDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 28) + super(pointer) + + } + static createExportNamedDeclaration(source: StringLiteral | undefined, specifiers: readonly ExportSpecifier[]): ExportNamedDeclaration { + return new ExportNamedDeclaration(global.generatedEs2panda._CreateExportNamedDeclaration(global.context, passNode(source), passNodeArray(specifiers), specifiers.length)) + } + static updateExportNamedDeclaration(original: ExportNamedDeclaration | undefined, source: StringLiteral | undefined, specifiers: readonly ExportSpecifier[]): ExportNamedDeclaration { + return new ExportNamedDeclaration(global.generatedEs2panda._UpdateExportNamedDeclaration(global.context, passNode(original), passNode(source), passNodeArray(specifiers), specifiers.length)) + } + static create1ExportNamedDeclaration(decl: AstNode | undefined, specifiers: readonly ExportSpecifier[]): ExportNamedDeclaration { + return new ExportNamedDeclaration(global.generatedEs2panda._CreateExportNamedDeclaration1(global.context, passNode(decl), passNodeArray(specifiers), specifiers.length)) + } + static update1ExportNamedDeclaration(original: ExportNamedDeclaration | undefined, decl: AstNode | undefined, specifiers: readonly ExportSpecifier[]): ExportNamedDeclaration { + return new ExportNamedDeclaration(global.generatedEs2panda._UpdateExportNamedDeclaration1(global.context, passNode(original), passNode(decl), passNodeArray(specifiers), specifiers.length)) + } + static create2ExportNamedDeclaration(decl?: AstNode): ExportNamedDeclaration { + return new ExportNamedDeclaration(global.generatedEs2panda._CreateExportNamedDeclaration2(global.context, passNode(decl))) + } + static update2ExportNamedDeclaration(original?: ExportNamedDeclaration, decl?: AstNode): ExportNamedDeclaration { + return new ExportNamedDeclaration(global.generatedEs2panda._UpdateExportNamedDeclaration2(global.context, passNode(original), passNode(decl))) + } + get decl(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._ExportNamedDeclarationDeclConst(global.context, this.peer)) + } + get source(): StringLiteral | undefined { + return unpackNode(global.generatedEs2panda._ExportNamedDeclarationSourceConst(global.context, this.peer)) + } + get specifiers(): readonly ExportSpecifier[] { + return unpackNodeArray(global.generatedEs2panda._ExportNamedDeclarationSpecifiersConst(global.context, this.peer)) + } +} +export function isExportNamedDeclaration(node: AstNode): node is ExportNamedDeclaration { + return node instanceof ExportNamedDeclaration +} +if (!nodeByType.has(28)) { + nodeByType.set(28, ExportNamedDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExportSpecifier.ts b/koala-wrapper/src/generated/peers/ExportSpecifier.ts new file mode 100644 index 000000000..de59281d9 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ExportSpecifier.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Identifier } from "./Identifier" +export class ExportSpecifier extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 29) + super(pointer) + + } + static createExportSpecifier(local?: Identifier, exported?: Identifier): ExportSpecifier { + return new ExportSpecifier(global.generatedEs2panda._CreateExportSpecifier(global.context, passNode(local), passNode(exported))) + } + static updateExportSpecifier(original?: ExportSpecifier, local?: Identifier, exported?: Identifier): ExportSpecifier { + return new ExportSpecifier(global.generatedEs2panda._UpdateExportSpecifier(global.context, passNode(original), passNode(local), passNode(exported))) + } + get local(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ExportSpecifierLocalConst(global.context, this.peer)) + } + get exported(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ExportSpecifierExportedConst(global.context, this.peer)) + } +} +export function isExportSpecifier(node: AstNode): node is ExportSpecifier { + return node instanceof ExportSpecifier +} +if (!nodeByType.has(29)) { + nodeByType.set(29, ExportSpecifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Expression.ts b/koala-wrapper/src/generated/peers/Expression.ts new file mode 100644 index 000000000..9a08ad491 --- /dev/null +++ b/koala-wrapper/src/generated/peers/Expression.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedAstNode } from "./TypedAstNode" +import { Literal } from "./Literal" +import { TypeNode } from "./TypeNode" +import { AnnotatedExpression } from "./AnnotatedExpression" +export class Expression extends TypedAstNode { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get isGrouped(): boolean { + return global.generatedEs2panda._ExpressionIsGroupedConst(global.context, this.peer) + } + /** @deprecated */ + setGrouped(): this { + global.generatedEs2panda._ExpressionSetGrouped(global.context, this.peer) + return this + } + get isLiteral(): boolean { + return global.generatedEs2panda._ExpressionIsLiteralConst(global.context, this.peer) + } + get isTypeNode(): boolean { + return global.generatedEs2panda._ExpressionIsTypeNodeConst(global.context, this.peer) + } + get isAnnotatedExpression(): boolean { + return global.generatedEs2panda._ExpressionIsAnnotatedExpressionConst(global.context, this.peer) + } +} +export function isExpression(node: AstNode): node is Expression { + return node instanceof Expression +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExpressionStatement.ts b/koala-wrapper/src/generated/peers/ExpressionStatement.ts new file mode 100644 index 000000000..6603e673e --- /dev/null +++ b/koala-wrapper/src/generated/peers/ExpressionStatement.ts @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class ExpressionStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 30) + super(pointer) + + } + static createExpressionStatement(expr?: Expression): ExpressionStatement { + return new ExpressionStatement(global.generatedEs2panda._CreateExpressionStatement(global.context, passNode(expr))) + } + static updateExpressionStatement(original?: ExpressionStatement, expr?: Expression): ExpressionStatement { + return new ExpressionStatement(global.generatedEs2panda._UpdateExpressionStatement(global.context, passNode(original), passNode(expr))) + } + get getExpression(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ExpressionStatementGetExpressionConst(global.context, this.peer)) + } + /** @deprecated */ + setExpression(expr: Expression): this { + global.generatedEs2panda._ExpressionStatementSetExpression(global.context, this.peer, passNode(expr)) + return this + } +} +export function isExpressionStatement(node: AstNode): node is ExpressionStatement { + return node instanceof ExpressionStatement +} +if (!nodeByType.has(30)) { + nodeByType.set(30, ExpressionStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ForInStatement.ts b/koala-wrapper/src/generated/peers/ForInStatement.ts new file mode 100644 index 000000000..ff051e35b --- /dev/null +++ b/koala-wrapper/src/generated/peers/ForInStatement.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { LoopStatement } from "./LoopStatement" +import { Expression } from "./Expression" +import { Statement } from "./Statement" +export class ForInStatement extends LoopStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 31) + super(pointer) + + } + static createForInStatement(left?: AstNode, right?: Expression, body?: Statement): ForInStatement { + return new ForInStatement(global.generatedEs2panda._CreateForInStatement(global.context, passNode(left), passNode(right), passNode(body))) + } + static updateForInStatement(original?: ForInStatement, left?: AstNode, right?: Expression, body?: Statement): ForInStatement { + return new ForInStatement(global.generatedEs2panda._UpdateForInStatement(global.context, passNode(original), passNode(left), passNode(right), passNode(body))) + } + get left(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._ForInStatementLeftConst(global.context, this.peer)) + } + get right(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ForInStatementRightConst(global.context, this.peer)) + } + get body(): Statement | undefined { + return unpackNode(global.generatedEs2panda._ForInStatementBodyConst(global.context, this.peer)) + } +} +export function isForInStatement(node: AstNode): node is ForInStatement { + return node instanceof ForInStatement +} +if (!nodeByType.has(31)) { + nodeByType.set(31, ForInStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ForOfStatement.ts b/koala-wrapper/src/generated/peers/ForOfStatement.ts new file mode 100644 index 000000000..801178fd3 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ForOfStatement.ts @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { LoopStatement } from "./LoopStatement" +import { Expression } from "./Expression" +import { Statement } from "./Statement" +export class ForOfStatement extends LoopStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 32) + super(pointer) + + } + static createForOfStatement(left: AstNode | undefined, right: Expression | undefined, body: Statement | undefined, isAwait: boolean): ForOfStatement { + return new ForOfStatement(global.generatedEs2panda._CreateForOfStatement(global.context, passNode(left), passNode(right), passNode(body), isAwait)) + } + static updateForOfStatement(original: ForOfStatement | undefined, left: AstNode | undefined, right: Expression | undefined, body: Statement | undefined, isAwait: boolean): ForOfStatement { + return new ForOfStatement(global.generatedEs2panda._UpdateForOfStatement(global.context, passNode(original), passNode(left), passNode(right), passNode(body), isAwait)) + } + get left(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._ForOfStatementLeftConst(global.context, this.peer)) + } + get right(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ForOfStatementRightConst(global.context, this.peer)) + } + get body(): Statement | undefined { + return unpackNode(global.generatedEs2panda._ForOfStatementBodyConst(global.context, this.peer)) + } + get isAwait(): boolean { + return global.generatedEs2panda._ForOfStatementIsAwaitConst(global.context, this.peer) + } +} +export function isForOfStatement(node: AstNode): node is ForOfStatement { + return node instanceof ForOfStatement +} +if (!nodeByType.has(32)) { + nodeByType.set(32, ForOfStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ForUpdateStatement.ts b/koala-wrapper/src/generated/peers/ForUpdateStatement.ts new file mode 100644 index 000000000..dbf5a9686 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ForUpdateStatement.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { LoopStatement } from "./LoopStatement" +import { Expression } from "./Expression" +import { Statement } from "./Statement" +export class ForUpdateStatement extends LoopStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 33) + super(pointer) + + } + static createForUpdateStatement(init?: AstNode, test?: Expression, update?: Expression, body?: Statement): ForUpdateStatement { + return new ForUpdateStatement(global.generatedEs2panda._CreateForUpdateStatement(global.context, passNode(init), passNode(test), passNode(update), passNode(body))) + } + get init(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._ForUpdateStatementInitConst(global.context, this.peer)) + } + get test(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ForUpdateStatementTestConst(global.context, this.peer)) + } + get update(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ForUpdateStatementUpdateConst(global.context, this.peer)) + } + get body(): Statement | undefined { + return unpackNode(global.generatedEs2panda._ForUpdateStatementBodyConst(global.context, this.peer)) + } +} +export function isForUpdateStatement(node: AstNode): node is ForUpdateStatement { + return node instanceof ForUpdateStatement +} +if (!nodeByType.has(33)) { + nodeByType.set(33, ForUpdateStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/FunctionDecl.ts b/koala-wrapper/src/generated/peers/FunctionDecl.ts new file mode 100644 index 000000000..f4ede5520 --- /dev/null +++ b/koala-wrapper/src/generated/peers/FunctionDecl.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { ScriptFunction } from "./ScriptFunction" +export class FunctionDecl extends ScriptFunction { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isFunctionDecl(node: AstNode): node is FunctionDecl { + return node instanceof FunctionDecl +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/FunctionDeclaration.ts b/koala-wrapper/src/generated/peers/FunctionDeclaration.ts new file mode 100644 index 000000000..1265a281a --- /dev/null +++ b/koala-wrapper/src/generated/peers/FunctionDeclaration.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { ScriptFunction } from "./ScriptFunction" +import { AnnotationUsage } from "./AnnotationUsage" +export class FunctionDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 34) + super(pointer) + + } + static createFunctionDeclaration(func: ScriptFunction | undefined, annotations: readonly AnnotationUsage[], isAnonymous: boolean): FunctionDeclaration { + return new FunctionDeclaration(global.generatedEs2panda._CreateFunctionDeclaration(global.context, passNode(func), passNodeArray(annotations), annotations.length, isAnonymous)) + } + static updateFunctionDeclaration(original: FunctionDeclaration | undefined, func: ScriptFunction | undefined, annotations: readonly AnnotationUsage[], isAnonymous: boolean): FunctionDeclaration { + return new FunctionDeclaration(global.generatedEs2panda._UpdateFunctionDeclaration(global.context, passNode(original), passNode(func), passNodeArray(annotations), annotations.length, isAnonymous)) + } + static create1FunctionDeclaration(func: ScriptFunction | undefined, isAnonymous: boolean): FunctionDeclaration { + return new FunctionDeclaration(global.generatedEs2panda._CreateFunctionDeclaration1(global.context, passNode(func), isAnonymous)) + } + static update1FunctionDeclaration(original: FunctionDeclaration | undefined, func: ScriptFunction | undefined, isAnonymous: boolean): FunctionDeclaration { + return new FunctionDeclaration(global.generatedEs2panda._UpdateFunctionDeclaration1(global.context, passNode(original), passNode(func), isAnonymous)) + } + get isAnonymous(): boolean { + return global.generatedEs2panda._FunctionDeclarationIsAnonymousConst(global.context, this.peer) + } + get function(): ScriptFunction | undefined { + return unpackNode(global.generatedEs2panda._FunctionDeclarationFunctionConst(global.context, this.peer)) + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._FunctionDeclarationAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._FunctionDeclarationSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isFunctionDeclaration(node: AstNode): node is FunctionDeclaration { + return node instanceof FunctionDeclaration +} +if (!nodeByType.has(34)) { + nodeByType.set(34, FunctionDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/FunctionExpression.ts b/koala-wrapper/src/generated/peers/FunctionExpression.ts new file mode 100644 index 000000000..d9e2b3886 --- /dev/null +++ b/koala-wrapper/src/generated/peers/FunctionExpression.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { ScriptFunction } from "./ScriptFunction" +import { Identifier } from "./Identifier" +export class FunctionExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 35) + super(pointer) + + } + static createFunctionExpression(func?: ScriptFunction): FunctionExpression { + return new FunctionExpression(global.generatedEs2panda._CreateFunctionExpression(global.context, passNode(func))) + } + static updateFunctionExpression(original?: FunctionExpression, func?: ScriptFunction): FunctionExpression { + return new FunctionExpression(global.generatedEs2panda._UpdateFunctionExpression(global.context, passNode(original), passNode(func))) + } + static create1FunctionExpression(namedExpr?: Identifier, func?: ScriptFunction): FunctionExpression { + return new FunctionExpression(global.generatedEs2panda._CreateFunctionExpression1(global.context, passNode(namedExpr), passNode(func))) + } + static update1FunctionExpression(original?: FunctionExpression, namedExpr?: Identifier, func?: ScriptFunction): FunctionExpression { + return new FunctionExpression(global.generatedEs2panda._UpdateFunctionExpression1(global.context, passNode(original), passNode(namedExpr), passNode(func))) + } + get function(): ScriptFunction | undefined { + return unpackNode(global.generatedEs2panda._FunctionExpressionFunctionConst(global.context, this.peer)) + } + get isAnonymous(): boolean { + return global.generatedEs2panda._FunctionExpressionIsAnonymousConst(global.context, this.peer) + } + get id(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._FunctionExpressionId(global.context, this.peer)) + } +} +export function isFunctionExpression(node: AstNode): node is FunctionExpression { + return node instanceof FunctionExpression +} +if (!nodeByType.has(35)) { + nodeByType.set(35, FunctionExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/FunctionSignature.ts b/koala-wrapper/src/generated/peers/FunctionSignature.ts new file mode 100644 index 000000000..127399ef3 --- /dev/null +++ b/koala-wrapper/src/generated/peers/FunctionSignature.ts @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class FunctionSignature extends ArktsObject { + constructor(pointer: KNativePointer) { + super(pointer) + + } + static createFunctionSignature(typeParams: TSTypeParameterDeclaration | undefined, params: readonly Expression[], returnTypeAnnotation: TypeNode | undefined, hasReceiver: boolean): FunctionSignature { + return new FunctionSignature(global.generatedEs2panda._CreateFunctionSignature(global.context, passNode(typeParams), passNodeArray(params), params.length, passNode(returnTypeAnnotation), hasReceiver)) + } + get params(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._FunctionSignatureParamsConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._FunctionSignatureTypeParamsConst(global.context, this.peer)) + } + /** @deprecated */ + setReturnType(type: TypeNode): this { + global.generatedEs2panda._FunctionSignatureSetReturnType(global.context, this.peer, passNode(type)) + return this + } + get returnType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._FunctionSignatureReturnTypeConst(global.context, this.peer)) + } + get hasReceiver(): boolean { + return global.generatedEs2panda._FunctionSignatureHasReceiverConst(global.context, this.peer) + } +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Identifier.ts b/koala-wrapper/src/generated/peers/Identifier.ts new file mode 100644 index 000000000..042688c12 --- /dev/null +++ b/koala-wrapper/src/generated/peers/Identifier.ts @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { AnnotatedExpression } from "./AnnotatedExpression" +import { TypeNode } from "./TypeNode" +import { Decorator } from "./Decorator" +import { ValidationInfo } from "./ValidationInfo" +export class Identifier extends AnnotatedExpression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 36) + super(pointer) + + } + static createIdentifier(): Identifier { + return new Identifier(global.generatedEs2panda._CreateIdentifier(global.context)) + } + static updateIdentifier(original?: Identifier): Identifier { + return new Identifier(global.generatedEs2panda._UpdateIdentifier(global.context, passNode(original))) + } + static create1Identifier(name: string): Identifier { + return new Identifier(global.generatedEs2panda._CreateIdentifier1(global.context, name)) + } + static update1Identifier(original: Identifier | undefined, name: string): Identifier { + return new Identifier(global.generatedEs2panda._UpdateIdentifier1(global.context, passNode(original), name)) + } + static create2Identifier(name: string, typeAnnotation?: TypeNode): Identifier { + return new Identifier(global.generatedEs2panda._CreateIdentifier2(global.context, name, passNode(typeAnnotation))) + } + static update2Identifier(original: Identifier | undefined, name: string, typeAnnotation?: TypeNode): Identifier { + return new Identifier(global.generatedEs2panda._UpdateIdentifier2(global.context, passNode(original), name, passNode(typeAnnotation))) + } + get name(): string { + return unpackString(global.generatedEs2panda._IdentifierNameConst(global.context, this.peer)) + } + /** @deprecated */ + setName(newName: string): this { + global.generatedEs2panda._IdentifierSetName(global.context, this.peer, newName) + return this + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._IdentifierDecoratorsConst(global.context, this.peer)) + } + get isErrorPlaceHolder(): boolean { + return global.generatedEs2panda._IdentifierIsErrorPlaceHolderConst(global.context, this.peer) + } + get isOptional(): boolean { + return global.generatedEs2panda._IdentifierIsOptionalConst(global.context, this.peer) + } + /** @deprecated */ + setOptional(optional_arg: boolean): this { + global.generatedEs2panda._IdentifierSetOptional(global.context, this.peer, optional_arg) + return this + } + get isReference(): boolean { + return global.generatedEs2panda._IdentifierIsReferenceConst(global.context, this.peer) + } + get isTdz(): boolean { + return global.generatedEs2panda._IdentifierIsTdzConst(global.context, this.peer) + } + /** @deprecated */ + setTdz(): this { + global.generatedEs2panda._IdentifierSetTdz(global.context, this.peer) + return this + } + /** @deprecated */ + setAccessor(): this { + global.generatedEs2panda._IdentifierSetAccessor(global.context, this.peer) + return this + } + get isAccessor(): boolean { + return global.generatedEs2panda._IdentifierIsAccessorConst(global.context, this.peer) + } + /** @deprecated */ + setMutator(): this { + global.generatedEs2panda._IdentifierSetMutator(global.context, this.peer) + return this + } + get isMutator(): boolean { + return global.generatedEs2panda._IdentifierIsMutatorConst(global.context, this.peer) + } + get isReceiver(): boolean { + return global.generatedEs2panda._IdentifierIsReceiverConst(global.context, this.peer) + } + get isPrivateIdent(): boolean { + return global.generatedEs2panda._IdentifierIsPrivateIdentConst(global.context, this.peer) + } + /** @deprecated */ + setPrivate(isPrivate: boolean): this { + global.generatedEs2panda._IdentifierSetPrivate(global.context, this.peer, isPrivate) + return this + } + get isIgnoreBox(): boolean { + return global.generatedEs2panda._IdentifierIsIgnoreBoxConst(global.context, this.peer) + } + /** @deprecated */ + setIgnoreBox(): this { + global.generatedEs2panda._IdentifierSetIgnoreBox(global.context, this.peer) + return this + } + get isAnnotationDecl(): boolean { + return global.generatedEs2panda._IdentifierIsAnnotationDeclConst(global.context, this.peer) + } + /** @deprecated */ + setAnnotationDecl(): this { + global.generatedEs2panda._IdentifierSetAnnotationDecl(global.context, this.peer) + return this + } + get isAnnotationUsage(): boolean { + return global.generatedEs2panda._IdentifierIsAnnotationUsageConst(global.context, this.peer) + } + /** @deprecated */ + setAnnotationUsage(): this { + global.generatedEs2panda._IdentifierSetAnnotationUsage(global.context, this.peer) + return this + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._IdentifierTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._IdentifierSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } +} +export function isIdentifier(node: AstNode): node is Identifier { + return node instanceof Identifier +} +if (!nodeByType.has(36)) { + nodeByType.set(36, Identifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/IfStatement.ts b/koala-wrapper/src/generated/peers/IfStatement.ts new file mode 100644 index 000000000..056f095f6 --- /dev/null +++ b/koala-wrapper/src/generated/peers/IfStatement.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class IfStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 38) + super(pointer) + + } + static createIfStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement { + return new IfStatement(global.generatedEs2panda._CreateIfStatement(global.context, passNode(test), passNode(consequent), passNode(alternate))) + } + static updateIfStatement(original?: IfStatement, test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement { + return new IfStatement(global.generatedEs2panda._UpdateIfStatement(global.context, passNode(original), passNode(test), passNode(consequent), passNode(alternate))) + } + get test(): Expression | undefined { + return unpackNode(global.generatedEs2panda._IfStatementTestConst(global.context, this.peer)) + } + get consequent(): Statement | undefined { + return unpackNode(global.generatedEs2panda._IfStatementConsequentConst(global.context, this.peer)) + } + get alternate(): Statement | undefined { + return unpackNode(global.generatedEs2panda._IfStatementAlternateConst(global.context, this.peer)) + } +} +export function isIfStatement(node: AstNode): node is IfStatement { + return node instanceof IfStatement +} +if (!nodeByType.has(38)) { + nodeByType.set(38, IfStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportDeclaration.ts b/koala-wrapper/src/generated/peers/ImportDeclaration.ts new file mode 100644 index 000000000..3ce4b85d1 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ImportDeclaration.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { StringLiteral } from "./StringLiteral" +import { Es2pandaImportKinds } from "./../Es2pandaEnums" +export class ImportDeclaration extends Statement { + constructor(pointer: KNativePointer) { + // assertValidPeer(pointer, 39) + super(pointer) + + } + static createImportDeclaration(source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds): ImportDeclaration { + return new ImportDeclaration(global.generatedEs2panda._CreateImportDeclaration(global.context, passNode(source), passNodeArray(specifiers), specifiers.length, importKind)) + } + static updateImportDeclaration(original: ImportDeclaration | undefined, source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds): ImportDeclaration { + return new ImportDeclaration(global.generatedEs2panda._UpdateImportDeclaration(global.context, passNode(original), passNode(source), passNodeArray(specifiers), specifiers.length, importKind)) + } + get source(): StringLiteral | undefined { + return unpackNode(global.generatedEs2panda._ImportDeclarationSourceConst(global.context, this.peer)) + } + get specifiers(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._ImportDeclarationSpecifiersConst(global.context, this.peer)) + } + get isTypeKind(): boolean { + return global.generatedEs2panda._ImportDeclarationIsTypeKindConst(global.context, this.peer) + } +} +export function isImportDeclaration(node: AstNode): node is ImportDeclaration { + return node instanceof ImportDeclaration +} +if (!nodeByType.has(39)) { + nodeByType.set(39, ImportDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts b/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts new file mode 100644 index 000000000..5b4ce34e9 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Identifier } from "./Identifier" +export class ImportDefaultSpecifier extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 41) + super(pointer) + + } + static createImportDefaultSpecifier(local?: Identifier): ImportDefaultSpecifier { + return new ImportDefaultSpecifier(global.generatedEs2panda._CreateImportDefaultSpecifier(global.context, passNode(local))) + } + static updateImportDefaultSpecifier(original?: ImportDefaultSpecifier, local?: Identifier): ImportDefaultSpecifier { + return new ImportDefaultSpecifier(global.generatedEs2panda._UpdateImportDefaultSpecifier(global.context, passNode(original), passNode(local))) + } + get local(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ImportDefaultSpecifierLocalConst(global.context, this.peer)) + } +} +export function isImportDefaultSpecifier(node: AstNode): node is ImportDefaultSpecifier { + return node instanceof ImportDefaultSpecifier +} +if (!nodeByType.has(41)) { + nodeByType.set(41, ImportDefaultSpecifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportExpression.ts b/koala-wrapper/src/generated/peers/ImportExpression.ts new file mode 100644 index 000000000..fc70fd1cb --- /dev/null +++ b/koala-wrapper/src/generated/peers/ImportExpression.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class ImportExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 40) + super(pointer) + + } + static createImportExpression(source?: Expression): ImportExpression { + return new ImportExpression(global.generatedEs2panda._CreateImportExpression(global.context, passNode(source))) + } + static updateImportExpression(original?: ImportExpression, source?: Expression): ImportExpression { + return new ImportExpression(global.generatedEs2panda._UpdateImportExpression(global.context, passNode(original), passNode(source))) + } + get source(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ImportExpressionSourceConst(global.context, this.peer)) + } +} +export function isImportExpression(node: AstNode): node is ImportExpression { + return node instanceof ImportExpression +} +if (!nodeByType.has(40)) { + nodeByType.set(40, ImportExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts b/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts new file mode 100644 index 000000000..4f1e128bf --- /dev/null +++ b/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Identifier } from "./Identifier" +export class ImportNamespaceSpecifier extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 42) + super(pointer) + + } + static createImportNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier { + return new ImportNamespaceSpecifier(global.generatedEs2panda._CreateImportNamespaceSpecifier(global.context, passNode(local))) + } + static updateImportNamespaceSpecifier(original?: ImportNamespaceSpecifier, local?: Identifier): ImportNamespaceSpecifier { + return new ImportNamespaceSpecifier(global.generatedEs2panda._UpdateImportNamespaceSpecifier(global.context, passNode(original), passNode(local))) + } + get local(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ImportNamespaceSpecifierLocalConst(global.context, this.peer)) + } +} +export function isImportNamespaceSpecifier(node: AstNode): node is ImportNamespaceSpecifier { + return node instanceof ImportNamespaceSpecifier +} +if (!nodeByType.has(42)) { + nodeByType.set(42, ImportNamespaceSpecifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportSource.ts b/koala-wrapper/src/generated/peers/ImportSource.ts new file mode 100644 index 000000000..70c8fb289 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ImportSource.ts @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { StringLiteral } from "./StringLiteral" +export class ImportSource extends ArktsObject { + constructor(pointer: KNativePointer) { + super(pointer) + + } + static createImportSource(source: StringLiteral | undefined, resolvedSource: StringLiteral | undefined, hasDecl: boolean): ImportSource { + return new ImportSource(global.generatedEs2panda._CreateImportSource(global.context, passNode(source), passNode(resolvedSource), hasDecl)) + } + get source(): StringLiteral | undefined { + return unpackNode(global.generatedEs2panda._ImportSourceSourceConst(global.context, this.peer)) + } + get resolvedSource(): StringLiteral | undefined { + return unpackNode(global.generatedEs2panda._ImportSourceResolvedSourceConst(global.context, this.peer)) + } + get hasDecl(): boolean { + return global.generatedEs2panda._ImportSourceHasDeclConst(global.context, this.peer) + } +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportSpecifier.ts b/koala-wrapper/src/generated/peers/ImportSpecifier.ts new file mode 100644 index 000000000..e2d49f139 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ImportSpecifier.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Identifier } from "./Identifier" +export class ImportSpecifier extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 43) + super(pointer) + + } + static createImportSpecifier(imported?: Identifier, local?: Identifier): ImportSpecifier { + return new ImportSpecifier(global.generatedEs2panda._CreateImportSpecifier(global.context, passNode(imported), passNode(local))) + } + static updateImportSpecifier(original?: ImportSpecifier, imported?: Identifier, local?: Identifier): ImportSpecifier { + return new ImportSpecifier(global.generatedEs2panda._UpdateImportSpecifier(global.context, passNode(original), passNode(imported), passNode(local))) + } + get imported(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ImportSpecifierImportedConst(global.context, this.peer)) + } + get local(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ImportSpecifierLocalConst(global.context, this.peer)) + } +} +export function isImportSpecifier(node: AstNode): node is ImportSpecifier { + return node instanceof ImportSpecifier +} +if (!nodeByType.has(43)) { + nodeByType.set(43, ImportSpecifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/InterfaceDecl.ts b/koala-wrapper/src/generated/peers/InterfaceDecl.ts new file mode 100644 index 000000000..3e708c7f9 --- /dev/null +++ b/koala-wrapper/src/generated/peers/InterfaceDecl.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TSInterfaceDeclaration } from "./TSInterfaceDeclaration" +export class InterfaceDecl extends TSInterfaceDeclaration { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isInterfaceDecl(node: AstNode): node is InterfaceDecl { + return node instanceof InterfaceDecl +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/LabelledStatement.ts b/koala-wrapper/src/generated/peers/LabelledStatement.ts new file mode 100644 index 000000000..7dec2f9ee --- /dev/null +++ b/koala-wrapper/src/generated/peers/LabelledStatement.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Identifier } from "./Identifier" +export class LabelledStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 44) + super(pointer) + + } + static createLabelledStatement(ident?: Identifier, body?: Statement): LabelledStatement { + return new LabelledStatement(global.generatedEs2panda._CreateLabelledStatement(global.context, passNode(ident), passNode(body))) + } + static updateLabelledStatement(original?: LabelledStatement, ident?: Identifier, body?: Statement): LabelledStatement { + return new LabelledStatement(global.generatedEs2panda._UpdateLabelledStatement(global.context, passNode(original), passNode(ident), passNode(body))) + } + get body(): Statement | undefined { + return unpackNode(global.generatedEs2panda._LabelledStatementBodyConst(global.context, this.peer)) + } + get ident(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._LabelledStatementIdentConst(global.context, this.peer)) + } +} +export function isLabelledStatement(node: AstNode): node is LabelledStatement { + return node instanceof LabelledStatement +} +if (!nodeByType.has(44)) { + nodeByType.set(44, LabelledStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Literal.ts b/koala-wrapper/src/generated/peers/Literal.ts new file mode 100644 index 000000000..76b9e6681 --- /dev/null +++ b/koala-wrapper/src/generated/peers/Literal.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class Literal extends Expression { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isLiteral(node: AstNode): node is Literal { + return node instanceof Literal +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/LoopStatement.ts b/koala-wrapper/src/generated/peers/LoopStatement.ts new file mode 100644 index 000000000..eaed67cf3 --- /dev/null +++ b/koala-wrapper/src/generated/peers/LoopStatement.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +export class LoopStatement extends Statement { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isLoopStatement(node: AstNode): node is LoopStatement { + return node instanceof LoopStatement +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/MaybeOptionalExpression.ts b/koala-wrapper/src/generated/peers/MaybeOptionalExpression.ts new file mode 100644 index 000000000..b02bcf152 --- /dev/null +++ b/koala-wrapper/src/generated/peers/MaybeOptionalExpression.ts @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class MaybeOptionalExpression extends Expression { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get isOptional(): boolean { + return global.generatedEs2panda._MaybeOptionalExpressionIsOptionalConst(global.context, this.peer) + } + /** @deprecated */ + clearOptional(): this { + global.generatedEs2panda._MaybeOptionalExpressionClearOptional(global.context, this.peer) + return this + } +} +export function isMaybeOptionalExpression(node: AstNode): node is MaybeOptionalExpression { + return node instanceof MaybeOptionalExpression +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/MemberExpression.ts b/koala-wrapper/src/generated/peers/MemberExpression.ts new file mode 100644 index 000000000..40f74fe00 --- /dev/null +++ b/koala-wrapper/src/generated/peers/MemberExpression.ts @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { MaybeOptionalExpression } from "./MaybeOptionalExpression" +import { Expression } from "./Expression" +import { Es2pandaMemberExpressionKind } from "./../Es2pandaEnums" +export class MemberExpression extends MaybeOptionalExpression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 45) + super(pointer) + + } + static createMemberExpression(object_arg: Expression | undefined, property: Expression | undefined, kind: Es2pandaMemberExpressionKind, computed: boolean, optional_arg: boolean): MemberExpression { + return new MemberExpression(global.generatedEs2panda._CreateMemberExpression(global.context, passNode(object_arg), passNode(property), kind, computed, optional_arg)) + } + static updateMemberExpression(original: MemberExpression | undefined, object_arg: Expression | undefined, property: Expression | undefined, kind: Es2pandaMemberExpressionKind, computed: boolean, optional_arg: boolean): MemberExpression { + return new MemberExpression(global.generatedEs2panda._UpdateMemberExpression(global.context, passNode(original), passNode(object_arg), passNode(property), kind, computed, optional_arg)) + } + get object(): Expression | undefined { + return unpackNode(global.generatedEs2panda._MemberExpressionObjectConst(global.context, this.peer)) + } + /** @deprecated */ + setObject(object_arg: Expression): this { + global.generatedEs2panda._MemberExpressionSetObject(global.context, this.peer, passNode(object_arg)) + return this + } + /** @deprecated */ + setProperty(prop: Expression): this { + global.generatedEs2panda._MemberExpressionSetProperty(global.context, this.peer, passNode(prop)) + return this + } + get property(): Expression | undefined { + return unpackNode(global.generatedEs2panda._MemberExpressionPropertyConst(global.context, this.peer)) + } + get isComputed(): boolean { + return global.generatedEs2panda._MemberExpressionIsComputedConst(global.context, this.peer) + } + get kind(): Es2pandaMemberExpressionKind { + return global.generatedEs2panda._MemberExpressionKindConst(global.context, this.peer) + } + /** @deprecated */ + addMemberKind(kind: Es2pandaMemberExpressionKind): this { + global.generatedEs2panda._MemberExpressionAddMemberKind(global.context, this.peer, kind) + return this + } + /** @deprecated */ + removeMemberKind(kind: Es2pandaMemberExpressionKind): this { + global.generatedEs2panda._MemberExpressionRemoveMemberKind(global.context, this.peer, kind) + return this + } + get isIgnoreBox(): boolean { + return global.generatedEs2panda._MemberExpressionIsIgnoreBoxConst(global.context, this.peer) + } + /** @deprecated */ + setIgnoreBox(): this { + global.generatedEs2panda._MemberExpressionSetIgnoreBox(global.context, this.peer) + return this + } +} +export function isMemberExpression(node: AstNode): node is MemberExpression { + return node instanceof MemberExpression +} +if (!nodeByType.has(45)) { + nodeByType.set(45, MemberExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/MetaProperty.ts b/koala-wrapper/src/generated/peers/MetaProperty.ts new file mode 100644 index 000000000..82c8bc8ae --- /dev/null +++ b/koala-wrapper/src/generated/peers/MetaProperty.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Es2pandaMetaPropertyKind } from "./../Es2pandaEnums" +export class MetaProperty extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 46) + super(pointer) + + } + static createMetaProperty(kind: Es2pandaMetaPropertyKind): MetaProperty { + return new MetaProperty(global.generatedEs2panda._CreateMetaProperty(global.context, kind)) + } + static updateMetaProperty(original: MetaProperty | undefined, kind: Es2pandaMetaPropertyKind): MetaProperty { + return new MetaProperty(global.generatedEs2panda._UpdateMetaProperty(global.context, passNode(original), kind)) + } + get kind(): Es2pandaMetaPropertyKind { + return global.generatedEs2panda._MetaPropertyKindConst(global.context, this.peer) + } +} +export function isMetaProperty(node: AstNode): node is MetaProperty { + return node instanceof MetaProperty +} +if (!nodeByType.has(46)) { + nodeByType.set(46, MetaProperty) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/MethodDefinition.ts b/koala-wrapper/src/generated/peers/MethodDefinition.ts new file mode 100644 index 000000000..40dd13888 --- /dev/null +++ b/koala-wrapper/src/generated/peers/MethodDefinition.ts @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { ClassElement } from "./ClassElement" +import { Es2pandaMethodDefinitionKind } from "./../Es2pandaEnums" +import { Expression } from "./Expression" +import { Es2pandaModifierFlags } from "./../Es2pandaEnums" +import { ScriptFunction } from "./ScriptFunction" +export class MethodDefinition extends ClassElement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 47) + super(pointer) + + } + static createMethodDefinition(kind: Es2pandaMethodDefinitionKind, key: Expression | undefined, value: Expression | undefined, modifiers: Es2pandaModifierFlags, isComputed: boolean): MethodDefinition { + return new MethodDefinition(global.generatedEs2panda._CreateMethodDefinition(global.context, kind, passNode(key), passNode(value), modifiers, isComputed)) + } + static updateMethodDefinition(original: MethodDefinition | undefined, kind: Es2pandaMethodDefinitionKind, key: Expression | undefined, value: Expression | undefined, modifiers: Es2pandaModifierFlags, isComputed: boolean): MethodDefinition { + return new MethodDefinition(global.generatedEs2panda._UpdateMethodDefinition(global.context, passNode(original), kind, passNode(key), passNode(value), modifiers, isComputed)) + } + get kind(): Es2pandaMethodDefinitionKind { + return global.generatedEs2panda._MethodDefinitionKindConst(global.context, this.peer) + } + get isConstructor(): boolean { + return global.generatedEs2panda._MethodDefinitionIsConstructorConst(global.context, this.peer) + } + get isExtensionMethod(): boolean { + return global.generatedEs2panda._MethodDefinitionIsExtensionMethodConst(global.context, this.peer) + } + get overloads(): readonly MethodDefinition[] { + return unpackNodeArray(global.generatedEs2panda._MethodDefinitionOverloadsConst(global.context, this.peer)) + } + get baseOverloadMethod(): MethodDefinition | undefined { + return unpackNode(global.generatedEs2panda._MethodDefinitionBaseOverloadMethodConst(global.context, this.peer)) + } + get asyncPairMethod(): MethodDefinition | undefined { + return unpackNode(global.generatedEs2panda._MethodDefinitionAsyncPairMethodConst(global.context, this.peer)) + } + /** @deprecated */ + setOverloads(overloads: readonly MethodDefinition[]): this { + global.generatedEs2panda._MethodDefinitionSetOverloads(global.context, this.peer, passNodeArray(overloads), overloads.length) + return this + } + /** @deprecated */ + clearOverloads(): this { + global.generatedEs2panda._MethodDefinitionClearOverloads(global.context, this.peer) + return this + } + /** @deprecated */ + addOverload(overload: MethodDefinition): this { + global.generatedEs2panda._MethodDefinitionAddOverload(global.context, this.peer, passNode(overload)) + return this + } + /** @deprecated */ + setBaseOverloadMethod(baseOverloadMethod: MethodDefinition): this { + global.generatedEs2panda._MethodDefinitionSetBaseOverloadMethod(global.context, this.peer, passNode(baseOverloadMethod)) + return this + } + /** @deprecated */ + setAsyncPairMethod(method: MethodDefinition): this { + global.generatedEs2panda._MethodDefinitionSetAsyncPairMethod(global.context, this.peer, passNode(method)) + return this + } +} +export function isMethodDefinition(node: AstNode): node is MethodDefinition { + return node instanceof MethodDefinition +} +if (!nodeByType.has(47)) { + nodeByType.set(47, MethodDefinition) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/NamedType.ts b/koala-wrapper/src/generated/peers/NamedType.ts new file mode 100644 index 000000000..ce6ee368e --- /dev/null +++ b/koala-wrapper/src/generated/peers/NamedType.ts @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Identifier } from "./Identifier" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +export class NamedType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 48) + super(pointer) + + } + static createNamedType(name?: Identifier): NamedType { + return new NamedType(global.generatedEs2panda._CreateNamedType(global.context, passNode(name))) + } + static updateNamedType(original?: NamedType, name?: Identifier): NamedType { + return new NamedType(global.generatedEs2panda._UpdateNamedType(global.context, passNode(original), passNode(name))) + } + get name(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._NamedTypeNameConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterInstantiation | undefined { + return unpackNode(global.generatedEs2panda._NamedTypeTypeParamsConst(global.context, this.peer)) + } + get isNullable(): boolean { + return global.generatedEs2panda._NamedTypeIsNullableConst(global.context, this.peer) + } + /** @deprecated */ + setNullable(nullable: boolean): this { + global.generatedEs2panda._NamedTypeSetNullable(global.context, this.peer, nullable) + return this + } + /** @deprecated */ + setNext(next: NamedType): this { + global.generatedEs2panda._NamedTypeSetNext(global.context, this.peer, passNode(next)) + return this + } + /** @deprecated */ + setTypeParams(typeParams: TSTypeParameterInstantiation): this { + global.generatedEs2panda._NamedTypeSetTypeParams(global.context, this.peer, passNode(typeParams)) + return this + } +} +export function isNamedType(node: AstNode): node is NamedType { + return node instanceof NamedType +} +if (!nodeByType.has(48)) { + nodeByType.set(48, NamedType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/NewExpression.ts b/koala-wrapper/src/generated/peers/NewExpression.ts new file mode 100644 index 000000000..c267a581d --- /dev/null +++ b/koala-wrapper/src/generated/peers/NewExpression.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class NewExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 49) + super(pointer) + + } + static createNewExpression(callee: Expression | undefined, _arguments: readonly Expression[]): NewExpression { + return new NewExpression(global.generatedEs2panda._CreateNewExpression(global.context, passNode(callee), passNodeArray(_arguments), _arguments.length)) + } + static updateNewExpression(original: NewExpression | undefined, callee: Expression | undefined, _arguments: readonly Expression[]): NewExpression { + return new NewExpression(global.generatedEs2panda._UpdateNewExpression(global.context, passNode(original), passNode(callee), passNodeArray(_arguments), _arguments.length)) + } + get callee(): Expression | undefined { + return unpackNode(global.generatedEs2panda._NewExpressionCalleeConst(global.context, this.peer)) + } + get arguments(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._NewExpressionArgumentsConst(global.context, this.peer)) + } +} +export function isNewExpression(node: AstNode): node is NewExpression { + return node instanceof NewExpression +} +if (!nodeByType.has(49)) { + nodeByType.set(49, NewExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/NullLiteral.ts b/koala-wrapper/src/generated/peers/NullLiteral.ts new file mode 100644 index 000000000..a8047b711 --- /dev/null +++ b/koala-wrapper/src/generated/peers/NullLiteral.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Literal } from "./Literal" +export class NullLiteral extends Literal { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 50) + super(pointer) + + } + static createNullLiteral(): NullLiteral { + return new NullLiteral(global.generatedEs2panda._CreateNullLiteral(global.context)) + } + static updateNullLiteral(original?: NullLiteral): NullLiteral { + return new NullLiteral(global.generatedEs2panda._UpdateNullLiteral(global.context, passNode(original))) + } +} +export function isNullLiteral(node: AstNode): node is NullLiteral { + return node instanceof NullLiteral +} +if (!nodeByType.has(50)) { + nodeByType.set(50, NullLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/NumberLiteral.ts b/koala-wrapper/src/generated/peers/NumberLiteral.ts new file mode 100644 index 000000000..e14e174d9 --- /dev/null +++ b/koala-wrapper/src/generated/peers/NumberLiteral.ts @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Literal } from "./Literal" +export class NumberLiteral extends Literal { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 52) + super(pointer) + + } + get str(): string { + return unpackString(global.generatedEs2panda._NumberLiteralStrConst(global.context, this.peer)) + } +} +export function isNumberLiteral(node: AstNode): node is NumberLiteral { + return node instanceof NumberLiteral +} +if (!nodeByType.has(52)) { + nodeByType.set(52, NumberLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ObjectExpression.ts b/koala-wrapper/src/generated/peers/ObjectExpression.ts new file mode 100644 index 000000000..3c008e515 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ObjectExpression.ts @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { AnnotatedExpression } from "./AnnotatedExpression" +import { Expression } from "./Expression" +import { Decorator } from "./Decorator" +import { ValidationInfo } from "./ValidationInfo" +import { TypeNode } from "./TypeNode" +import { Es2pandaObjectTypeKind } from "../Es2pandaEnums" +import { Property } from "./Property" +export class ObjectExpression extends AnnotatedExpression { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get properties(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._ObjectExpressionPropertiesConst(global.context, this.peer)) + } + get isDeclaration(): boolean { + return global.generatedEs2panda._ObjectExpressionIsDeclarationConst(global.context, this.peer) + } + get isOptional(): boolean { + return global.generatedEs2panda._ObjectExpressionIsOptionalConst(global.context, this.peer) + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._ObjectExpressionDecoratorsConst(global.context, this.peer)) + } + /** @deprecated */ + setDeclaration(): this { + global.generatedEs2panda._ObjectExpressionSetDeclaration(global.context, this.peer) + return this + } + /** @deprecated */ + setOptional(optional_arg: boolean): this { + global.generatedEs2panda._ObjectExpressionSetOptional(global.context, this.peer, optional_arg) + return this + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._ObjectExpressionTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._ObjectExpressionSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } + static createObjectExpression(nodeType: Es2pandaAstNodeType, properties: Property[], trailingComma: boolean): ObjectExpression { + return new ObjectExpression(global.generatedEs2panda._CreateObjectExpression(global.context, nodeType, passNodeArray(properties), properties.length, trailingComma)) + } + static updateObjectExpression(original: ObjectExpression, nodeType: Es2pandaAstNodeType, properties: Property[], trailingComma: boolean): ObjectExpression { + return new ObjectExpression(global.generatedEs2panda._UpdateObjectExpression(global.context, passNode(original), nodeType, passNodeArray(properties), properties.length, trailingComma)) + } +} +export function isObjectExpression(node: AstNode): node is ObjectExpression { + return node instanceof ObjectExpression +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/OmittedExpression.ts b/koala-wrapper/src/generated/peers/OmittedExpression.ts new file mode 100644 index 000000000..339202ae3 --- /dev/null +++ b/koala-wrapper/src/generated/peers/OmittedExpression.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class OmittedExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 53) + super(pointer) + + } + static createOmittedExpression(): OmittedExpression { + return new OmittedExpression(global.generatedEs2panda._CreateOmittedExpression(global.context)) + } + static updateOmittedExpression(original?: OmittedExpression): OmittedExpression { + return new OmittedExpression(global.generatedEs2panda._UpdateOmittedExpression(global.context, passNode(original))) + } +} +export function isOmittedExpression(node: AstNode): node is OmittedExpression { + return node instanceof OmittedExpression +} +if (!nodeByType.has(53)) { + nodeByType.set(53, OmittedExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts b/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts new file mode 100644 index 000000000..ba2d646dc --- /dev/null +++ b/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class OpaqueTypeNode extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 154) + super(pointer) + + } + static create1OpaqueTypeNode(): OpaqueTypeNode { + return new OpaqueTypeNode(global.generatedEs2panda._CreateOpaqueTypeNode1(global.context)) + } + static update1OpaqueTypeNode(original?: OpaqueTypeNode): OpaqueTypeNode { + return new OpaqueTypeNode(global.generatedEs2panda._UpdateOpaqueTypeNode1(global.context, passNode(original))) + } +} +export function isOpaqueTypeNode(node: AstNode): node is OpaqueTypeNode { + return node instanceof OpaqueTypeNode +} +if (!nodeByType.has(154)) { + nodeByType.set(154, OpaqueTypeNode) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts b/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts new file mode 100644 index 000000000..03a093531 --- /dev/null +++ b/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class PrefixAssertionExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 54) + super(pointer) + + } + static createPrefixAssertionExpression(expr?: Expression, type?: TypeNode): PrefixAssertionExpression { + return new PrefixAssertionExpression(global.generatedEs2panda._CreatePrefixAssertionExpression(global.context, passNode(expr), passNode(type))) + } + static updatePrefixAssertionExpression(original?: PrefixAssertionExpression, expr?: Expression, type?: TypeNode): PrefixAssertionExpression { + return new PrefixAssertionExpression(global.generatedEs2panda._UpdatePrefixAssertionExpression(global.context, passNode(original), passNode(expr), passNode(type))) + } + get expr(): Expression | undefined { + return unpackNode(global.generatedEs2panda._PrefixAssertionExpressionExprConst(global.context, this.peer)) + } + get type(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._PrefixAssertionExpressionTypeConst(global.context, this.peer)) + } +} +export function isPrefixAssertionExpression(node: AstNode): node is PrefixAssertionExpression { + return node instanceof PrefixAssertionExpression +} +if (!nodeByType.has(54)) { + nodeByType.set(54, PrefixAssertionExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Property.ts b/koala-wrapper/src/generated/peers/Property.ts new file mode 100644 index 000000000..982cb0241 --- /dev/null +++ b/koala-wrapper/src/generated/peers/Property.ts @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Es2pandaPropertyKind } from "./../Es2pandaEnums" +import { ValidationInfo } from "./ValidationInfo" +export class Property extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 55) + super(pointer) + + } + static createProperty(key?: Expression, value?: Expression): Property { + return new Property(global.generatedEs2panda._CreateProperty(global.context, passNode(key), passNode(value))) + } + static updateProperty(original?: Property, key?: Expression, value?: Expression): Property { + return new Property(global.generatedEs2panda._UpdateProperty(global.context, passNode(original), passNode(key), passNode(value))) + } + static create1Property(kind: Es2pandaPropertyKind, key: Expression | undefined, value: Expression | undefined, isMethod: boolean, isComputed: boolean): Property { + return new Property(global.generatedEs2panda._CreateProperty1(global.context, kind, passNode(key), passNode(value), isMethod, isComputed)) + } + static update1Property(original: Property | undefined, kind: Es2pandaPropertyKind, key: Expression | undefined, value: Expression | undefined, isMethod: boolean, isComputed: boolean): Property { + return new Property(global.generatedEs2panda._UpdateProperty1(global.context, passNode(original), kind, passNode(key), passNode(value), isMethod, isComputed)) + } + get key(): Expression | undefined { + return unpackNode(global.generatedEs2panda._PropertyKeyConst(global.context, this.peer)) + } + get value(): Expression | undefined { + return unpackNode(global.generatedEs2panda._PropertyValueConst(global.context, this.peer)) + } + get kind(): Es2pandaPropertyKind { + return global.generatedEs2panda._PropertyKindConst(global.context, this.peer) + } + get isMethod(): boolean { + return global.generatedEs2panda._PropertyIsMethodConst(global.context, this.peer) + } + get isShorthand(): boolean { + return global.generatedEs2panda._PropertyIsShorthandConst(global.context, this.peer) + } + get isComputed(): boolean { + return global.generatedEs2panda._PropertyIsComputedConst(global.context, this.peer) + } + get isAccessor(): boolean { + return global.generatedEs2panda._PropertyIsAccessorConst(global.context, this.peer) + } +} +export function isProperty(node: AstNode): node is Property { + return node instanceof Property +} +if (!nodeByType.has(55)) { + nodeByType.set(55, Property) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/RegExpLiteral.ts b/koala-wrapper/src/generated/peers/RegExpLiteral.ts new file mode 100644 index 000000000..5ae04143b --- /dev/null +++ b/koala-wrapper/src/generated/peers/RegExpLiteral.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Literal } from "./Literal" +import { Es2pandaRegExpFlags } from "./../Es2pandaEnums" +export class RegExpLiteral extends Literal { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 56) + super(pointer) + + } + static createRegExpLiteral(pattern: string, flags: Es2pandaRegExpFlags, flagsStr: string): RegExpLiteral { + return new RegExpLiteral(global.generatedEs2panda._CreateRegExpLiteral(global.context, pattern, flags, flagsStr)) + } + static updateRegExpLiteral(original: RegExpLiteral | undefined, pattern: string, flags: Es2pandaRegExpFlags, flagsStr: string): RegExpLiteral { + return new RegExpLiteral(global.generatedEs2panda._UpdateRegExpLiteral(global.context, passNode(original), pattern, flags, flagsStr)) + } + get pattern(): string { + return unpackString(global.generatedEs2panda._RegExpLiteralPatternConst(global.context, this.peer)) + } + get flags(): Es2pandaRegExpFlags { + return global.generatedEs2panda._RegExpLiteralFlagsConst(global.context, this.peer) + } +} +export function isRegExpLiteral(node: AstNode): node is RegExpLiteral { + return node instanceof RegExpLiteral +} +if (!nodeByType.has(56)) { + nodeByType.set(56, RegExpLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ReturnStatement.ts b/koala-wrapper/src/generated/peers/ReturnStatement.ts new file mode 100644 index 000000000..6489e99df --- /dev/null +++ b/koala-wrapper/src/generated/peers/ReturnStatement.ts @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class ReturnStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 58) + super(pointer) + + } + static createReturnStatement(): ReturnStatement { + return new ReturnStatement(global.generatedEs2panda._CreateReturnStatement(global.context)) + } + static updateReturnStatement(original?: ReturnStatement): ReturnStatement { + return new ReturnStatement(global.generatedEs2panda._UpdateReturnStatement(global.context, passNode(original))) + } + static create1ReturnStatement(argument?: Expression): ReturnStatement { + return new ReturnStatement(global.generatedEs2panda._CreateReturnStatement1(global.context, passNode(argument))) + } + static update1ReturnStatement(original?: ReturnStatement, argument?: Expression): ReturnStatement { + return new ReturnStatement(global.generatedEs2panda._UpdateReturnStatement1(global.context, passNode(original), passNode(argument))) + } + get argument(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ReturnStatementArgumentConst(global.context, this.peer)) + } + /** @deprecated */ + setArgument(arg: Expression): this { + global.generatedEs2panda._ReturnStatementSetArgument(global.context, this.peer, passNode(arg)) + return this + } +} +export function isReturnStatement(node: AstNode): node is ReturnStatement { + return node instanceof ReturnStatement +} +if (!nodeByType.has(58)) { + nodeByType.set(58, ReturnStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ScriptFunction.ts b/koala-wrapper/src/generated/peers/ScriptFunction.ts new file mode 100644 index 000000000..28b262008 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ScriptFunction.ts @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { FunctionSignature } from "./FunctionSignature" +import { Identifier } from "./Identifier" +import { Expression } from "./Expression" +import { ReturnStatement } from "./ReturnStatement" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { TypeNode } from "./TypeNode" +import { Es2pandaScriptFunctionFlags } from "./../Es2pandaEnums" +import { Es2pandaModifierFlags } from "./../Es2pandaEnums" +import { AnnotationUsage } from "./AnnotationUsage" +export class ScriptFunction extends AstNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 59) + super(pointer) + + } + static createScriptFunction(databody: AstNode | undefined, datasignature: FunctionSignature | undefined, datafuncFlags: number, dataflags: number): ScriptFunction { + return new ScriptFunction(global.generatedEs2panda._CreateScriptFunction(global.context, passNode(databody), passNode(datasignature), datafuncFlags, dataflags)) + } + static updateScriptFunction(original: ScriptFunction | undefined, databody: AstNode | undefined, datasignature: FunctionSignature | undefined, datafuncFlags: number, dataflags: number): ScriptFunction { + return new ScriptFunction(global.generatedEs2panda._UpdateScriptFunction(global.context, passNode(original), passNode(databody), passNode(datasignature), datafuncFlags, dataflags)) + } + get id(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._ScriptFunctionIdConst(global.context, this.peer)) + } + get params(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._ScriptFunctionParamsConst(global.context, this.peer)) + } + get returnStatements(): readonly ReturnStatement[] { + return unpackNodeArray(global.generatedEs2panda._ScriptFunctionReturnStatementsConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._ScriptFunctionTypeParamsConst(global.context, this.peer)) + } + get body(): AstNode | undefined { + return unpackNode(global.generatedEs2panda._ScriptFunctionBodyConst(global.context, this.peer)) + } + /** @deprecated */ + addReturnStatement(returnStatement: ReturnStatement): this { + global.generatedEs2panda._ScriptFunctionAddReturnStatement(global.context, this.peer, passNode(returnStatement)) + return this + } + /** @deprecated */ + setBody(body: AstNode): this { + global.generatedEs2panda._ScriptFunctionSetBody(global.context, this.peer, passNode(body)) + return this + } + get returnTypeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._ScriptFunctionReturnTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setReturnTypeAnnotation(node: TypeNode): this { + global.generatedEs2panda._ScriptFunctionSetReturnTypeAnnotation(global.context, this.peer, passNode(node)) + return this + } + get isEntryPoint(): boolean { + return global.generatedEs2panda._ScriptFunctionIsEntryPointConst(global.context, this.peer) + } + get isGenerator(): boolean { + return global.generatedEs2panda._ScriptFunctionIsGeneratorConst(global.context, this.peer) + } + get isAsyncFunc(): boolean { + return global.generatedEs2panda._ScriptFunctionIsAsyncFuncConst(global.context, this.peer) + } + get isAsyncImplFunc(): boolean { + return global.generatedEs2panda._ScriptFunctionIsAsyncImplFuncConst(global.context, this.peer) + } + get isArrow(): boolean { + return global.generatedEs2panda._ScriptFunctionIsArrowConst(global.context, this.peer) + } + get isOverload(): boolean { + return global.generatedEs2panda._ScriptFunctionIsOverloadConst(global.context, this.peer) + } + get isExternalOverload(): boolean { + return global.generatedEs2panda._ScriptFunctionIsExternalOverloadConst(global.context, this.peer) + } + get isConstructor(): boolean { + return global.generatedEs2panda._ScriptFunctionIsConstructorConst(global.context, this.peer) + } + get isGetter(): boolean { + return global.generatedEs2panda._ScriptFunctionIsGetterConst(global.context, this.peer) + } + get isSetter(): boolean { + return global.generatedEs2panda._ScriptFunctionIsSetterConst(global.context, this.peer) + } + get isExtensionAccessor(): boolean { + return global.generatedEs2panda._ScriptFunctionIsExtensionAccessorConst(global.context, this.peer) + } + get isMethod(): boolean { + return global.generatedEs2panda._ScriptFunctionIsMethodConst(global.context, this.peer) + } + get isProxy(): boolean { + return global.generatedEs2panda._ScriptFunctionIsProxyConst(global.context, this.peer) + } + get isStaticBlock(): boolean { + return global.generatedEs2panda._ScriptFunctionIsStaticBlockConst(global.context, this.peer) + } + get isEnum(): boolean { + return global.generatedEs2panda._ScriptFunctionIsEnumConst(global.context, this.peer) + } + get isHidden(): boolean { + return global.generatedEs2panda._ScriptFunctionIsHiddenConst(global.context, this.peer) + } + get isExternal(): boolean { + return global.generatedEs2panda._ScriptFunctionIsExternalConst(global.context, this.peer) + } + get isImplicitSuperCallNeeded(): boolean { + return global.generatedEs2panda._ScriptFunctionIsImplicitSuperCallNeededConst(global.context, this.peer) + } + get hasBody(): boolean { + return global.generatedEs2panda._ScriptFunctionHasBodyConst(global.context, this.peer) + } + get hasRestParameter(): boolean { + return global.generatedEs2panda._ScriptFunctionHasRestParameterConst(global.context, this.peer) + } + get hasReturnStatement(): boolean { + return global.generatedEs2panda._ScriptFunctionHasReturnStatementConst(global.context, this.peer) + } + get hasThrowStatement(): boolean { + return global.generatedEs2panda._ScriptFunctionHasThrowStatementConst(global.context, this.peer) + } + get isThrowing(): boolean { + return global.generatedEs2panda._ScriptFunctionIsThrowingConst(global.context, this.peer) + } + get isRethrowing(): boolean { + return global.generatedEs2panda._ScriptFunctionIsRethrowingConst(global.context, this.peer) + } + get isDynamic(): boolean { + return global.generatedEs2panda._ScriptFunctionIsDynamicConst(global.context, this.peer) + } + get isExtensionMethod(): boolean { + return global.generatedEs2panda._ScriptFunctionIsExtensionMethodConst(global.context, this.peer) + } + get flags(): Es2pandaScriptFunctionFlags { + return global.generatedEs2panda._ScriptFunctionFlagsConst(global.context, this.peer) + } + get hasReceiver(): boolean { + return global.generatedEs2panda._ScriptFunctionHasReceiverConst(global.context, this.peer) + } + /** @deprecated */ + setIdent(id: Identifier): this { + global.generatedEs2panda._ScriptFunctionSetIdent(global.context, this.peer, passNode(id)) + return this + } + /** @deprecated */ + addFlag(flags: Es2pandaScriptFunctionFlags): this { + global.generatedEs2panda._ScriptFunctionAddFlag(global.context, this.peer, flags) + return this + } + /** @deprecated */ + addModifier(flags: Es2pandaModifierFlags): this { + global.generatedEs2panda._ScriptFunctionAddModifier(global.context, this.peer, flags) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._ScriptFunctionAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._ScriptFunctionSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isScriptFunction(node: AstNode): node is ScriptFunction { + return node instanceof ScriptFunction +} +if (!nodeByType.has(59)) { + nodeByType.set(59, ScriptFunction) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SequenceExpression.ts b/koala-wrapper/src/generated/peers/SequenceExpression.ts new file mode 100644 index 000000000..fb0f1a9c0 --- /dev/null +++ b/koala-wrapper/src/generated/peers/SequenceExpression.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class SequenceExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 60) + super(pointer) + + } + static createSequenceExpression(sequence_arg: readonly Expression[]): SequenceExpression { + return new SequenceExpression(global.generatedEs2panda._CreateSequenceExpression(global.context, passNodeArray(sequence_arg), sequence_arg.length)) + } + static updateSequenceExpression(original: SequenceExpression | undefined, sequence_arg: readonly Expression[]): SequenceExpression { + return new SequenceExpression(global.generatedEs2panda._UpdateSequenceExpression(global.context, passNode(original), passNodeArray(sequence_arg), sequence_arg.length)) + } + get sequence(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._SequenceExpressionSequenceConst(global.context, this.peer)) + } +} +export function isSequenceExpression(node: AstNode): node is SequenceExpression { + return node instanceof SequenceExpression +} +if (!nodeByType.has(60)) { + nodeByType.set(60, SequenceExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SpreadElement.ts b/koala-wrapper/src/generated/peers/SpreadElement.ts new file mode 100644 index 000000000..4b721b993 --- /dev/null +++ b/koala-wrapper/src/generated/peers/SpreadElement.ts @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { AnnotatedExpression } from "./AnnotatedExpression" +import { Expression } from "./Expression" +import { Decorator } from "./Decorator" +import { ValidationInfo } from "./ValidationInfo" +import { TypeNode } from "./TypeNode" +export class SpreadElement extends AnnotatedExpression { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get argument(): Expression | undefined { + return unpackNode(global.generatedEs2panda._SpreadElementArgumentConst(global.context, this.peer)) + } + get isOptional(): boolean { + return global.generatedEs2panda._SpreadElementIsOptionalConst(global.context, this.peer) + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._SpreadElementDecoratorsConst(global.context, this.peer)) + } + /** @deprecated */ + setOptional(optional_arg: boolean): this { + global.generatedEs2panda._SpreadElementSetOptional(global.context, this.peer, optional_arg) + return this + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._SpreadElementTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._SpreadElementSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } +} +export function isSpreadElement(node: AstNode): node is SpreadElement { + return node instanceof SpreadElement +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SrcDumper.ts b/koala-wrapper/src/generated/peers/SrcDumper.ts new file mode 100644 index 000000000..cb17a8868 --- /dev/null +++ b/koala-wrapper/src/generated/peers/SrcDumper.ts @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +export class SrcDumper extends ArktsObject { + constructor(pointer: KNativePointer) { + super(pointer) + + } + static createSrcDumper(node?: AstNode): SrcDumper { + return new SrcDumper(global.generatedEs2panda._CreateSrcDumper(global.context, passNode(node))) + } + /** @deprecated */ + add(str: string): this { + global.generatedEs2panda._SrcDumperAdd(global.context, this.peer, str) + return this + } + /** @deprecated */ + add1(i: number): this { + global.generatedEs2panda._SrcDumperAdd1(global.context, this.peer, i) + return this + } + /** @deprecated */ + add2(l: number): this { + global.generatedEs2panda._SrcDumperAdd2(global.context, this.peer, l) + return this + } + /** @deprecated */ + add3(f: number): this { + global.generatedEs2panda._SrcDumperAdd3(global.context, this.peer, f) + return this + } + /** @deprecated */ + add4(d: number): this { + global.generatedEs2panda._SrcDumperAdd4(global.context, this.peer, d) + return this + } + get str(): string { + return unpackString(global.generatedEs2panda._SrcDumperStrConst(global.context, this.peer)) + } + /** @deprecated */ + incrIndent(): this { + global.generatedEs2panda._SrcDumperIncrIndent(global.context, this.peer) + return this + } + /** @deprecated */ + decrIndent(): this { + global.generatedEs2panda._SrcDumperDecrIndent(global.context, this.peer) + return this + } + /** @deprecated */ + endl(num: number): this { + global.generatedEs2panda._SrcDumperEndl(global.context, this.peer, num) + return this + } +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Statement.ts b/koala-wrapper/src/generated/peers/Statement.ts new file mode 100644 index 000000000..ace0ee9dc --- /dev/null +++ b/koala-wrapper/src/generated/peers/Statement.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +export class Statement extends AstNode { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isStatement(node: AstNode): node is Statement { + return node instanceof Statement +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/StringLiteral.ts b/koala-wrapper/src/generated/peers/StringLiteral.ts new file mode 100644 index 000000000..6eed3c9e4 --- /dev/null +++ b/koala-wrapper/src/generated/peers/StringLiteral.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + unpackString +} from "../../reexport-for-generated" + +import { Literal } from "./Literal" +export class StringLiteral extends Literal { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 61) + super(pointer) + + } + static createStringLiteral(): StringLiteral { + return new StringLiteral(global.generatedEs2panda._CreateStringLiteral(global.context)) + } + static updateStringLiteral(original?: StringLiteral): StringLiteral { + return new StringLiteral(global.generatedEs2panda._UpdateStringLiteral(global.context, passNode(original))) + } + static create1StringLiteral(str: string): StringLiteral { + return new StringLiteral(global.generatedEs2panda._CreateStringLiteral1(global.context, str)) + } + static update1StringLiteral(original: StringLiteral | undefined, str: string): StringLiteral { + return new StringLiteral(global.generatedEs2panda._UpdateStringLiteral1(global.context, passNode(original), str)) + } + get str(): string { + return unpackString(global.generatedEs2panda._StringLiteralStrConst(global.context, this.peer)) + } +} +export function isStringLiteral(node: AstNode): node is StringLiteral { + return node instanceof StringLiteral +} +if (!nodeByType.has(61)) { + nodeByType.set(61, StringLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SuperExpression.ts b/koala-wrapper/src/generated/peers/SuperExpression.ts new file mode 100644 index 000000000..57b35074d --- /dev/null +++ b/koala-wrapper/src/generated/peers/SuperExpression.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class SuperExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 83) + super(pointer) + + } + static createSuperExpression(): SuperExpression { + return new SuperExpression(global.generatedEs2panda._CreateSuperExpression(global.context)) + } + static updateSuperExpression(original?: SuperExpression): SuperExpression { + return new SuperExpression(global.generatedEs2panda._UpdateSuperExpression(global.context, passNode(original))) + } +} +export function isSuperExpression(node: AstNode): node is SuperExpression { + return node instanceof SuperExpression +} +if (!nodeByType.has(83)) { + nodeByType.set(83, SuperExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts b/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts new file mode 100644 index 000000000..93ff25f08 --- /dev/null +++ b/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class SwitchCaseStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 85) + super(pointer) + + } + static createSwitchCaseStatement(test: Expression | undefined, consequent: readonly Statement[]): SwitchCaseStatement { + return new SwitchCaseStatement(global.generatedEs2panda._CreateSwitchCaseStatement(global.context, passNode(test), passNodeArray(consequent), consequent.length)) + } + static updateSwitchCaseStatement(original: SwitchCaseStatement | undefined, test: Expression | undefined, consequent: readonly Statement[]): SwitchCaseStatement { + return new SwitchCaseStatement(global.generatedEs2panda._UpdateSwitchCaseStatement(global.context, passNode(original), passNode(test), passNodeArray(consequent), consequent.length)) + } + get test(): Expression | undefined { + return unpackNode(global.generatedEs2panda._SwitchCaseStatementTestConst(global.context, this.peer)) + } + get consequent(): readonly Statement[] { + return unpackNodeArray(global.generatedEs2panda._SwitchCaseStatementConsequentConst(global.context, this.peer)) + } +} +export function isSwitchCaseStatement(node: AstNode): node is SwitchCaseStatement { + return node instanceof SwitchCaseStatement +} +if (!nodeByType.has(85)) { + nodeByType.set(85, SwitchCaseStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SwitchStatement.ts b/koala-wrapper/src/generated/peers/SwitchStatement.ts new file mode 100644 index 000000000..d11afaf4a --- /dev/null +++ b/koala-wrapper/src/generated/peers/SwitchStatement.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +import { SwitchCaseStatement } from "./SwitchCaseStatement" +export class SwitchStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 86) + super(pointer) + + } + static createSwitchStatement(discriminant: Expression | undefined, cases: readonly SwitchCaseStatement[]): SwitchStatement { + return new SwitchStatement(global.generatedEs2panda._CreateSwitchStatement(global.context, passNode(discriminant), passNodeArray(cases), cases.length)) + } + static updateSwitchStatement(original: SwitchStatement | undefined, discriminant: Expression | undefined, cases: readonly SwitchCaseStatement[]): SwitchStatement { + return new SwitchStatement(global.generatedEs2panda._UpdateSwitchStatement(global.context, passNode(original), passNode(discriminant), passNodeArray(cases), cases.length)) + } + get discriminant(): Expression | undefined { + return unpackNode(global.generatedEs2panda._SwitchStatementDiscriminantConst(global.context, this.peer)) + } + get cases(): readonly SwitchCaseStatement[] { + return unpackNodeArray(global.generatedEs2panda._SwitchStatementCasesConst(global.context, this.peer)) + } +} +export function isSwitchStatement(node: AstNode): node is SwitchStatement { + return node instanceof SwitchStatement +} +if (!nodeByType.has(86)) { + nodeByType.set(86, SwitchStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSAnyKeyword.ts b/koala-wrapper/src/generated/peers/TSAnyKeyword.ts new file mode 100644 index 000000000..ffb19bebf --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSAnyKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSAnyKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 91) + super(pointer) + + } + static createTSAnyKeyword(): TSAnyKeyword { + return new TSAnyKeyword(global.generatedEs2panda._CreateTSAnyKeyword(global.context)) + } + static updateTSAnyKeyword(original?: TSAnyKeyword): TSAnyKeyword { + return new TSAnyKeyword(global.generatedEs2panda._UpdateTSAnyKeyword(global.context, passNode(original))) + } +} +export function isTSAnyKeyword(node: AstNode): node is TSAnyKeyword { + return node instanceof TSAnyKeyword +} +if (!nodeByType.has(91)) { + nodeByType.set(91, TSAnyKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSArrayType.ts b/koala-wrapper/src/generated/peers/TSArrayType.ts new file mode 100644 index 000000000..a727d24fc --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSArrayType.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSArrayType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 102) + super(pointer) + + } + static createTSArrayType(elementType?: TypeNode): TSArrayType { + return new TSArrayType(global.generatedEs2panda._CreateTSArrayType(global.context, passNode(elementType))) + } + static updateTSArrayType(original?: TSArrayType, elementType?: TypeNode): TSArrayType { + return new TSArrayType(global.generatedEs2panda._UpdateTSArrayType(global.context, passNode(original), passNode(elementType))) + } + get elementType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSArrayTypeElementTypeConst(global.context, this.peer)) + } +} +export function isTSArrayType(node: AstNode): node is TSArrayType { + return node instanceof TSArrayType +} +if (!nodeByType.has(102)) { + nodeByType.set(102, TSArrayType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSAsExpression.ts b/koala-wrapper/src/generated/peers/TSAsExpression.ts new file mode 100644 index 000000000..718b9427b --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSAsExpression.ts @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { AnnotatedExpression } from "./AnnotatedExpression" +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class TSAsExpression extends AnnotatedExpression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 138) + super(pointer) + + } + static createTSAsExpression(expression: Expression | undefined, typeAnnotation: TypeNode | undefined, isConst: boolean): TSAsExpression { + return new TSAsExpression(global.generatedEs2panda._CreateTSAsExpression(global.context, passNode(expression), passNode(typeAnnotation), isConst)) + } + static updateTSAsExpression(original: TSAsExpression | undefined, expression: Expression | undefined, typeAnnotation: TypeNode | undefined, isConst: boolean): TSAsExpression { + return new TSAsExpression(global.generatedEs2panda._UpdateTSAsExpression(global.context, passNode(original), passNode(expression), passNode(typeAnnotation), isConst)) + } + get expr(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSAsExpressionExprConst(global.context, this.peer)) + } + /** @deprecated */ + setExpr(expr: Expression): this { + global.generatedEs2panda._TSAsExpressionSetExpr(global.context, this.peer, passNode(expr)) + return this + } + get isConst(): boolean { + return global.generatedEs2panda._TSAsExpressionIsConstConst(global.context, this.peer) + } + /** @deprecated */ + setUncheckedCast(isUncheckedCast: boolean): this { + global.generatedEs2panda._TSAsExpressionSetUncheckedCast(global.context, this.peer, isUncheckedCast) + return this + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSAsExpressionTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._TSAsExpressionSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } +} +export function isTSAsExpression(node: AstNode): node is TSAsExpression { + return node instanceof TSAsExpression +} +if (!nodeByType.has(138)) { + nodeByType.set(138, TSAsExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSBigintKeyword.ts b/koala-wrapper/src/generated/peers/TSBigintKeyword.ts new file mode 100644 index 000000000..371719a14 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSBigintKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSBigintKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 98) + super(pointer) + + } + static createTSBigintKeyword(): TSBigintKeyword { + return new TSBigintKeyword(global.generatedEs2panda._CreateTSBigintKeyword(global.context)) + } + static updateTSBigintKeyword(original?: TSBigintKeyword): TSBigintKeyword { + return new TSBigintKeyword(global.generatedEs2panda._UpdateTSBigintKeyword(global.context, passNode(original))) + } +} +export function isTSBigintKeyword(node: AstNode): node is TSBigintKeyword { + return node instanceof TSBigintKeyword +} +if (!nodeByType.has(98)) { + nodeByType.set(98, TSBigintKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts b/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts new file mode 100644 index 000000000..cc4c077b3 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSBooleanKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 93) + super(pointer) + + } + static createTSBooleanKeyword(): TSBooleanKeyword { + return new TSBooleanKeyword(global.generatedEs2panda._CreateTSBooleanKeyword(global.context)) + } + static updateTSBooleanKeyword(original?: TSBooleanKeyword): TSBooleanKeyword { + return new TSBooleanKeyword(global.generatedEs2panda._UpdateTSBooleanKeyword(global.context, passNode(original))) + } +} +export function isTSBooleanKeyword(node: AstNode): node is TSBooleanKeyword { + return node instanceof TSBooleanKeyword +} +if (!nodeByType.has(93)) { + nodeByType.set(93, TSBooleanKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSClassImplements.ts b/koala-wrapper/src/generated/peers/TSClassImplements.ts new file mode 100644 index 000000000..b06a578a1 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSClassImplements.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +export class TSClassImplements extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 139) + super(pointer) + + } + static createTSClassImplements(expression?: Expression, typeParameters?: TSTypeParameterInstantiation): TSClassImplements { + return new TSClassImplements(global.generatedEs2panda._CreateTSClassImplements(global.context, passNode(expression), passNode(typeParameters))) + } + static updateTSClassImplements(original?: TSClassImplements, expression?: Expression, typeParameters?: TSTypeParameterInstantiation): TSClassImplements { + return new TSClassImplements(global.generatedEs2panda._UpdateTSClassImplements(global.context, passNode(original), passNode(expression), passNode(typeParameters))) + } + static create1TSClassImplements(expression?: Expression): TSClassImplements { + return new TSClassImplements(global.generatedEs2panda._CreateTSClassImplements1(global.context, passNode(expression))) + } + static update1TSClassImplements(original?: TSClassImplements, expression?: Expression): TSClassImplements { + return new TSClassImplements(global.generatedEs2panda._UpdateTSClassImplements1(global.context, passNode(original), passNode(expression))) + } + get expr(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSClassImplementsExprConst(global.context, this.peer)) + } + get typeParameters(): TSTypeParameterInstantiation | undefined { + return unpackNode(global.generatedEs2panda._TSClassImplementsTypeParametersConst(global.context, this.peer)) + } +} +export function isTSClassImplements(node: AstNode): node is TSClassImplements { + return node instanceof TSClassImplements +} +if (!nodeByType.has(139)) { + nodeByType.set(139, TSClassImplements) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSConditionalType.ts b/koala-wrapper/src/generated/peers/TSConditionalType.ts new file mode 100644 index 000000000..f03de8600 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSConditionalType.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +export class TSConditionalType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 111) + super(pointer) + + } + static createTSConditionalType(checkType?: Expression, extendsType?: Expression, trueType?: Expression, falseType?: Expression): TSConditionalType { + return new TSConditionalType(global.generatedEs2panda._CreateTSConditionalType(global.context, passNode(checkType), passNode(extendsType), passNode(trueType), passNode(falseType))) + } + static updateTSConditionalType(original?: TSConditionalType, checkType?: Expression, extendsType?: Expression, trueType?: Expression, falseType?: Expression): TSConditionalType { + return new TSConditionalType(global.generatedEs2panda._UpdateTSConditionalType(global.context, passNode(original), passNode(checkType), passNode(extendsType), passNode(trueType), passNode(falseType))) + } + get checkType(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSConditionalTypeCheckTypeConst(global.context, this.peer)) + } + get extendsType(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSConditionalTypeExtendsTypeConst(global.context, this.peer)) + } + get trueType(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSConditionalTypeTrueTypeConst(global.context, this.peer)) + } + get falseType(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSConditionalTypeFalseTypeConst(global.context, this.peer)) + } +} +export function isTSConditionalType(node: AstNode): node is TSConditionalType { + return node instanceof TSConditionalType +} +if (!nodeByType.has(111)) { + nodeByType.set(111, TSConditionalType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSConstructorType.ts b/koala-wrapper/src/generated/peers/TSConstructorType.ts new file mode 100644 index 000000000..896ccf390 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSConstructorType.ts @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { FunctionSignature } from "./FunctionSignature" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { Expression } from "./Expression" +export class TSConstructorType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 126) + super(pointer) + + } + static createTSConstructorType(signature: FunctionSignature | undefined, abstract: boolean): TSConstructorType { + return new TSConstructorType(global.generatedEs2panda._CreateTSConstructorType(global.context, passNode(signature), abstract)) + } + static updateTSConstructorType(original: TSConstructorType | undefined, signature: FunctionSignature | undefined, abstract: boolean): TSConstructorType { + return new TSConstructorType(global.generatedEs2panda._UpdateTSConstructorType(global.context, passNode(original), passNode(signature), abstract)) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._TSConstructorTypeTypeParamsConst(global.context, this.peer)) + } + get params(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._TSConstructorTypeParamsConst(global.context, this.peer)) + } + get returnType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSConstructorTypeReturnTypeConst(global.context, this.peer)) + } + get abstract(): boolean { + return global.generatedEs2panda._TSConstructorTypeAbstractConst(global.context, this.peer) + } +} +export function isTSConstructorType(node: AstNode): node is TSConstructorType { + return node instanceof TSConstructorType +} +if (!nodeByType.has(126)) { + nodeByType.set(126, TSConstructorType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts b/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts new file mode 100644 index 000000000..ecebdceed --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedStatement } from "./TypedStatement" +import { Identifier } from "./Identifier" +import { ClassDefinition } from "./ClassDefinition" +import { Decorator } from "./Decorator" +export class TSEnumDeclaration extends TypedStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 87) + super(pointer) + + } + static createTSEnumDeclaration(key: Identifier | undefined, members: readonly AstNode[], isConst: boolean, isStatic: boolean, isDeclare: boolean): TSEnumDeclaration { + return new TSEnumDeclaration(global.generatedEs2panda._CreateTSEnumDeclaration(global.context, passNode(key), passNodeArray(members), members.length, isConst, isStatic, isDeclare)) + } + static updateTSEnumDeclaration(original: TSEnumDeclaration | undefined, key: Identifier | undefined, members: readonly AstNode[], isConst: boolean, isStatic: boolean, isDeclare: boolean): TSEnumDeclaration { + return new TSEnumDeclaration(global.generatedEs2panda._UpdateTSEnumDeclaration(global.context, passNode(original), passNode(key), passNodeArray(members), members.length, isConst, isStatic, isDeclare)) + } + get key(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._TSEnumDeclarationKeyConst(global.context, this.peer)) + } + get members(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._TSEnumDeclarationMembersConst(global.context, this.peer)) + } + get internalName(): string { + return unpackString(global.generatedEs2panda._TSEnumDeclarationInternalNameConst(global.context, this.peer)) + } + /** @deprecated */ + setInternalName(internalName: string): this { + global.generatedEs2panda._TSEnumDeclarationSetInternalName(global.context, this.peer, internalName) + return this + } + get boxedClass(): ClassDefinition | undefined { + return unpackNode(global.generatedEs2panda._TSEnumDeclarationBoxedClassConst(global.context, this.peer)) + } + /** @deprecated */ + setBoxedClass(wrapperClass: ClassDefinition): this { + global.generatedEs2panda._TSEnumDeclarationSetBoxedClass(global.context, this.peer, passNode(wrapperClass)) + return this + } + get isConst(): boolean { + return global.generatedEs2panda._TSEnumDeclarationIsConstConst(global.context, this.peer) + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._TSEnumDeclarationDecoratorsConst(global.context, this.peer)) + } +} +export function isTSEnumDeclaration(node: AstNode): node is TSEnumDeclaration { + return node instanceof TSEnumDeclaration +} +if (!nodeByType.has(87)) { + nodeByType.set(87, TSEnumDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSEnumMember.ts b/koala-wrapper/src/generated/peers/TSEnumMember.ts new file mode 100644 index 000000000..c0332c509 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSEnumMember.ts @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class TSEnumMember extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 88) + super(pointer) + + } + static createTSEnumMember(key?: Expression, init?: Expression): TSEnumMember { + return new TSEnumMember(global.generatedEs2panda._CreateTSEnumMember(global.context, passNode(key), passNode(init))) + } + static updateTSEnumMember(original?: TSEnumMember, key?: Expression, init?: Expression): TSEnumMember { + return new TSEnumMember(global.generatedEs2panda._UpdateTSEnumMember(global.context, passNode(original), passNode(key), passNode(init))) + } + static create1TSEnumMember(key: Expression | undefined, init: Expression | undefined, isGenerated: boolean): TSEnumMember { + return new TSEnumMember(global.generatedEs2panda._CreateTSEnumMember1(global.context, passNode(key), passNode(init), isGenerated)) + } + static update1TSEnumMember(original: TSEnumMember | undefined, key: Expression | undefined, init: Expression | undefined, isGenerated: boolean): TSEnumMember { + return new TSEnumMember(global.generatedEs2panda._UpdateTSEnumMember1(global.context, passNode(original), passNode(key), passNode(init), isGenerated)) + } + get key(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSEnumMemberKeyConst(global.context, this.peer)) + } + get init(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSEnumMemberInitConst(global.context, this.peer)) + } + get isGenerated(): boolean { + return global.generatedEs2panda._TSEnumMemberIsGeneratedConst(global.context, this.peer) + } +} +export function isTSEnumMember(node: AstNode): node is TSEnumMember { + return node instanceof TSEnumMember +} +if (!nodeByType.has(88)) { + nodeByType.set(88, TSEnumMember) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts b/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts new file mode 100644 index 000000000..eae8cfabc --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class TSExternalModuleReference extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 89) + super(pointer) + + } + static createTSExternalModuleReference(expr?: Expression): TSExternalModuleReference { + return new TSExternalModuleReference(global.generatedEs2panda._CreateTSExternalModuleReference(global.context, passNode(expr))) + } + static updateTSExternalModuleReference(original?: TSExternalModuleReference, expr?: Expression): TSExternalModuleReference { + return new TSExternalModuleReference(global.generatedEs2panda._UpdateTSExternalModuleReference(global.context, passNode(original), passNode(expr))) + } + get expr(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSExternalModuleReferenceExprConst(global.context, this.peer)) + } +} +export function isTSExternalModuleReference(node: AstNode): node is TSExternalModuleReference { + return node instanceof TSExternalModuleReference +} +if (!nodeByType.has(89)) { + nodeByType.set(89, TSExternalModuleReference) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSFunctionType.ts b/koala-wrapper/src/generated/peers/TSFunctionType.ts new file mode 100644 index 000000000..f65d2fa56 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSFunctionType.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { FunctionSignature } from "./FunctionSignature" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { Expression } from "./Expression" +export class TSFunctionType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 125) + super(pointer) + + } + static createTSFunctionType(signature?: FunctionSignature): TSFunctionType { + return new TSFunctionType(global.generatedEs2panda._CreateTSFunctionType(global.context, passNode(signature))) + } + static updateTSFunctionType(original?: TSFunctionType, signature?: FunctionSignature): TSFunctionType { + return new TSFunctionType(global.generatedEs2panda._UpdateTSFunctionType(global.context, passNode(original), passNode(signature))) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._TSFunctionTypeTypeParamsConst(global.context, this.peer)) + } + get params(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._TSFunctionTypeParamsConst(global.context, this.peer)) + } + get returnType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSFunctionTypeReturnTypeConst(global.context, this.peer)) + } + /** @deprecated */ + setNullable(nullable: boolean): this { + global.generatedEs2panda._TSFunctionTypeSetNullable(global.context, this.peer, nullable) + return this + } +} +export function isTSFunctionType(node: AstNode): node is TSFunctionType { + return node instanceof TSFunctionType +} +if (!nodeByType.has(125)) { + nodeByType.set(125, TSFunctionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts b/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts new file mode 100644 index 000000000..a04b88379 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Identifier } from "./Identifier" +import { Expression } from "./Expression" +export class TSImportEqualsDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 124) + super(pointer) + + } + static createTSImportEqualsDeclaration(id: Identifier | undefined, moduleReference: Expression | undefined, isExport: boolean): TSImportEqualsDeclaration { + return new TSImportEqualsDeclaration(global.generatedEs2panda._CreateTSImportEqualsDeclaration(global.context, passNode(id), passNode(moduleReference), isExport)) + } + static updateTSImportEqualsDeclaration(original: TSImportEqualsDeclaration | undefined, id: Identifier | undefined, moduleReference: Expression | undefined, isExport: boolean): TSImportEqualsDeclaration { + return new TSImportEqualsDeclaration(global.generatedEs2panda._UpdateTSImportEqualsDeclaration(global.context, passNode(original), passNode(id), passNode(moduleReference), isExport)) + } + get id(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._TSImportEqualsDeclarationIdConst(global.context, this.peer)) + } + get moduleReference(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSImportEqualsDeclarationModuleReferenceConst(global.context, this.peer)) + } + get isExport(): boolean { + return global.generatedEs2panda._TSImportEqualsDeclarationIsExportConst(global.context, this.peer) + } +} +export function isTSImportEqualsDeclaration(node: AstNode): node is TSImportEqualsDeclaration { + return node instanceof TSImportEqualsDeclaration +} +if (!nodeByType.has(124)) { + nodeByType.set(124, TSImportEqualsDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSImportType.ts b/koala-wrapper/src/generated/peers/TSImportType.ts new file mode 100644 index 000000000..43e08e49a --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSImportType.ts @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +export class TSImportType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 112) + super(pointer) + + } + static createTSImportType(param: Expression | undefined, typeParams: TSTypeParameterInstantiation | undefined, qualifier: Expression | undefined, isTypeof: boolean): TSImportType { + return new TSImportType(global.generatedEs2panda._CreateTSImportType(global.context, passNode(param), passNode(typeParams), passNode(qualifier), isTypeof)) + } + static updateTSImportType(original: TSImportType | undefined, param: Expression | undefined, typeParams: TSTypeParameterInstantiation | undefined, qualifier: Expression | undefined, isTypeof: boolean): TSImportType { + return new TSImportType(global.generatedEs2panda._UpdateTSImportType(global.context, passNode(original), passNode(param), passNode(typeParams), passNode(qualifier), isTypeof)) + } + get param(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSImportTypeParamConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterInstantiation | undefined { + return unpackNode(global.generatedEs2panda._TSImportTypeTypeParamsConst(global.context, this.peer)) + } + get qualifier(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSImportTypeQualifierConst(global.context, this.peer)) + } + get isTypeof(): boolean { + return global.generatedEs2panda._TSImportTypeIsTypeofConst(global.context, this.peer) + } +} +export function isTSImportType(node: AstNode): node is TSImportType { + return node instanceof TSImportType +} +if (!nodeByType.has(112)) { + nodeByType.set(112, TSImportType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSIndexSignature.ts b/koala-wrapper/src/generated/peers/TSIndexSignature.ts new file mode 100644 index 000000000..6a7bf5ea9 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSIndexSignature.ts @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedAstNode } from "./TypedAstNode" +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +import { Es2pandaTSIndexSignatureKind } from "./../Es2pandaEnums" +export class TSIndexSignature extends TypedAstNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 136) + super(pointer) + + } + static createTSIndexSignature(param: Expression | undefined, typeAnnotation: TypeNode | undefined, readonly_arg: boolean): TSIndexSignature { + return new TSIndexSignature(global.generatedEs2panda._CreateTSIndexSignature(global.context, passNode(param), passNode(typeAnnotation), readonly_arg)) + } + static updateTSIndexSignature(original: TSIndexSignature | undefined, param: Expression | undefined, typeAnnotation: TypeNode | undefined, readonly_arg: boolean): TSIndexSignature { + return new TSIndexSignature(global.generatedEs2panda._UpdateTSIndexSignature(global.context, passNode(original), passNode(param), passNode(typeAnnotation), readonly_arg)) + } + get param(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSIndexSignatureParamConst(global.context, this.peer)) + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSIndexSignatureTypeAnnotationConst(global.context, this.peer)) + } + get readonly(): boolean { + return global.generatedEs2panda._TSIndexSignatureReadonlyConst(global.context, this.peer) + } +} +export function isTSIndexSignature(node: AstNode): node is TSIndexSignature { + return node instanceof TSIndexSignature +} +if (!nodeByType.has(136)) { + nodeByType.set(136, TSIndexSignature) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts b/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts new file mode 100644 index 000000000..edb3a5c1f --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSIndexedAccessType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 130) + super(pointer) + + } + static createTSIndexedAccessType(objectType?: TypeNode, indexType?: TypeNode): TSIndexedAccessType { + return new TSIndexedAccessType(global.generatedEs2panda._CreateTSIndexedAccessType(global.context, passNode(objectType), passNode(indexType))) + } + static updateTSIndexedAccessType(original?: TSIndexedAccessType, objectType?: TypeNode, indexType?: TypeNode): TSIndexedAccessType { + return new TSIndexedAccessType(global.generatedEs2panda._UpdateTSIndexedAccessType(global.context, passNode(original), passNode(objectType), passNode(indexType))) + } + get objectType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSIndexedAccessTypeObjectTypeConst(global.context, this.peer)) + } + get indexType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSIndexedAccessTypeIndexTypeConst(global.context, this.peer)) + } +} +export function isTSIndexedAccessType(node: AstNode): node is TSIndexedAccessType { + return node instanceof TSIndexedAccessType +} +if (!nodeByType.has(130)) { + nodeByType.set(130, TSIndexedAccessType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSInferType.ts b/koala-wrapper/src/generated/peers/TSInferType.ts new file mode 100644 index 000000000..f2a5d6597 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSInferType.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { TSTypeParameter } from "./TSTypeParameter" +export class TSInferType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 110) + super(pointer) + + } + static createTSInferType(typeParam?: TSTypeParameter): TSInferType { + return new TSInferType(global.generatedEs2panda._CreateTSInferType(global.context, passNode(typeParam))) + } + static updateTSInferType(original?: TSInferType, typeParam?: TSTypeParameter): TSInferType { + return new TSInferType(global.generatedEs2panda._UpdateTSInferType(global.context, passNode(original), passNode(typeParam))) + } + get typeParam(): TSTypeParameter | undefined { + return unpackNode(global.generatedEs2panda._TSInferTypeTypeParamConst(global.context, this.peer)) + } +} +export function isTSInferType(node: AstNode): node is TSInferType { + return node instanceof TSInferType +} +if (!nodeByType.has(110)) { + nodeByType.set(110, TSInferType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSInterfaceBody.ts b/koala-wrapper/src/generated/peers/TSInterfaceBody.ts new file mode 100644 index 000000000..103fa4a1a --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSInterfaceBody.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class TSInterfaceBody extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 132) + super(pointer) + + } + static createTSInterfaceBody(body: readonly AstNode[]): TSInterfaceBody { + return new TSInterfaceBody(global.generatedEs2panda._CreateTSInterfaceBody(global.context, passNodeArray(body), body.length)) + } + static updateTSInterfaceBody(original: TSInterfaceBody | undefined, body: readonly AstNode[]): TSInterfaceBody { + return new TSInterfaceBody(global.generatedEs2panda._UpdateTSInterfaceBody(global.context, passNode(original), passNodeArray(body), body.length)) + } + get bodyPtr(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._TSInterfaceBodyBodyPtr(global.context, this.peer)) + } + get body(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._TSInterfaceBodyBodyConst(global.context, this.peer)) + } +} +export function isTSInterfaceBody(node: AstNode): node is TSInterfaceBody { + return node instanceof TSInterfaceBody +} +if (!nodeByType.has(132)) { + nodeByType.set(132, TSInterfaceBody) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts b/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts new file mode 100644 index 000000000..21c064fcf --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedStatement } from "./TypedStatement" +import { TSInterfaceHeritage } from "./TSInterfaceHeritage" +import { TSInterfaceBody } from "./TSInterfaceBody" +import { Identifier } from "./Identifier" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { Decorator } from "./Decorator" +import { ClassDeclaration } from "./ClassDeclaration" +import { AnnotationUsage } from "./AnnotationUsage" +export class TSInterfaceDeclaration extends TypedStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 131) + super(pointer) + + } + static createTSInterfaceDeclaration(_extends: readonly TSInterfaceHeritage[], id: AstNode | undefined, typeParams: AstNode | undefined, body: AstNode | undefined, isStatic: boolean, isExternal: boolean): TSInterfaceDeclaration { + return new TSInterfaceDeclaration(global.generatedEs2panda._CreateTSInterfaceDeclaration(global.context, passNodeArray(_extends), _extends.length, passNode(id), passNode(typeParams), passNode(body), isStatic, isExternal)) + } + static updateTSInterfaceDeclaration(original: TSInterfaceDeclaration | undefined, _extends: readonly TSInterfaceHeritage[], id: AstNode | undefined, typeParams: AstNode | undefined, body: AstNode | undefined, isStatic: boolean, isExternal: boolean): TSInterfaceDeclaration { + return new TSInterfaceDeclaration(global.generatedEs2panda._UpdateTSInterfaceDeclaration(global.context, passNode(original), passNodeArray(_extends), _extends.length, passNode(id), passNode(typeParams), passNode(body), isStatic, isExternal)) + } + get body(): TSInterfaceBody | undefined { + return unpackNode(global.generatedEs2panda._TSInterfaceDeclarationBodyConst(global.context, this.peer)) + } + get id(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._TSInterfaceDeclarationIdConst(global.context, this.peer)) + } + get internalName(): string { + return unpackString(global.generatedEs2panda._TSInterfaceDeclarationInternalNameConst(global.context, this.peer)) + } + /** @deprecated */ + setInternalName(internalName: string): this { + global.generatedEs2panda._TSInterfaceDeclarationSetInternalName(global.context, this.peer, internalName) + return this + } + get isStatic(): boolean { + return global.generatedEs2panda._TSInterfaceDeclarationIsStaticConst(global.context, this.peer) + } + get isFromExternal(): boolean { + return global.generatedEs2panda._TSInterfaceDeclarationIsFromExternalConst(global.context, this.peer) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._TSInterfaceDeclarationTypeParamsConst(global.context, this.peer)) + } + get extends(): readonly TSInterfaceHeritage[] { + return unpackNodeArray(global.generatedEs2panda._TSInterfaceDeclarationExtendsConst(global.context, this.peer)) + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._TSInterfaceDeclarationDecoratorsConst(global.context, this.peer)) + } + get getAnonClass(): ClassDeclaration | undefined { + return unpackNode(global.generatedEs2panda._TSInterfaceDeclarationGetAnonClassConst(global.context, this.peer)) + } + /** @deprecated */ + setAnonClass(anonClass: ClassDeclaration): this { + global.generatedEs2panda._TSInterfaceDeclarationSetAnonClass(global.context, this.peer, passNode(anonClass)) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._TSInterfaceDeclarationAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._TSInterfaceDeclarationSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isTSInterfaceDeclaration(node: AstNode): node is TSInterfaceDeclaration { + return node instanceof TSInterfaceDeclaration +} +if (!nodeByType.has(131)) { + nodeByType.set(131, TSInterfaceDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts b/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts new file mode 100644 index 000000000..4af6bfb0f --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class TSInterfaceHeritage extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 133) + super(pointer) + + } + static createTSInterfaceHeritage(expr?: TypeNode): TSInterfaceHeritage { + return new TSInterfaceHeritage(global.generatedEs2panda._CreateTSInterfaceHeritage(global.context, passNode(expr))) + } + static updateTSInterfaceHeritage(original?: TSInterfaceHeritage, expr?: TypeNode): TSInterfaceHeritage { + return new TSInterfaceHeritage(global.generatedEs2panda._UpdateTSInterfaceHeritage(global.context, passNode(original), passNode(expr))) + } + get expr(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSInterfaceHeritageExprConst(global.context, this.peer)) + } +} +export function isTSInterfaceHeritage(node: AstNode): node is TSInterfaceHeritage { + return node instanceof TSInterfaceHeritage +} +if (!nodeByType.has(133)) { + nodeByType.set(133, TSInterfaceHeritage) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSIntersectionType.ts b/koala-wrapper/src/generated/peers/TSIntersectionType.ts new file mode 100644 index 000000000..d21f48d7a --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSIntersectionType.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +export class TSIntersectionType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 113) + super(pointer) + + } + static createTSIntersectionType(types: readonly Expression[]): TSIntersectionType { + return new TSIntersectionType(global.generatedEs2panda._CreateTSIntersectionType(global.context, passNodeArray(types), types.length)) + } + static updateTSIntersectionType(original: TSIntersectionType | undefined, types: readonly Expression[]): TSIntersectionType { + return new TSIntersectionType(global.generatedEs2panda._UpdateTSIntersectionType(global.context, passNode(original), passNodeArray(types), types.length)) + } + get types(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._TSIntersectionTypeTypesConst(global.context, this.peer)) + } +} +export function isTSIntersectionType(node: AstNode): node is TSIntersectionType { + return node instanceof TSIntersectionType +} +if (!nodeByType.has(113)) { + nodeByType.set(113, TSIntersectionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSLiteralType.ts b/koala-wrapper/src/generated/peers/TSLiteralType.ts new file mode 100644 index 000000000..f9ecdf774 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSLiteralType.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +export class TSLiteralType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 109) + super(pointer) + + } + static createTSLiteralType(literal?: Expression): TSLiteralType { + return new TSLiteralType(global.generatedEs2panda._CreateTSLiteralType(global.context, passNode(literal))) + } + static updateTSLiteralType(original?: TSLiteralType, literal?: Expression): TSLiteralType { + return new TSLiteralType(global.generatedEs2panda._UpdateTSLiteralType(global.context, passNode(original), passNode(literal))) + } + get literal(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSLiteralTypeLiteralConst(global.context, this.peer)) + } +} +export function isTSLiteralType(node: AstNode): node is TSLiteralType { + return node instanceof TSLiteralType +} +if (!nodeByType.has(109)) { + nodeByType.set(109, TSLiteralType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSMappedType.ts b/koala-wrapper/src/generated/peers/TSMappedType.ts new file mode 100644 index 000000000..e8a2202dc --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSMappedType.ts @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { TSTypeParameter } from "./TSTypeParameter" +import { Es2pandaMappedOption } from "./../Es2pandaEnums" +export class TSMappedType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 114) + super(pointer) + + } + static createTSMappedType(typeParameter: TSTypeParameter | undefined, typeAnnotation: TypeNode | undefined, readonly_arg: Es2pandaMappedOption, optional_arg: Es2pandaMappedOption): TSMappedType { + return new TSMappedType(global.generatedEs2panda._CreateTSMappedType(global.context, passNode(typeParameter), passNode(typeAnnotation), readonly_arg, optional_arg)) + } + static updateTSMappedType(original: TSMappedType | undefined, typeParameter: TSTypeParameter | undefined, typeAnnotation: TypeNode | undefined, readonly_arg: Es2pandaMappedOption, optional_arg: Es2pandaMappedOption): TSMappedType { + return new TSMappedType(global.generatedEs2panda._UpdateTSMappedType(global.context, passNode(original), passNode(typeParameter), passNode(typeAnnotation), readonly_arg, optional_arg)) + } + get typeParameter(): TSTypeParameter | undefined { + return unpackNode(global.generatedEs2panda._TSMappedTypeTypeParameter(global.context, this.peer)) + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSMappedTypeTypeAnnotation(global.context, this.peer)) + } + get readonly(): Es2pandaMappedOption { + return global.generatedEs2panda._TSMappedTypeReadonly(global.context, this.peer) + } + get optional(): Es2pandaMappedOption { + return global.generatedEs2panda._TSMappedTypeOptional(global.context, this.peer) + } +} +export function isTSMappedType(node: AstNode): node is TSMappedType { + return node instanceof TSMappedType +} +if (!nodeByType.has(114)) { + nodeByType.set(114, TSMappedType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSMethodSignature.ts b/koala-wrapper/src/generated/peers/TSMethodSignature.ts new file mode 100644 index 000000000..d16351da0 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSMethodSignature.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { FunctionSignature } from "./FunctionSignature" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { TypeNode } from "./TypeNode" +export class TSMethodSignature extends AstNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 106) + super(pointer) + + } + static createTSMethodSignature(key: Expression | undefined, signature: FunctionSignature | undefined, computed: boolean, optional_arg: boolean): TSMethodSignature { + return new TSMethodSignature(global.generatedEs2panda._CreateTSMethodSignature(global.context, passNode(key), passNode(signature), computed, optional_arg)) + } + static updateTSMethodSignature(original: TSMethodSignature | undefined, key: Expression | undefined, signature: FunctionSignature | undefined, computed: boolean, optional_arg: boolean): TSMethodSignature { + return new TSMethodSignature(global.generatedEs2panda._UpdateTSMethodSignature(global.context, passNode(original), passNode(key), passNode(signature), computed, optional_arg)) + } + get key(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSMethodSignatureKeyConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._TSMethodSignatureTypeParamsConst(global.context, this.peer)) + } + get params(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._TSMethodSignatureParamsConst(global.context, this.peer)) + } + get returnTypeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSMethodSignatureReturnTypeAnnotationConst(global.context, this.peer)) + } + get computed(): boolean { + return global.generatedEs2panda._TSMethodSignatureComputedConst(global.context, this.peer) + } + get optional(): boolean { + return global.generatedEs2panda._TSMethodSignatureOptionalConst(global.context, this.peer) + } +} +export function isTSMethodSignature(node: AstNode): node is TSMethodSignature { + return node instanceof TSMethodSignature +} +if (!nodeByType.has(106)) { + nodeByType.set(106, TSMethodSignature) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSModuleBlock.ts b/koala-wrapper/src/generated/peers/TSModuleBlock.ts new file mode 100644 index 000000000..d25d54f36 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSModuleBlock.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +export class TSModuleBlock extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 115) + super(pointer) + + } + static createTSModuleBlock(statements: readonly Statement[]): TSModuleBlock { + return new TSModuleBlock(global.generatedEs2panda._CreateTSModuleBlock(global.context, passNodeArray(statements), statements.length)) + } + static updateTSModuleBlock(original: TSModuleBlock | undefined, statements: readonly Statement[]): TSModuleBlock { + return new TSModuleBlock(global.generatedEs2panda._UpdateTSModuleBlock(global.context, passNode(original), passNodeArray(statements), statements.length)) + } + get statements(): readonly Statement[] { + return unpackNodeArray(global.generatedEs2panda._TSModuleBlockStatementsConst(global.context, this.peer)) + } +} +export function isTSModuleBlock(node: AstNode): node is TSModuleBlock { + return node instanceof TSModuleBlock +} +if (!nodeByType.has(115)) { + nodeByType.set(115, TSModuleBlock) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts b/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts new file mode 100644 index 000000000..c4582a84c --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class TSModuleDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 123) + super(pointer) + + } + static createTSModuleDeclaration(name: Expression | undefined, body: Statement | undefined, declare: boolean, _global: boolean): TSModuleDeclaration { + return new TSModuleDeclaration(global.generatedEs2panda._CreateTSModuleDeclaration(global.context, passNode(name), passNode(body), declare, _global)) + } + static updateTSModuleDeclaration(original: TSModuleDeclaration | undefined, name: Expression | undefined, body: Statement | undefined, declare: boolean, _global: boolean): TSModuleDeclaration { + return new TSModuleDeclaration(global.generatedEs2panda._UpdateTSModuleDeclaration(global.context, passNode(original), passNode(name), passNode(body), declare, _global)) + } + get name(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSModuleDeclarationNameConst(global.context, this.peer)) + } + get body(): Statement | undefined { + return unpackNode(global.generatedEs2panda._TSModuleDeclarationBodyConst(global.context, this.peer)) + } + get global(): boolean { + return global.generatedEs2panda._TSModuleDeclarationGlobalConst(global.context, this.peer) + } + get isExternalOrAmbient(): boolean { + return global.generatedEs2panda._TSModuleDeclarationIsExternalOrAmbientConst(global.context, this.peer) + } +} +export function isTSModuleDeclaration(node: AstNode): node is TSModuleDeclaration { + return node instanceof TSModuleDeclaration +} +if (!nodeByType.has(123)) { + nodeByType.set(123, TSModuleDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts b/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts new file mode 100644 index 000000000..3252f8a47 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +export class TSNamedTupleMember extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 135) + super(pointer) + + } + static createTSNamedTupleMember(label: Expression | undefined, elementType: TypeNode | undefined, optional_arg: boolean): TSNamedTupleMember { + return new TSNamedTupleMember(global.generatedEs2panda._CreateTSNamedTupleMember(global.context, passNode(label), passNode(elementType), optional_arg)) + } + static updateTSNamedTupleMember(original: TSNamedTupleMember | undefined, label: Expression | undefined, elementType: TypeNode | undefined, optional_arg: boolean): TSNamedTupleMember { + return new TSNamedTupleMember(global.generatedEs2panda._UpdateTSNamedTupleMember(global.context, passNode(original), passNode(label), passNode(elementType), optional_arg)) + } + get label(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSNamedTupleMemberLabelConst(global.context, this.peer)) + } + get elementType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSNamedTupleMemberElementTypeConst(global.context, this.peer)) + } + get isOptional(): boolean { + return global.generatedEs2panda._TSNamedTupleMemberIsOptionalConst(global.context, this.peer) + } +} +export function isTSNamedTupleMember(node: AstNode): node is TSNamedTupleMember { + return node instanceof TSNamedTupleMember +} +if (!nodeByType.has(135)) { + nodeByType.set(135, TSNamedTupleMember) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNeverKeyword.ts b/koala-wrapper/src/generated/peers/TSNeverKeyword.ts new file mode 100644 index 000000000..39b7de7ff --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSNeverKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSNeverKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 99) + super(pointer) + + } + static createTSNeverKeyword(): TSNeverKeyword { + return new TSNeverKeyword(global.generatedEs2panda._CreateTSNeverKeyword(global.context)) + } + static updateTSNeverKeyword(original?: TSNeverKeyword): TSNeverKeyword { + return new TSNeverKeyword(global.generatedEs2panda._UpdateTSNeverKeyword(global.context, passNode(original))) + } +} +export function isTSNeverKeyword(node: AstNode): node is TSNeverKeyword { + return node instanceof TSNeverKeyword +} +if (!nodeByType.has(99)) { + nodeByType.set(99, TSNeverKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNonNullExpression.ts b/koala-wrapper/src/generated/peers/TSNonNullExpression.ts new file mode 100644 index 000000000..21bc3e670 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSNonNullExpression.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class TSNonNullExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 100) + super(pointer) + + } + static createTSNonNullExpression(expr?: Expression): TSNonNullExpression { + return new TSNonNullExpression(global.generatedEs2panda._CreateTSNonNullExpression(global.context, passNode(expr))) + } + static updateTSNonNullExpression(original?: TSNonNullExpression, expr?: Expression): TSNonNullExpression { + return new TSNonNullExpression(global.generatedEs2panda._UpdateTSNonNullExpression(global.context, passNode(original), passNode(expr))) + } + get expr(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSNonNullExpressionExprConst(global.context, this.peer)) + } + /** @deprecated */ + setExpr(expr: Expression): this { + global.generatedEs2panda._TSNonNullExpressionSetExpr(global.context, this.peer, passNode(expr)) + return this + } +} +export function isTSNonNullExpression(node: AstNode): node is TSNonNullExpression { + return node instanceof TSNonNullExpression +} +if (!nodeByType.has(100)) { + nodeByType.set(100, TSNonNullExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNullKeyword.ts b/koala-wrapper/src/generated/peers/TSNullKeyword.ts new file mode 100644 index 000000000..c3b161938 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSNullKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSNullKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 101) + super(pointer) + + } + static createTSNullKeyword(): TSNullKeyword { + return new TSNullKeyword(global.generatedEs2panda._CreateTSNullKeyword(global.context)) + } + static updateTSNullKeyword(original?: TSNullKeyword): TSNullKeyword { + return new TSNullKeyword(global.generatedEs2panda._UpdateTSNullKeyword(global.context, passNode(original))) + } +} +export function isTSNullKeyword(node: AstNode): node is TSNullKeyword { + return node instanceof TSNullKeyword +} +if (!nodeByType.has(101)) { + nodeByType.set(101, TSNullKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNumberKeyword.ts b/koala-wrapper/src/generated/peers/TSNumberKeyword.ts new file mode 100644 index 000000000..ff3c783af --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSNumberKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSNumberKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 90) + super(pointer) + + } + static createTSNumberKeyword(): TSNumberKeyword { + return new TSNumberKeyword(global.generatedEs2panda._CreateTSNumberKeyword(global.context)) + } + static updateTSNumberKeyword(original?: TSNumberKeyword): TSNumberKeyword { + return new TSNumberKeyword(global.generatedEs2panda._UpdateTSNumberKeyword(global.context, passNode(original))) + } +} +export function isTSNumberKeyword(node: AstNode): node is TSNumberKeyword { + return node instanceof TSNumberKeyword +} +if (!nodeByType.has(90)) { + nodeByType.set(90, TSNumberKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSObjectKeyword.ts b/koala-wrapper/src/generated/peers/TSObjectKeyword.ts new file mode 100644 index 000000000..2279f62af --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSObjectKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSObjectKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 97) + super(pointer) + + } + static createTSObjectKeyword(): TSObjectKeyword { + return new TSObjectKeyword(global.generatedEs2panda._CreateTSObjectKeyword(global.context)) + } + static updateTSObjectKeyword(original?: TSObjectKeyword): TSObjectKeyword { + return new TSObjectKeyword(global.generatedEs2panda._UpdateTSObjectKeyword(global.context, passNode(original))) + } +} +export function isTSObjectKeyword(node: AstNode): node is TSObjectKeyword { + return node instanceof TSObjectKeyword +} +if (!nodeByType.has(97)) { + nodeByType.set(97, TSObjectKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSParameterProperty.ts b/koala-wrapper/src/generated/peers/TSParameterProperty.ts new file mode 100644 index 000000000..9efa642c8 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSParameterProperty.ts @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Es2pandaAccessibilityOption } from "./../Es2pandaEnums" +export class TSParameterProperty extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 122) + super(pointer) + + } + static createTSParameterProperty(accessibility: Es2pandaAccessibilityOption, parameter: Expression | undefined, readonly_arg: boolean, isStatic: boolean, isExport: boolean): TSParameterProperty { + return new TSParameterProperty(global.generatedEs2panda._CreateTSParameterProperty(global.context, accessibility, passNode(parameter), readonly_arg, isStatic, isExport)) + } + static updateTSParameterProperty(original: TSParameterProperty | undefined, accessibility: Es2pandaAccessibilityOption, parameter: Expression | undefined, readonly_arg: boolean, isStatic: boolean, isExport: boolean): TSParameterProperty { + return new TSParameterProperty(global.generatedEs2panda._UpdateTSParameterProperty(global.context, passNode(original), accessibility, passNode(parameter), readonly_arg, isStatic, isExport)) + } + get accessibility(): Es2pandaAccessibilityOption { + return global.generatedEs2panda._TSParameterPropertyAccessibilityConst(global.context, this.peer) + } + get readonly(): boolean { + return global.generatedEs2panda._TSParameterPropertyReadonlyConst(global.context, this.peer) + } + get isStatic(): boolean { + return global.generatedEs2panda._TSParameterPropertyIsStaticConst(global.context, this.peer) + } + get isExport(): boolean { + return global.generatedEs2panda._TSParameterPropertyIsExportConst(global.context, this.peer) + } + get parameter(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSParameterPropertyParameterConst(global.context, this.peer)) + } +} +export function isTSParameterProperty(node: AstNode): node is TSParameterProperty { + return node instanceof TSParameterProperty +} +if (!nodeByType.has(122)) { + nodeByType.set(122, TSParameterProperty) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSParenthesizedType.ts b/koala-wrapper/src/generated/peers/TSParenthesizedType.ts new file mode 100644 index 000000000..043431f71 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSParenthesizedType.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +export class TSParenthesizedType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 108) + super(pointer) + + } + static createTSParenthesizedType(type?: TypeNode): TSParenthesizedType { + return new TSParenthesizedType(global.generatedEs2panda._CreateTSParenthesizedType(global.context, passNode(type))) + } + static updateTSParenthesizedType(original?: TSParenthesizedType, type?: TypeNode): TSParenthesizedType { + return new TSParenthesizedType(global.generatedEs2panda._UpdateTSParenthesizedType(global.context, passNode(original), passNode(type))) + } + get type(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSParenthesizedTypeTypeConst(global.context, this.peer)) + } +} +export function isTSParenthesizedType(node: AstNode): node is TSParenthesizedType { + return node instanceof TSParenthesizedType +} +if (!nodeByType.has(108)) { + nodeByType.set(108, TSParenthesizedType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSPropertySignature.ts b/koala-wrapper/src/generated/peers/TSPropertySignature.ts new file mode 100644 index 000000000..b2725a964 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSPropertySignature.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { AnnotatedAstNode } from "./AnnotatedAstNode" +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class TSPropertySignature extends AnnotatedAstNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 105) + super(pointer) + + } + static createTSPropertySignature(key: Expression | undefined, typeAnnotation: TypeNode | undefined, computed: boolean, optional_arg: boolean, readonly_arg: boolean): TSPropertySignature { + return new TSPropertySignature(global.generatedEs2panda._CreateTSPropertySignature(global.context, passNode(key), passNode(typeAnnotation), computed, optional_arg, readonly_arg)) + } + static updateTSPropertySignature(original: TSPropertySignature | undefined, key: Expression | undefined, typeAnnotation: TypeNode | undefined, computed: boolean, optional_arg: boolean, readonly_arg: boolean): TSPropertySignature { + return new TSPropertySignature(global.generatedEs2panda._UpdateTSPropertySignature(global.context, passNode(original), passNode(key), passNode(typeAnnotation), computed, optional_arg, readonly_arg)) + } + get key(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSPropertySignatureKeyConst(global.context, this.peer)) + } + get computed(): boolean { + return global.generatedEs2panda._TSPropertySignatureComputedConst(global.context, this.peer) + } + get optional(): boolean { + return global.generatedEs2panda._TSPropertySignatureOptionalConst(global.context, this.peer) + } + get readonly(): boolean { + return global.generatedEs2panda._TSPropertySignatureReadonlyConst(global.context, this.peer) + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSPropertySignatureTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._TSPropertySignatureSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } +} +export function isTSPropertySignature(node: AstNode): node is TSPropertySignature { + return node instanceof TSPropertySignature +} +if (!nodeByType.has(105)) { + nodeByType.set(105, TSPropertySignature) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSQualifiedName.ts b/koala-wrapper/src/generated/peers/TSQualifiedName.ts new file mode 100644 index 000000000..e0f4d87ea --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSQualifiedName.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Identifier } from "./Identifier" +export class TSQualifiedName extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 129) + super(pointer) + + } + static createTSQualifiedName(left?: Expression, right?: Identifier): TSQualifiedName { + return new TSQualifiedName(global.generatedEs2panda._CreateTSQualifiedName(global.context, passNode(left), passNode(right))) + } + static updateTSQualifiedName(original?: TSQualifiedName, left?: Expression, right?: Identifier): TSQualifiedName { + return new TSQualifiedName(global.generatedEs2panda._UpdateTSQualifiedName(global.context, passNode(original), passNode(left), passNode(right))) + } + get left(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSQualifiedNameLeftConst(global.context, this.peer)) + } + get right(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._TSQualifiedNameRightConst(global.context, this.peer)) + } +} +export function isTSQualifiedName(node: AstNode): node is TSQualifiedName { + return node instanceof TSQualifiedName +} +if (!nodeByType.has(129)) { + nodeByType.set(129, TSQualifiedName) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts b/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts new file mode 100644 index 000000000..e70bbf176 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedAstNode } from "./TypedAstNode" +import { Es2pandaTSSignatureDeclarationKind } from "./../Es2pandaEnums" +import { FunctionSignature } from "./FunctionSignature" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class TSSignatureDeclaration extends TypedAstNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 107) + super(pointer) + + } + static createTSSignatureDeclaration(kind: Es2pandaTSSignatureDeclarationKind, signature?: FunctionSignature): TSSignatureDeclaration { + return new TSSignatureDeclaration(global.generatedEs2panda._CreateTSSignatureDeclaration(global.context, kind, passNode(signature))) + } + static updateTSSignatureDeclaration(original: TSSignatureDeclaration | undefined, kind: Es2pandaTSSignatureDeclarationKind, signature?: FunctionSignature): TSSignatureDeclaration { + return new TSSignatureDeclaration(global.generatedEs2panda._UpdateTSSignatureDeclaration(global.context, passNode(original), kind, passNode(signature))) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._TSSignatureDeclarationTypeParamsConst(global.context, this.peer)) + } + get params(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._TSSignatureDeclarationParamsConst(global.context, this.peer)) + } + get returnTypeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSSignatureDeclarationReturnTypeAnnotationConst(global.context, this.peer)) + } + get kind(): Es2pandaTSSignatureDeclarationKind { + return global.generatedEs2panda._TSSignatureDeclarationKindConst(global.context, this.peer) + } +} +export function isTSSignatureDeclaration(node: AstNode): node is TSSignatureDeclaration { + return node instanceof TSSignatureDeclaration +} +if (!nodeByType.has(107)) { + nodeByType.set(107, TSSignatureDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSStringKeyword.ts b/koala-wrapper/src/generated/peers/TSStringKeyword.ts new file mode 100644 index 000000000..6f749be33 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSStringKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSStringKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 92) + super(pointer) + + } + static createTSStringKeyword(): TSStringKeyword { + return new TSStringKeyword(global.generatedEs2panda._CreateTSStringKeyword(global.context)) + } + static updateTSStringKeyword(original?: TSStringKeyword): TSStringKeyword { + return new TSStringKeyword(global.generatedEs2panda._UpdateTSStringKeyword(global.context, passNode(original))) + } +} +export function isTSStringKeyword(node: AstNode): node is TSStringKeyword { + return node instanceof TSStringKeyword +} +if (!nodeByType.has(92)) { + nodeByType.set(92, TSStringKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSThisType.ts b/koala-wrapper/src/generated/peers/TSThisType.ts new file mode 100644 index 000000000..e57be0ab0 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSThisType.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSThisType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 116) + super(pointer) + + } + static createTSThisType(): TSThisType { + return new TSThisType(global.generatedEs2panda._CreateTSThisType(global.context)) + } + static updateTSThisType(original?: TSThisType): TSThisType { + return new TSThisType(global.generatedEs2panda._UpdateTSThisType(global.context, passNode(original))) + } +} +export function isTSThisType(node: AstNode): node is TSThisType { + return node instanceof TSThisType +} +if (!nodeByType.has(116)) { + nodeByType.set(116, TSThisType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTupleType.ts b/koala-wrapper/src/generated/peers/TSTupleType.ts new file mode 100644 index 000000000..11bafff08 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTupleType.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSTupleType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 134) + super(pointer) + + } + static createTSTupleType(elementTypes: readonly TypeNode[]): TSTupleType { + return new TSTupleType(global.generatedEs2panda._CreateTSTupleType(global.context, passNodeArray(elementTypes), elementTypes.length)) + } + static updateTSTupleType(original: TSTupleType | undefined, elementTypes: readonly TypeNode[]): TSTupleType { + return new TSTupleType(global.generatedEs2panda._UpdateTSTupleType(global.context, passNode(original), passNodeArray(elementTypes), elementTypes.length)) + } + get elementType(): readonly TypeNode[] { + return unpackNodeArray(global.generatedEs2panda._TSTupleTypeElementTypeConst(global.context, this.peer)) + } +} +export function isTSTupleType(node: AstNode): node is TSTupleType { + return node instanceof TSTupleType +} +if (!nodeByType.has(134)) { + nodeByType.set(134, TSTupleType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts b/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts new file mode 100644 index 000000000..58e381c2d --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { AnnotatedStatement } from "./AnnotatedStatement" +import { Identifier } from "./Identifier" +import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" +import { TypeNode } from "./TypeNode" +import { Decorator } from "./Decorator" +import { AnnotationUsage } from "./AnnotationUsage" +export class TSTypeAliasDeclaration extends AnnotatedStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 127) + super(pointer) + + } + static createTSTypeAliasDeclaration(id?: Identifier, typeParams?: TSTypeParameterDeclaration, typeAnnotation?: TypeNode): TSTypeAliasDeclaration { + return new TSTypeAliasDeclaration(global.generatedEs2panda._CreateTSTypeAliasDeclaration(global.context, passNode(id), passNode(typeParams), passNode(typeAnnotation))) + } + static updateTSTypeAliasDeclaration(original?: TSTypeAliasDeclaration, id?: Identifier, typeParams?: TSTypeParameterDeclaration, typeAnnotation?: TypeNode): TSTypeAliasDeclaration { + return new TSTypeAliasDeclaration(global.generatedEs2panda._UpdateTSTypeAliasDeclaration(global.context, passNode(original), passNode(id), passNode(typeParams), passNode(typeAnnotation))) + } + static create1TSTypeAliasDeclaration(id?: Identifier): TSTypeAliasDeclaration { + return new TSTypeAliasDeclaration(global.generatedEs2panda._CreateTSTypeAliasDeclaration1(global.context, passNode(id))) + } + static update1TSTypeAliasDeclaration(original?: TSTypeAliasDeclaration, id?: Identifier): TSTypeAliasDeclaration { + return new TSTypeAliasDeclaration(global.generatedEs2panda._UpdateTSTypeAliasDeclaration1(global.context, passNode(original), passNode(id))) + } + get id(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._TSTypeAliasDeclarationIdConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterDeclaration | undefined { + return unpackNode(global.generatedEs2panda._TSTypeAliasDeclarationTypeParamsConst(global.context, this.peer)) + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._TSTypeAliasDeclarationDecoratorsConst(global.context, this.peer)) + } + /** @deprecated */ + setTypeParameters(typeParams: TSTypeParameterDeclaration): this { + global.generatedEs2panda._TSTypeAliasDeclarationSetTypeParameters(global.context, this.peer, passNode(typeParams)) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._TSTypeAliasDeclarationAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._TSTypeAliasDeclarationSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSTypeAliasDeclarationTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._TSTypeAliasDeclarationSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } +} +export function isTSTypeAliasDeclaration(node: AstNode): node is TSTypeAliasDeclaration { + return node instanceof TSTypeAliasDeclaration +} +if (!nodeByType.has(127)) { + nodeByType.set(127, TSTypeAliasDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeAssertion.ts b/koala-wrapper/src/generated/peers/TSTypeAssertion.ts new file mode 100644 index 000000000..e01615f9b --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeAssertion.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { AnnotatedExpression } from "./AnnotatedExpression" +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +export class TSTypeAssertion extends AnnotatedExpression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 140) + super(pointer) + + } + static createTSTypeAssertion(typeAnnotation?: TypeNode, expression?: Expression): TSTypeAssertion { + return new TSTypeAssertion(global.generatedEs2panda._CreateTSTypeAssertion(global.context, passNode(typeAnnotation), passNode(expression))) + } + static updateTSTypeAssertion(original?: TSTypeAssertion, typeAnnotation?: TypeNode, expression?: Expression): TSTypeAssertion { + return new TSTypeAssertion(global.generatedEs2panda._UpdateTSTypeAssertion(global.context, passNode(original), passNode(typeAnnotation), passNode(expression))) + } + get getExpression(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSTypeAssertionGetExpressionConst(global.context, this.peer)) + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSTypeAssertionTypeAnnotationConst(global.context, this.peer)) + } + /** @deprecated */ + setTsTypeAnnotation(typeAnnotation: TypeNode): this { + global.generatedEs2panda._TSTypeAssertionSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this + } +} +export function isTSTypeAssertion(node: AstNode): node is TSTypeAssertion { + return node instanceof TSTypeAssertion +} +if (!nodeByType.has(140)) { + nodeByType.set(140, TSTypeAssertion) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeLiteral.ts b/koala-wrapper/src/generated/peers/TSTypeLiteral.ts new file mode 100644 index 000000000..20e3a4f22 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeLiteral.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSTypeLiteral extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 104) + super(pointer) + + } + static createTSTypeLiteral(members: readonly AstNode[]): TSTypeLiteral { + return new TSTypeLiteral(global.generatedEs2panda._CreateTSTypeLiteral(global.context, passNodeArray(members), members.length)) + } + static updateTSTypeLiteral(original: TSTypeLiteral | undefined, members: readonly AstNode[]): TSTypeLiteral { + return new TSTypeLiteral(global.generatedEs2panda._UpdateTSTypeLiteral(global.context, passNode(original), passNodeArray(members), members.length)) + } + get members(): readonly AstNode[] { + return unpackNodeArray(global.generatedEs2panda._TSTypeLiteralMembersConst(global.context, this.peer)) + } +} +export function isTSTypeLiteral(node: AstNode): node is TSTypeLiteral { + return node instanceof TSTypeLiteral +} +if (!nodeByType.has(104)) { + nodeByType.set(104, TSTypeLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeOperator.ts b/koala-wrapper/src/generated/peers/TSTypeOperator.ts new file mode 100644 index 000000000..3f94d244f --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeOperator.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Es2pandaTSOperatorType } from "./../Es2pandaEnums" +export class TSTypeOperator extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 117) + super(pointer) + + } + static createTSTypeOperator(type: TypeNode | undefined, operatorType: Es2pandaTSOperatorType): TSTypeOperator { + return new TSTypeOperator(global.generatedEs2panda._CreateTSTypeOperator(global.context, passNode(type), operatorType)) + } + static updateTSTypeOperator(original: TSTypeOperator | undefined, type: TypeNode | undefined, operatorType: Es2pandaTSOperatorType): TSTypeOperator { + return new TSTypeOperator(global.generatedEs2panda._UpdateTSTypeOperator(global.context, passNode(original), passNode(type), operatorType)) + } + get type(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSTypeOperatorTypeConst(global.context, this.peer)) + } + get isReadonly(): boolean { + return global.generatedEs2panda._TSTypeOperatorIsReadonlyConst(global.context, this.peer) + } + get isKeyof(): boolean { + return global.generatedEs2panda._TSTypeOperatorIsKeyofConst(global.context, this.peer) + } + get isUnique(): boolean { + return global.generatedEs2panda._TSTypeOperatorIsUniqueConst(global.context, this.peer) + } +} +export function isTSTypeOperator(node: AstNode): node is TSTypeOperator { + return node instanceof TSTypeOperator +} +if (!nodeByType.has(117)) { + nodeByType.set(117, TSTypeOperator) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameter.ts b/koala-wrapper/src/generated/peers/TSTypeParameter.ts new file mode 100644 index 000000000..28012faf1 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeParameter.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Identifier } from "./Identifier" +import { TypeNode } from "./TypeNode" +import { Es2pandaModifierFlags } from "./../Es2pandaEnums" +import { AnnotationUsage } from "./AnnotationUsage" +export class TSTypeParameter extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 118) + super(pointer) + + } + static createTSTypeParameter(name?: Identifier, constraint?: TypeNode, defaultType?: TypeNode): TSTypeParameter { + return new TSTypeParameter(global.generatedEs2panda._CreateTSTypeParameter(global.context, passNode(name), passNode(constraint), passNode(defaultType))) + } + static updateTSTypeParameter(original?: TSTypeParameter, name?: Identifier, constraint?: TypeNode, defaultType?: TypeNode): TSTypeParameter { + return new TSTypeParameter(global.generatedEs2panda._UpdateTSTypeParameter(global.context, passNode(original), passNode(name), passNode(constraint), passNode(defaultType))) + } + static create1TSTypeParameter(name: Identifier | undefined, constraint: TypeNode | undefined, defaultType: TypeNode | undefined, flags: Es2pandaModifierFlags): TSTypeParameter { + return new TSTypeParameter(global.generatedEs2panda._CreateTSTypeParameter1(global.context, passNode(name), passNode(constraint), passNode(defaultType), flags)) + } + static update1TSTypeParameter(original: TSTypeParameter | undefined, name: Identifier | undefined, constraint: TypeNode | undefined, defaultType: TypeNode | undefined, flags: Es2pandaModifierFlags): TSTypeParameter { + return new TSTypeParameter(global.generatedEs2panda._UpdateTSTypeParameter1(global.context, passNode(original), passNode(name), passNode(constraint), passNode(defaultType), flags)) + } + get name(): Identifier | undefined { + return unpackNode(global.generatedEs2panda._TSTypeParameterNameConst(global.context, this.peer)) + } + get constraint(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSTypeParameterConstraintConst(global.context, this.peer)) + } + /** @deprecated */ + setConstraint(constraint: TypeNode): this { + global.generatedEs2panda._TSTypeParameterSetConstraint(global.context, this.peer, passNode(constraint)) + return this + } + get defaultType(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSTypeParameterDefaultTypeConst(global.context, this.peer)) + } + /** @deprecated */ + setDefaultType(defaultType: TypeNode): this { + global.generatedEs2panda._TSTypeParameterSetDefaultType(global.context, this.peer, passNode(defaultType)) + return this + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._TSTypeParameterAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._TSTypeParameterSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isTSTypeParameter(node: AstNode): node is TSTypeParameter { + return node instanceof TSTypeParameter +} +if (!nodeByType.has(118)) { + nodeByType.set(118, TSTypeParameter) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts b/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts new file mode 100644 index 000000000..59f4ab594 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TSTypeParameter } from "./TSTypeParameter" +export class TSTypeParameterDeclaration extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 119) + super(pointer) + + } + static createTSTypeParameterDeclaration(params: readonly TSTypeParameter[], requiredParams: number): TSTypeParameterDeclaration { + return new TSTypeParameterDeclaration(global.generatedEs2panda._CreateTSTypeParameterDeclaration(global.context, passNodeArray(params), params.length, requiredParams)) + } + static updateTSTypeParameterDeclaration(original: TSTypeParameterDeclaration | undefined, params: readonly TSTypeParameter[], requiredParams: number): TSTypeParameterDeclaration { + return new TSTypeParameterDeclaration(global.generatedEs2panda._UpdateTSTypeParameterDeclaration(global.context, passNode(original), passNodeArray(params), params.length, requiredParams)) + } + get params(): readonly TSTypeParameter[] { + return unpackNodeArray(global.generatedEs2panda._TSTypeParameterDeclarationParamsConst(global.context, this.peer)) + } + /** @deprecated */ + addParam(param: TSTypeParameter): this { + global.generatedEs2panda._TSTypeParameterDeclarationAddParam(global.context, this.peer, passNode(param)) + return this + } + get requiredParams(): number { + return global.generatedEs2panda._TSTypeParameterDeclarationRequiredParamsConst(global.context, this.peer) + } +} +export function isTSTypeParameterDeclaration(node: AstNode): node is TSTypeParameterDeclaration { + return node instanceof TSTypeParameterDeclaration +} +if (!nodeByType.has(119)) { + nodeByType.set(119, TSTypeParameterDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts b/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts new file mode 100644 index 000000000..b6a23b329 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TypeNode } from "./TypeNode" +export class TSTypeParameterInstantiation extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 120) + super(pointer) + + } + static createTSTypeParameterInstantiation(params: readonly TypeNode[]): TSTypeParameterInstantiation { + return new TSTypeParameterInstantiation(global.generatedEs2panda._CreateTSTypeParameterInstantiation(global.context, passNodeArray(params), params.length)) + } + static updateTSTypeParameterInstantiation(original: TSTypeParameterInstantiation | undefined, params: readonly TypeNode[]): TSTypeParameterInstantiation { + return new TSTypeParameterInstantiation(global.generatedEs2panda._UpdateTSTypeParameterInstantiation(global.context, passNode(original), passNodeArray(params), params.length)) + } + get params(): readonly TypeNode[] { + return unpackNodeArray(global.generatedEs2panda._TSTypeParameterInstantiationParamsConst(global.context, this.peer)) + } +} +export function isTSTypeParameterInstantiation(node: AstNode): node is TSTypeParameterInstantiation { + return node instanceof TSTypeParameterInstantiation +} +if (!nodeByType.has(120)) { + nodeByType.set(120, TSTypeParameterInstantiation) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypePredicate.ts b/koala-wrapper/src/generated/peers/TSTypePredicate.ts new file mode 100644 index 000000000..551d62f98 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypePredicate.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +export class TSTypePredicate extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 121) + super(pointer) + + } + static createTSTypePredicate(parameterName: Expression | undefined, typeAnnotation: TypeNode | undefined, asserts: boolean): TSTypePredicate { + return new TSTypePredicate(global.generatedEs2panda._CreateTSTypePredicate(global.context, passNode(parameterName), passNode(typeAnnotation), asserts)) + } + static updateTSTypePredicate(original: TSTypePredicate | undefined, parameterName: Expression | undefined, typeAnnotation: TypeNode | undefined, asserts: boolean): TSTypePredicate { + return new TSTypePredicate(global.generatedEs2panda._UpdateTSTypePredicate(global.context, passNode(original), passNode(parameterName), passNode(typeAnnotation), asserts)) + } + get parameterName(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSTypePredicateParameterNameConst(global.context, this.peer)) + } + get typeAnnotation(): TypeNode | undefined { + return unpackNode(global.generatedEs2panda._TSTypePredicateTypeAnnotationConst(global.context, this.peer)) + } + get asserts(): boolean { + return global.generatedEs2panda._TSTypePredicateAssertsConst(global.context, this.peer) + } +} +export function isTSTypePredicate(node: AstNode): node is TSTypePredicate { + return node instanceof TSTypePredicate +} +if (!nodeByType.has(121)) { + nodeByType.set(121, TSTypePredicate) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeQuery.ts b/koala-wrapper/src/generated/peers/TSTypeQuery.ts new file mode 100644 index 000000000..d4576d1fa --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeQuery.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +export class TSTypeQuery extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 137) + super(pointer) + + } + static createTSTypeQuery(exprName?: Expression): TSTypeQuery { + return new TSTypeQuery(global.generatedEs2panda._CreateTSTypeQuery(global.context, passNode(exprName))) + } + static updateTSTypeQuery(original?: TSTypeQuery, exprName?: Expression): TSTypeQuery { + return new TSTypeQuery(global.generatedEs2panda._UpdateTSTypeQuery(global.context, passNode(original), passNode(exprName))) + } + get exprName(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSTypeQueryExprNameConst(global.context, this.peer)) + } +} +export function isTSTypeQuery(node: AstNode): node is TSTypeQuery { + return node instanceof TSTypeQuery +} +if (!nodeByType.has(137)) { + nodeByType.set(137, TSTypeQuery) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeReference.ts b/koala-wrapper/src/generated/peers/TSTypeReference.ts new file mode 100644 index 000000000..50e62aafb --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSTypeReference.ts @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +import { Expression } from "./Expression" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +import { Identifier } from "./Identifier" +export class TSTypeReference extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 128) + super(pointer) + + } + static createTSTypeReference(typeName?: Expression, typeParams?: TSTypeParameterInstantiation): TSTypeReference { + return new TSTypeReference(global.generatedEs2panda._CreateTSTypeReference(global.context, passNode(typeName), passNode(typeParams))) + } + static updateTSTypeReference(original?: TSTypeReference, typeName?: Expression, typeParams?: TSTypeParameterInstantiation): TSTypeReference { + return new TSTypeReference(global.generatedEs2panda._UpdateTSTypeReference(global.context, passNode(original), passNode(typeName), passNode(typeParams))) + } + get typeParams(): TSTypeParameterInstantiation | undefined { + return unpackNode(global.generatedEs2panda._TSTypeReferenceTypeParamsConst(global.context, this.peer)) + } + get typeName(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TSTypeReferenceTypeNameConst(global.context, this.peer)) + } +} +export function isTSTypeReference(node: AstNode): node is TSTypeReference { + return node instanceof TSTypeReference +} +if (!nodeByType.has(128)) { + nodeByType.set(128, TSTypeReference) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts b/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts new file mode 100644 index 000000000..9129d02d9 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSUndefinedKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 95) + super(pointer) + + } + static createTSUndefinedKeyword(): TSUndefinedKeyword { + return new TSUndefinedKeyword(global.generatedEs2panda._CreateTSUndefinedKeyword(global.context)) + } + static updateTSUndefinedKeyword(original?: TSUndefinedKeyword): TSUndefinedKeyword { + return new TSUndefinedKeyword(global.generatedEs2panda._UpdateTSUndefinedKeyword(global.context, passNode(original))) + } +} +export function isTSUndefinedKeyword(node: AstNode): node is TSUndefinedKeyword { + return node instanceof TSUndefinedKeyword +} +if (!nodeByType.has(95)) { + nodeByType.set(95, TSUndefinedKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUnionType.ts b/koala-wrapper/src/generated/peers/TSUnionType.ts new file mode 100644 index 000000000..406ecc416 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSUnionType.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSUnionType extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 103) + super(pointer) + + } + static createTSUnionType(types: readonly TypeNode[]): TSUnionType { + return new TSUnionType(global.generatedEs2panda._CreateTSUnionType(global.context, passNodeArray(types), types.length)) + } + static updateTSUnionType(original: TSUnionType | undefined, types: readonly TypeNode[]): TSUnionType { + return new TSUnionType(global.generatedEs2panda._UpdateTSUnionType(global.context, passNode(original), passNodeArray(types), types.length)) + } + get types(): readonly TypeNode[] { + return unpackNodeArray(global.generatedEs2panda._TSUnionTypeTypesConst(global.context, this.peer)) + } +} +export function isTSUnionType(node: AstNode): node is TSUnionType { + return node instanceof TSUnionType +} +if (!nodeByType.has(103)) { + nodeByType.set(103, TSUnionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts b/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts new file mode 100644 index 000000000..0371b243c --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSUnknownKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 96) + super(pointer) + + } + static createTSUnknownKeyword(): TSUnknownKeyword { + return new TSUnknownKeyword(global.generatedEs2panda._CreateTSUnknownKeyword(global.context)) + } + static updateTSUnknownKeyword(original?: TSUnknownKeyword): TSUnknownKeyword { + return new TSUnknownKeyword(global.generatedEs2panda._UpdateTSUnknownKeyword(global.context, passNode(original))) + } +} +export function isTSUnknownKeyword(node: AstNode): node is TSUnknownKeyword { + return node instanceof TSUnknownKeyword +} +if (!nodeByType.has(96)) { + nodeByType.set(96, TSUnknownKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSVoidKeyword.ts b/koala-wrapper/src/generated/peers/TSVoidKeyword.ts new file mode 100644 index 000000000..605cceb11 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TSVoidKeyword.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypeNode } from "./TypeNode" +export class TSVoidKeyword extends TypeNode { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 94) + super(pointer) + + } + static createTSVoidKeyword(): TSVoidKeyword { + return new TSVoidKeyword(global.generatedEs2panda._CreateTSVoidKeyword(global.context)) + } + static updateTSVoidKeyword(original?: TSVoidKeyword): TSVoidKeyword { + return new TSVoidKeyword(global.generatedEs2panda._UpdateTSVoidKeyword(global.context, passNode(original))) + } +} +export function isTSVoidKeyword(node: AstNode): node is TSVoidKeyword { + return node instanceof TSVoidKeyword +} +if (!nodeByType.has(94)) { + nodeByType.set(94, TSVoidKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts b/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts new file mode 100644 index 000000000..0ccbf0f08 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TemplateLiteral } from "./TemplateLiteral" +import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" +export class TaggedTemplateExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 141) + super(pointer) + + } + static createTaggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral, typeParams?: TSTypeParameterInstantiation): TaggedTemplateExpression { + return new TaggedTemplateExpression(global.generatedEs2panda._CreateTaggedTemplateExpression(global.context, passNode(tag), passNode(quasi), passNode(typeParams))) + } + static updateTaggedTemplateExpression(original?: TaggedTemplateExpression, tag?: Expression, quasi?: TemplateLiteral, typeParams?: TSTypeParameterInstantiation): TaggedTemplateExpression { + return new TaggedTemplateExpression(global.generatedEs2panda._UpdateTaggedTemplateExpression(global.context, passNode(original), passNode(tag), passNode(quasi), passNode(typeParams))) + } + get tag(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TaggedTemplateExpressionTagConst(global.context, this.peer)) + } + get quasi(): TemplateLiteral | undefined { + return unpackNode(global.generatedEs2panda._TaggedTemplateExpressionQuasiConst(global.context, this.peer)) + } + get typeParams(): TSTypeParameterInstantiation | undefined { + return unpackNode(global.generatedEs2panda._TaggedTemplateExpressionTypeParamsConst(global.context, this.peer)) + } +} +export function isTaggedTemplateExpression(node: AstNode): node is TaggedTemplateExpression { + return node instanceof TaggedTemplateExpression +} +if (!nodeByType.has(141)) { + nodeByType.set(141, TaggedTemplateExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TemplateElement.ts b/koala-wrapper/src/generated/peers/TemplateElement.ts new file mode 100644 index 000000000..0c4108f47 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TemplateElement.ts @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class TemplateElement extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 142) + super(pointer) + + } + static createTemplateElement(): TemplateElement { + return new TemplateElement(global.generatedEs2panda._CreateTemplateElement(global.context)) + } + static updateTemplateElement(original?: TemplateElement): TemplateElement { + return new TemplateElement(global.generatedEs2panda._UpdateTemplateElement(global.context, passNode(original))) + } + static create1TemplateElement(raw: string, cooked: string): TemplateElement { + return new TemplateElement(global.generatedEs2panda._CreateTemplateElement1(global.context, raw, cooked)) + } + static update1TemplateElement(original: TemplateElement | undefined, raw: string, cooked: string): TemplateElement { + return new TemplateElement(global.generatedEs2panda._UpdateTemplateElement1(global.context, passNode(original), raw, cooked)) + } + get raw(): string { + return unpackString(global.generatedEs2panda._TemplateElementRawConst(global.context, this.peer)) + } + get cooked(): string { + return unpackString(global.generatedEs2panda._TemplateElementCookedConst(global.context, this.peer)) + } +} +export function isTemplateElement(node: AstNode): node is TemplateElement { + return node instanceof TemplateElement +} +if (!nodeByType.has(142)) { + nodeByType.set(142, TemplateElement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TemplateLiteral.ts b/koala-wrapper/src/generated/peers/TemplateLiteral.ts new file mode 100644 index 000000000..58039a87e --- /dev/null +++ b/koala-wrapper/src/generated/peers/TemplateLiteral.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { TemplateElement } from "./TemplateElement" +export class TemplateLiteral extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 143) + super(pointer) + + } + static createTemplateLiteral(quasis: readonly TemplateElement[], expressions: readonly Expression[], multilineString: string): TemplateLiteral { + return new TemplateLiteral(global.generatedEs2panda._CreateTemplateLiteral(global.context, passNodeArray(quasis), quasis.length, passNodeArray(expressions), expressions.length, multilineString)) + } + static updateTemplateLiteral(original: TemplateLiteral | undefined, quasis: readonly TemplateElement[], expressions: readonly Expression[], multilineString: string): TemplateLiteral { + return new TemplateLiteral(global.generatedEs2panda._UpdateTemplateLiteral(global.context, passNode(original), passNodeArray(quasis), quasis.length, passNodeArray(expressions), expressions.length, multilineString)) + } + get quasis(): readonly TemplateElement[] { + return unpackNodeArray(global.generatedEs2panda._TemplateLiteralQuasisConst(global.context, this.peer)) + } + get expressions(): readonly Expression[] { + return unpackNodeArray(global.generatedEs2panda._TemplateLiteralExpressionsConst(global.context, this.peer)) + } +} +export function isTemplateLiteral(node: AstNode): node is TemplateLiteral { + return node instanceof TemplateLiteral +} +if (!nodeByType.has(143)) { + nodeByType.set(143, TemplateLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ThisExpression.ts b/koala-wrapper/src/generated/peers/ThisExpression.ts new file mode 100644 index 000000000..1ec6476d8 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ThisExpression.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class ThisExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 144) + super(pointer) + + } + static createThisExpression(): ThisExpression { + return new ThisExpression(global.generatedEs2panda._CreateThisExpression(global.context)) + } + static updateThisExpression(original?: ThisExpression): ThisExpression { + return new ThisExpression(global.generatedEs2panda._UpdateThisExpression(global.context, passNode(original))) + } +} +export function isThisExpression(node: AstNode): node is ThisExpression { + return node instanceof ThisExpression +} +if (!nodeByType.has(144)) { + nodeByType.set(144, ThisExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ThrowStatement.ts b/koala-wrapper/src/generated/peers/ThrowStatement.ts new file mode 100644 index 000000000..74cc30e59 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ThrowStatement.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Expression } from "./Expression" +export class ThrowStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 146) + super(pointer) + + } + static createThrowStatement(argument?: Expression): ThrowStatement { + return new ThrowStatement(global.generatedEs2panda._CreateThrowStatement(global.context, passNode(argument))) + } + static updateThrowStatement(original?: ThrowStatement, argument?: Expression): ThrowStatement { + return new ThrowStatement(global.generatedEs2panda._UpdateThrowStatement(global.context, passNode(original), passNode(argument))) + } + get argument(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ThrowStatementArgumentConst(global.context, this.peer)) + } +} +export function isThrowStatement(node: AstNode): node is ThrowStatement { + return node instanceof ThrowStatement +} +if (!nodeByType.has(146)) { + nodeByType.set(146, ThrowStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TryStatement.ts b/koala-wrapper/src/generated/peers/TryStatement.ts new file mode 100644 index 000000000..c855b8bfa --- /dev/null +++ b/koala-wrapper/src/generated/peers/TryStatement.ts @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { BlockStatement } from "./BlockStatement" +import { CatchClause } from "./CatchClause" +export class TryStatement extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 147) + super(pointer) + + } + get finallyBlock(): BlockStatement | undefined { + return unpackNode(global.generatedEs2panda._TryStatementFinallyBlockConst(global.context, this.peer)) + } + get block(): BlockStatement | undefined { + return unpackNode(global.generatedEs2panda._TryStatementBlockConst(global.context, this.peer)) + } + get hasFinalizer(): boolean { + return global.generatedEs2panda._TryStatementHasFinalizerConst(global.context, this.peer) + } + get catchClauses(): readonly CatchClause[] { + return unpackNodeArray(global.generatedEs2panda._TryStatementCatchClausesConst(global.context, this.peer)) + } + get finallyCanCompleteNormally(): boolean { + return global.generatedEs2panda._TryStatementFinallyCanCompleteNormallyConst(global.context, this.peer) + } + /** @deprecated */ + setFinallyCanCompleteNormally(finallyCanCompleteNormally: boolean): this { + global.generatedEs2panda._TryStatementSetFinallyCanCompleteNormally(global.context, this.peer, finallyCanCompleteNormally) + return this + } +} +export function isTryStatement(node: AstNode): node is TryStatement { + return node instanceof TryStatement +} +if (!nodeByType.has(147)) { + nodeByType.set(147, TryStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TypeNode.ts b/koala-wrapper/src/generated/peers/TypeNode.ts new file mode 100644 index 000000000..18b915e47 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TypeNode.ts @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { AnnotationUsage } from "./AnnotationUsage" +export class TypeNode extends Expression { + constructor(pointer: KNativePointer) { + super(pointer) + + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._TypeNodeAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._TypeNodeSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isTypeNode(node: AstNode): node is TypeNode { + return node instanceof TypeNode +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TypedAstNode.ts b/koala-wrapper/src/generated/peers/TypedAstNode.ts new file mode 100644 index 000000000..d749fe3be --- /dev/null +++ b/koala-wrapper/src/generated/peers/TypedAstNode.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +export class TypedAstNode extends AstNode { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isTypedAstNode(node: AstNode): node is TypedAstNode { + return node instanceof TypedAstNode +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TypedStatement.ts b/koala-wrapper/src/generated/peers/TypedStatement.ts new file mode 100644 index 000000000..a87344b96 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TypedStatement.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +export class TypedStatement extends Statement { + constructor(pointer: KNativePointer) { + super(pointer) + + } +} +export function isTypedStatement(node: AstNode): node is TypedStatement { + return node instanceof TypedStatement +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TypeofExpression.ts b/koala-wrapper/src/generated/peers/TypeofExpression.ts new file mode 100644 index 000000000..0c80ae8e8 --- /dev/null +++ b/koala-wrapper/src/generated/peers/TypeofExpression.ts @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class TypeofExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 145) + super(pointer) + + } + static createTypeofExpression(argument?: Expression): TypeofExpression { + return new TypeofExpression(global.generatedEs2panda._CreateTypeofExpression(global.context, passNode(argument))) + } + static updateTypeofExpression(original?: TypeofExpression, argument?: Expression): TypeofExpression { + return new TypeofExpression(global.generatedEs2panda._UpdateTypeofExpression(global.context, passNode(original), passNode(argument))) + } + get argument(): Expression | undefined { + return unpackNode(global.generatedEs2panda._TypeofExpressionArgumentConst(global.context, this.peer)) + } +} +export function isTypeofExpression(node: AstNode): node is TypeofExpression { + return node instanceof TypeofExpression +} +if (!nodeByType.has(145)) { + nodeByType.set(145, TypeofExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UnaryExpression.ts b/koala-wrapper/src/generated/peers/UnaryExpression.ts new file mode 100644 index 000000000..2b2d1aec7 --- /dev/null +++ b/koala-wrapper/src/generated/peers/UnaryExpression.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Es2pandaTokenType } from "./../Es2pandaEnums" +export class UnaryExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 148) + super(pointer) + + } + static createUnaryExpression(argument: Expression | undefined, unaryOperator: Es2pandaTokenType): UnaryExpression { + return new UnaryExpression(global.generatedEs2panda._CreateUnaryExpression(global.context, passNode(argument), unaryOperator)) + } + static updateUnaryExpression(original: UnaryExpression | undefined, argument: Expression | undefined, unaryOperator: Es2pandaTokenType): UnaryExpression { + return new UnaryExpression(global.generatedEs2panda._UpdateUnaryExpression(global.context, passNode(original), passNode(argument), unaryOperator)) + } + get operatorType(): Es2pandaTokenType { + return global.generatedEs2panda._UnaryExpressionOperatorTypeConst(global.context, this.peer) + } + get argument(): Expression | undefined { + return unpackNode(global.generatedEs2panda._UnaryExpressionArgumentConst(global.context, this.peer)) + } +} +export function isUnaryExpression(node: AstNode): node is UnaryExpression { + return node instanceof UnaryExpression +} +if (!nodeByType.has(148)) { + nodeByType.set(148, UnaryExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UndefinedLiteral.ts b/koala-wrapper/src/generated/peers/UndefinedLiteral.ts new file mode 100644 index 000000000..833805c1f --- /dev/null +++ b/koala-wrapper/src/generated/peers/UndefinedLiteral.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Literal } from "./Literal" +export class UndefinedLiteral extends Literal { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 51) + super(pointer) + + } + static createUndefinedLiteral(): UndefinedLiteral { + return new UndefinedLiteral(global.generatedEs2panda._CreateUndefinedLiteral(global.context)) + } + static updateUndefinedLiteral(original?: UndefinedLiteral): UndefinedLiteral { + return new UndefinedLiteral(global.generatedEs2panda._UpdateUndefinedLiteral(global.context, passNode(original))) + } +} +export function isUndefinedLiteral(node: AstNode): node is UndefinedLiteral { + return node instanceof UndefinedLiteral +} +if (!nodeByType.has(51)) { + nodeByType.set(51, UndefinedLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UpdateExpression.ts b/koala-wrapper/src/generated/peers/UpdateExpression.ts new file mode 100644 index 000000000..5c1b8d6f1 --- /dev/null +++ b/koala-wrapper/src/generated/peers/UpdateExpression.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +import { Es2pandaTokenType } from "./../Es2pandaEnums" +export class UpdateExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 149) + super(pointer) + + } + static createUpdateExpression(argument: Expression | undefined, updateOperator: Es2pandaTokenType, isPrefix: boolean): UpdateExpression { + return new UpdateExpression(global.generatedEs2panda._CreateUpdateExpression(global.context, passNode(argument), updateOperator, isPrefix)) + } + static updateUpdateExpression(original: UpdateExpression | undefined, argument: Expression | undefined, updateOperator: Es2pandaTokenType, isPrefix: boolean): UpdateExpression { + return new UpdateExpression(global.generatedEs2panda._UpdateUpdateExpression(global.context, passNode(original), passNode(argument), updateOperator, isPrefix)) + } + get operatorType(): Es2pandaTokenType { + return global.generatedEs2panda._UpdateExpressionOperatorTypeConst(global.context, this.peer) + } + get argument(): Expression | undefined { + return unpackNode(global.generatedEs2panda._UpdateExpressionArgumentConst(global.context, this.peer)) + } + get isPrefix(): boolean { + return global.generatedEs2panda._UpdateExpressionIsPrefixConst(global.context, this.peer) + } +} +export function isUpdateExpression(node: AstNode): node is UpdateExpression { + return node instanceof UpdateExpression +} +if (!nodeByType.has(149)) { + nodeByType.set(149, UpdateExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ValidationInfo.ts b/koala-wrapper/src/generated/peers/ValidationInfo.ts new file mode 100644 index 000000000..45e6b8212 --- /dev/null +++ b/koala-wrapper/src/generated/peers/ValidationInfo.ts @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +export class ValidationInfo extends ArktsObject { + constructor(pointer: KNativePointer) { + super(pointer) + + } + static createValidationInfo(): ValidationInfo { + return new ValidationInfo(global.generatedEs2panda._CreateValidationInfo(global.context)) + } + get fail(): boolean { + return global.generatedEs2panda._ValidationInfoFailConst(global.context, this.peer) + } +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/VariableDeclaration.ts b/koala-wrapper/src/generated/peers/VariableDeclaration.ts new file mode 100644 index 000000000..751968ae5 --- /dev/null +++ b/koala-wrapper/src/generated/peers/VariableDeclaration.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Statement } from "./Statement" +import { Es2pandaVariableDeclarationKind } from "./../Es2pandaEnums" +import { VariableDeclarator } from "./VariableDeclarator" +import { Decorator } from "./Decorator" +import { AnnotationUsage } from "./AnnotationUsage" +export class VariableDeclaration extends Statement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 150) + super(pointer) + + } + static createVariableDeclaration(kind: Es2pandaVariableDeclarationKind, declarators: readonly VariableDeclarator[]): VariableDeclaration { + return new VariableDeclaration(global.generatedEs2panda._CreateVariableDeclaration(global.context, kind, passNodeArray(declarators), declarators.length)) + } + static updateVariableDeclaration(original: VariableDeclaration | undefined, kind: Es2pandaVariableDeclarationKind, declarators: readonly VariableDeclarator[]): VariableDeclaration { + return new VariableDeclaration(global.generatedEs2panda._UpdateVariableDeclaration(global.context, passNode(original), kind, passNodeArray(declarators), declarators.length)) + } + get declarators(): readonly VariableDeclarator[] { + return unpackNodeArray(global.generatedEs2panda._VariableDeclarationDeclaratorsConst(global.context, this.peer)) + } + get kind(): Es2pandaVariableDeclarationKind { + return global.generatedEs2panda._VariableDeclarationKindConst(global.context, this.peer) + } + get decorators(): readonly Decorator[] { + return unpackNodeArray(global.generatedEs2panda._VariableDeclarationDecoratorsConst(global.context, this.peer)) + } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray(global.generatedEs2panda._VariableDeclarationAnnotationsConst(global.context, this.peer)) + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._VariableDeclarationSetAnnotations(global.context, this.peer, passNodeArray(annotations), annotations.length) + return this + } +} +export function isVariableDeclaration(node: AstNode): node is VariableDeclaration { + return node instanceof VariableDeclaration +} +if (!nodeByType.has(150)) { + nodeByType.set(150, VariableDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/VariableDeclarator.ts b/koala-wrapper/src/generated/peers/VariableDeclarator.ts new file mode 100644 index 000000000..e0d9cb077 --- /dev/null +++ b/koala-wrapper/src/generated/peers/VariableDeclarator.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { TypedStatement } from "./TypedStatement" +import { Es2pandaVariableDeclaratorFlag } from "./../Es2pandaEnums" +import { Expression } from "./Expression" +export class VariableDeclarator extends TypedStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 151) + super(pointer) + + } + static createVariableDeclarator(flag: Es2pandaVariableDeclaratorFlag, ident?: Expression): VariableDeclarator { + return new VariableDeclarator(global.generatedEs2panda._CreateVariableDeclarator(global.context, flag, passNode(ident))) + } + static updateVariableDeclarator(original: VariableDeclarator | undefined, flag: Es2pandaVariableDeclaratorFlag, ident?: Expression): VariableDeclarator { + return new VariableDeclarator(global.generatedEs2panda._UpdateVariableDeclarator(global.context, passNode(original), flag, passNode(ident))) + } + static create1VariableDeclarator(flag: Es2pandaVariableDeclaratorFlag, ident?: Expression, init?: Expression): VariableDeclarator { + return new VariableDeclarator(global.generatedEs2panda._CreateVariableDeclarator1(global.context, flag, passNode(ident), passNode(init))) + } + static update1VariableDeclarator(original: VariableDeclarator | undefined, flag: Es2pandaVariableDeclaratorFlag, ident?: Expression, init?: Expression): VariableDeclarator { + return new VariableDeclarator(global.generatedEs2panda._UpdateVariableDeclarator1(global.context, passNode(original), flag, passNode(ident), passNode(init))) + } + get init(): Expression | undefined { + return unpackNode(global.generatedEs2panda._VariableDeclaratorInitConst(global.context, this.peer)) + } + /** @deprecated */ + setInit(init: Expression): this { + global.generatedEs2panda._VariableDeclaratorSetInit(global.context, this.peer, passNode(init)) + return this + } + get id(): Expression | undefined { + return unpackNode(global.generatedEs2panda._VariableDeclaratorIdConst(global.context, this.peer)) + } + get flag(): Es2pandaVariableDeclaratorFlag { + return global.generatedEs2panda._VariableDeclaratorFlag(global.context, this.peer) + } +} +export function isVariableDeclarator(node: AstNode): node is VariableDeclarator { + return node instanceof VariableDeclarator +} +if (!nodeByType.has(151)) { + nodeByType.set(151, VariableDeclarator) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/WhileStatement.ts b/koala-wrapper/src/generated/peers/WhileStatement.ts new file mode 100644 index 000000000..f71a1d5dd --- /dev/null +++ b/koala-wrapper/src/generated/peers/WhileStatement.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { LoopStatement } from "./LoopStatement" +import { Expression } from "./Expression" +import { Statement } from "./Statement" +export class WhileStatement extends LoopStatement { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 152) + super(pointer) + + } + static createWhileStatement(test?: Expression, body?: Statement): WhileStatement { + return new WhileStatement(global.generatedEs2panda._CreateWhileStatement(global.context, passNode(test), passNode(body))) + } + static updateWhileStatement(original?: WhileStatement, test?: Expression, body?: Statement): WhileStatement { + return new WhileStatement(global.generatedEs2panda._UpdateWhileStatement(global.context, passNode(original), passNode(test), passNode(body))) + } + get test(): Expression | undefined { + return unpackNode(global.generatedEs2panda._WhileStatementTestConst(global.context, this.peer)) + } + get body(): Statement | undefined { + return unpackNode(global.generatedEs2panda._WhileStatementBodyConst(global.context, this.peer)) + } +} +export function isWhileStatement(node: AstNode): node is WhileStatement { + return node instanceof WhileStatement +} +if (!nodeByType.has(152)) { + nodeByType.set(152, WhileStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/YieldExpression.ts b/koala-wrapper/src/generated/peers/YieldExpression.ts new file mode 100644 index 000000000..55c0b9022 --- /dev/null +++ b/koala-wrapper/src/generated/peers/YieldExpression.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + Es2pandaAstNodeType, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" + +import { Expression } from "./Expression" +export class YieldExpression extends Expression { + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 153) + super(pointer) + + } + static createYieldExpression(argument: Expression | undefined, isDelegate: boolean): YieldExpression { + return new YieldExpression(global.generatedEs2panda._CreateYieldExpression(global.context, passNode(argument), isDelegate)) + } + static updateYieldExpression(original: YieldExpression | undefined, argument: Expression | undefined, isDelegate: boolean): YieldExpression { + return new YieldExpression(global.generatedEs2panda._UpdateYieldExpression(global.context, passNode(original), passNode(argument), isDelegate)) + } + get hasDelegate(): boolean { + return global.generatedEs2panda._YieldExpressionHasDelegateConst(global.context, this.peer) + } + get argument(): Expression | undefined { + return unpackNode(global.generatedEs2panda._YieldExpressionArgumentConst(global.context, this.peer)) + } +} +export function isYieldExpression(node: AstNode): node is YieldExpression { + return node instanceof YieldExpression +} +if (!nodeByType.has(153)) { + nodeByType.set(153, YieldExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/reexport-for-generated.ts b/koala-wrapper/src/reexport-for-generated.ts new file mode 100644 index 000000000..37e3c6f56 --- /dev/null +++ b/koala-wrapper/src/reexport-for-generated.ts @@ -0,0 +1,32 @@ +/* + * 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. + */ +export { KNativePointer } from "@koalaui/interop" +export { AstNode } from "./arkts-api/peers/AstNode" +export { ArktsObject } from "./arkts-api/peers/ArktsObject" +export { Es2pandaAstNodeType } from "./Es2pandaEnums" +export { + passNode, + unpackNonNullableNode, + unpackNodeArray, + passNodeArray, + unpackNode, + unpackNonNullableObject, + unpackString, + unpackObject, + assertValidPeer +} from "./arkts-api/utilities/private" +export { nodeByType } from "./arkts-api/class-by-peer" +export { global } from "./arkts-api/static/global" +export { Es2pandaMemberExpressionKind } from "./generated/Es2pandaEnums" diff --git a/koala-wrapper/src/utils.ts b/koala-wrapper/src/utils.ts new file mode 100644 index 000000000..9ef0b4d51 --- /dev/null +++ b/koala-wrapper/src/utils.ts @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2022-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. + */ + +export function throwError(error: string): never { + throw new Error(error) +} + +export function withWarning(value: T, message: string): T { + console.warn(message) + return value +} + +export function isNumber(value: any): value is number { + return typeof value === `number` +} + +function replacePercentOutsideStrings(code: string): string { + const stringPattern = /("[^"]*"|'[^']*'|`[^`]*`)/g; + const percentPattern = /(?(); + strings.forEach((string) => { + const placeholder = `__STRING_PLACEHOLDER_${placeholderCounter++}__`; + placeholderMap.set(placeholder, string); + code = code.replace(string, placeholder); + }); + + code = code.replace(percentPattern, '_'); + + placeholderMap.forEach((originalString, placeholder) => { + code = code.replace(new RegExp(placeholder, 'g'), originalString); + }); + + return code; +} + +function replaceIllegalHashes(code: string): string { + const stringPattern = /("[^"]*"|'[^']*'|`[^`]*`)/g; + const strings = code.match(stringPattern) || []; + + let placeholderCounter = 0; + const placeholderMap = new Map(); + strings.forEach((string) => { + const placeholder = `__STRING_PLACEHOLDER_${placeholderCounter++}__`; + placeholderMap.set(placeholder, string); + code = code.replace(string, placeholder); + }); + + code = code.replace(/#/g, '_'); + + placeholderMap.forEach((originalString, placeholder) => { + code = code.replace(new RegExp(placeholder, 'g'), originalString); + }); + + return code; +} + +/* + TODO: + The lowerings insert %% and other special symbols into names of temporary variables. + Until we keep feeding ast dumps back to the parser this function is needed. + */ +export function filterSource(text: string): string { + const filtered = replaceIllegalHashes(replacePercentOutsideStrings(text)) + .replaceAll("", "_cctor_") + + return filtered +} + +export function getEnumName(enumType: any, value: number): string | undefined { + return enumType[value]; +} \ No newline at end of file diff --git a/koala-wrapper/tools/issue_gen.mjs b/koala-wrapper/tools/issue_gen.mjs new file mode 100644 index 000000000..7d2e24fd4 --- /dev/null +++ b/koala-wrapper/tools/issue_gen.mjs @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as fs from 'fs' +import * as path from 'path' + +process.chdir(path.resolve('./')) + +const issue_src = fs.readFileSync('../playground/src/playground.cc', { encoding: 'utf8', flag: 'r' }) + +const component_src = +` +### Component + +Plugin API + +` + +const revision_src = +` +### Revision + +"@panda/sdk": "1.5.0-dev.9184" + +` + +const reproduction_src = +` +### Reproduction + +\`\`\` +${issue_src} +\`\`\` + +` + +// TODO: +const log = `` + +const log_src = +` +### Log + +\`\`\` +${log} +\`\`\` +` + +console.log( + component_src + + revision_src + + reproduction_src + + log_src +) diff --git a/koala-wrapper/tsconfig.json b/koala-wrapper/tsconfig.json new file mode 100644 index 000000000..bb0b7b59b --- /dev/null +++ b/koala-wrapper/tsconfig.json @@ -0,0 +1,38 @@ +{ + "compilerOptions": { + "target": "es2017", + "lib": ["ESNext", "ESNext.WeakRef", "DOM"], + "moduleResolution": "node", + "composite": true, + "incremental": true, + "declarationMap": true, + "sourceMap": true, + "declaration": true, + "noEmitOnError": true, + "strict": true, + "skipLibCheck": true, + "removeComments": false, + "outDir": "build", + "baseUrl": ".", + "rootDir": ".", + "module": "CommonJS", + "paths": { + "@koalaui/interop": [ + "./koalaui/interop/dist/lib/src/interop/" + ], + "@koalaui/common": [ + "./koalaui/common/dist/lib/src/" + ], + "@koalaui/compat": [ + "./koalaui/compat/dist/src/" + ] + } + }, + "include": [ + "./src/**/*.ts", + ], + "exclude": [ + "./src/ts-api/**/*.ts", + "./koalaui" + ] +} -- Gitee From b3180036cfc2bf299d3bb7378c26663632be04b7 Mon Sep 17 00:00:00 2001 From: Bojiang Date: Tue, 1 Apr 2025 20:46:35 +0800 Subject: [PATCH 003/123] jiangbo91@huawei.com Signed-off-by: Bojiang Change-Id: I808be817858899aa17ce1c732c94e69a980a70d8 --- BUILD.gn | 15 ++++++++++++--- compiler/build_declarations_file.js | 4 ++-- compiler/build_kitConfigs_file.js | 8 ++++++-- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 88a5392a1..8bf020a7a 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -14,6 +14,7 @@ import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") import("//build/ohos_var.gni") +import("//build/templates/bpf/ohos_bpf_config.gni") import("//foundation/arkui/ace_engine/ace_config.gni") if (sdk_build_public) { import("//out/sdk-public/public_interface/sdk-js/interface_config.gni") @@ -46,6 +47,11 @@ action("build_ets_loader_library") { ":install_arkguard_tsc", ":server", ] + if (sdk_build_public) { + deps += [ "//out/sdk-public/public_interface/sdk-js:ets_component" ] + } else { + deps += [ "//interface/sdk-js:ets_component" ] + } script = "build_ets_loader_library.py" depfile = "$target_gen_dir/$target_name.d" outputs = [ @@ -63,14 +69,17 @@ action("build_ets_loader_library") { } else { _ace_config_dir = "//prebuilts/ace-toolkit/ets-loader/compiler" } - _declarations_file_dir = "//interface/sdk-js/api/@internal/component/ets" + input_project_dir = "//interface/sdk-js" + if (sdk_build_public || product_name == "ohos-sdk") { + input_project_dir = "//out/sdk-public/public_interface/sdk-js" + } + _declarations_file_dir = + input_project_dir + "/ets/${bpf_inc_out_dir}/ets_component" _kit_configs_file_dir = "//interface/sdk-js/kits" _kit_apis_file_dir = "//interface/sdk-js/api" _arkts_apis_file_dir = "//interface/sdk-js/arkts" isPublic = "false" if (sdk_build_public) { - _declarations_file_dir = - "//out/sdk-public/public_interface/sdk-js/api/@internal/component/ets" _kit_configs_file_dir = "//out/sdk-public/public_interface/sdk-js/kits" _kit_apis_file_dir = "//out/sdk-public/public_interface/sdk-js/api" _arkts_apis_file_dir = "//out/sdk-public/public_interface/sdk-js/arkts" diff --git a/compiler/build_declarations_file.js b/compiler/build_declarations_file.js index 695d29691..d3f4782eb 100644 --- a/compiler/build_declarations_file.js +++ b/compiler/build_declarations_file.js @@ -36,8 +36,8 @@ const addTSAttributeSet = ['AlphabetIndexer', 'Animator', 'Badge', 'Blank', 'But generateTargetFile(process.argv[2], process.argv[3]); function generateTargetFile(filePath, output) { const files = []; - const globalTsFile = path.resolve(filePath, '../../ets/global.d.ts'); - const featureAbilityPath = path.resolve(filePath, '../../../common/full/featureability.d.ts'); + const globalTsFile = path.resolve(filePath, '../ets_internal_api/global.d.ts'); + const featureAbilityPath = path.resolve(filePath, '../internal_full/featureability.d.ts'); const middleTsFile = path.resolve(filePath, 'middle_class.d.ts'); if (fs.existsSync(globalTsFile)) { files.push(globalTsFile); diff --git a/compiler/build_kitConfigs_file.js b/compiler/build_kitConfigs_file.js index cdbfce6a5..af72535e1 100644 --- a/compiler/build_kitConfigs_file.js +++ b/compiler/build_kitConfigs_file.js @@ -104,7 +104,7 @@ function readFile(dir, fileDir) { const status = fs.statSync(filePath); if (status.isDirectory()) { readFile(filePath, fileDir); - } else { + } else if (filePath.endsWith('.d.ts')) { fileDir.push(filePath); } }); @@ -115,12 +115,16 @@ function readSystemApis(dir, fileDir) { files.forEach(file => { const filePath = path.join(dir, file); const status = fs.statSync(filePath); - if (!status.isDirectory()) { + if (!status.isDirectory() && !hasSameApi(filePath)) { fileDir.push(file); } }); } +function hasSameApi(filePath) { + return filePath.endsWith('.d.ets') && fs.existsSync(filePath.replace('.d.ets', '.d.ts')); +} + function mkDir(filePath) { const parent = path.join(filePath, '..'); if (!(fs.existsSync(parent) && !fs.statSync(parent).isFile())) { -- Gitee From b319f14328a38cf048cc3bab4500ea2d0f73be3c Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Sat, 29 Mar 2025 19:45:33 +0800 Subject: [PATCH 004/123] fix failed to add import in external source Signed-off-by: Jiakai Shi Change-Id: Ib6ab91b2a51cc5b37fccc869c41845321640f064 --- arkui-plugins/common/abstract-visitor.ts | 5 +++- arkui-plugins/common/program-visitor.ts | 7 +++--- .../memo-plugins/import-transformer.ts | 2 +- arkui-plugins/memo-plugins/memo-factory.ts | 7 ++++-- .../memo-plugins/memo-transformer.ts | 2 +- .../ui-plugins/component-transformer.ts | 24 +++++++++---------- .../ui-plugins/entry-translators/factory.ts | 24 +++++++++---------- .../ui-plugins/preprocessor-transform.ts | 7 ++++-- koala-wrapper/native/src/bridges.cc | 8 ++++--- koala-wrapper/src/Es2pandaNativeModule.ts | 2 +- .../src/arkts-api/utilities/public.ts | 5 ++-- 11 files changed, 51 insertions(+), 42 deletions(-) diff --git a/arkui-plugins/common/abstract-visitor.ts b/arkui-plugins/common/abstract-visitor.ts index 3117118b9..bccf6408a 100644 --- a/arkui-plugins/common/abstract-visitor.ts +++ b/arkui-plugins/common/abstract-visitor.ts @@ -17,16 +17,19 @@ import * as arkts from "@koalaui/libarkts" export interface VisitorOptions { isExternal?: boolean, - externalSourceName?: string + externalSourceName?: string, + program?: arkts.Program } export abstract class AbstractVisitor implements VisitorOptions { public isExternal: boolean; public externalSourceName?: string; + public program?: arkts.Program; constructor(options?: VisitorOptions) { this.isExternal = options?.isExternal ?? false; this.externalSourceName = options?.externalSourceName; + this.program = options?.program; } indentation = 0 diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 56f796690..68ac1e365 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -65,7 +65,7 @@ export class ProgramVisitor extends AbstractVisitor { getDumpFileName(this.state, "ORI", undefined, name), true ); - const script = this.visitor(currProgram.astNode, name); + const script = this.visitor(currProgram.astNode, currProgram, name); if (script) { debugDump( script.dumpSrc(), @@ -94,17 +94,18 @@ export class ProgramVisitor extends AbstractVisitor { } let programScript = program.astNode; - programScript = this.visitor(programScript, this.externalSourceName); + programScript = this.visitor(programScript, program, this.externalSourceName); return program; } - visitor(node: arkts.AstNode, externalSourceName?: string): arkts.EtsScript { + visitor(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): arkts.EtsScript { let script: arkts.EtsScript = node as arkts.EtsScript; let count: number = 0; for (const transformer of this.visitors) { transformer.isExternal = !!externalSourceName; transformer.externalSourceName = externalSourceName; + transformer.program = program; script = transformer.visitor(script) as arkts.EtsScript; transformer.reset(); arkts.setAllParents(script); diff --git a/arkui-plugins/memo-plugins/import-transformer.ts b/arkui-plugins/memo-plugins/import-transformer.ts index aece85ce4..4821e9c94 100644 --- a/arkui-plugins/memo-plugins/import-transformer.ts +++ b/arkui-plugins/memo-plugins/import-transformer.ts @@ -20,7 +20,7 @@ import { factory } from "./memo-factory" export class ImportTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { if (node instanceof arkts.EtsScript) { - factory.createContextTypesImportDeclaration(); + factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext.program); return arkts.factory.updateEtsScript( node, node.statements diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index 94bfcc855..135d64fdf 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -31,7 +31,7 @@ export class factory { ) } // TODO: Currently, import declaration can only be inserted at after-parsed stage. - static createContextTypesImportDeclaration(): void { + static createContextTypesImportDeclaration(program?: arkts.Program): void { const source: arkts.StringLiteral = arkts.factory.createStringLiteral(RuntimeNames.CONTEXT_TYPE_DEFAULT_IMPORT); // const resolvedSource: arkts.StringLiteral = arkts.factory.create1StringLiteral( // arkts.ImportPathManager.create().resolvePath('', source.str) @@ -45,7 +45,10 @@ export class factory { arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE ) // Insert this import at the top of the script's statements. - arkts.importDeclarationInsert(importDecl); + if (!program) { + throw Error("Failed to insert import: Transformer has no program"); + } + arkts.importDeclarationInsert(importDecl, program); return; } diff --git a/arkui-plugins/memo-plugins/memo-transformer.ts b/arkui-plugins/memo-plugins/memo-transformer.ts index 5fd6fe00a..118f294ef 100644 --- a/arkui-plugins/memo-plugins/memo-transformer.ts +++ b/arkui-plugins/memo-plugins/memo-transformer.ts @@ -39,7 +39,7 @@ export default function memoTransformer( const returnTransformer = new ReturnTransformer() const signatureTransformer = new SignatureTransformer() const functionTransformer = new FunctionTransformer({ positionalIdTracker, parameterTransformer, returnTransformer, signatureTransformer }) - factory.createContextTypesImportDeclaration(); + factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext.program); return functionTransformer.visitor( arkts.factory.updateEtsScript( node, diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index ef8a660fc..cf7942de2 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -142,19 +142,17 @@ export class ComponentTransformer extends AbstractVisitor { const imported: arkts.Identifier = arkts.factory.createIdentifier( CustomComponentNames.COMPONENT_CLASS_NAME ); - const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( - source, - [ - arkts.factory.createImportSpecifier( - imported, - imported - ) - ], - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE - ) // Insert this import at the top of the script's statements. - arkts.importDeclarationInsert(importDecl); - return; + if (!this.program) { + throw Error("Failed to insert import: Transformer has no program"); + } + factory.createAndInsertImportDeclaration( + source, + imported, + imported, + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, + this.program + ); } processEtsScript(node: arkts.EtsScript): arkts.EtsScript { @@ -172,7 +170,7 @@ export class ComponentTransformer extends AbstractVisitor { } if (this.entryNames.length > 0) { - if (!this.isEntryPointImported) entryFactory.createAndInsertEntryPointImport(); + if (!this.isEntryPointImported) entryFactory.createAndInsertEntryPointImport(this.program); // TODO: normally, we should only have at most one @Entry component in a single file. // probably need to handle error message here. updateStatements.push( diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index 99404e7b1..dd4992100 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -248,25 +248,23 @@ export class factory { * create and insert `import { EntryPoint as EntryPoint } from "@ohos.arkui.UserView";` * to the top of script's statements. */ - static createAndInsertEntryPointImport() { + static createAndInsertEntryPointImport(program?: arkts.Program) { const source: arkts.StringLiteral = arkts.factory.create1StringLiteral( EntryWrapperNames.ENTRY_DEFAULT_IMPORT ); const imported: arkts.Identifier = arkts.factory.createIdentifier( EntryWrapperNames.ENTRY_POINT_CLASS_NAME ); - const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( - source, - [ - arkts.factory.createImportSpecifier( - imported, - imported - ) - ], - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE - ) // Insert this import at the top of the script's statements. - arkts.importDeclarationInsert(importDecl); - return; + if (!program) { + throw Error("Failed to insert import: Transformer has no program"); + } + uiFactory.createAndInsertImportDeclaration( + source, + imported, + imported, + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, + program + ); } } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 57ce8393f..325bfaf33 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -128,6 +128,9 @@ export class PreprocessorTransformer extends AbstractVisitor { } updateScriptWithImport(): void { + if (!this.program) { + throw Error("Failed to insert import: Transformer has no program"); + } new Set(this.outNameArr).forEach((item: string) => { const source: string = this.getSourceDependency(item); const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( @@ -135,10 +138,10 @@ export class PreprocessorTransformer extends AbstractVisitor { [factory.createAdditionalImportSpecifier(item, item)], arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE ); - arkts.importDeclarationInsert(newImport); + arkts.importDeclarationInsert(newImport, this.program!); }); this.structInterfaceImport.forEach((element: arkts.ETSImportDeclaration) => { - arkts.importDeclarationInsert(element); + arkts.importDeclarationInsert(element, this.program!); }); } diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index 1823e99e4..b341d79ab 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -288,14 +288,16 @@ KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPt } KOALA_INTEROP_4(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean) -void impl_InsertETSImportDeclarationAndParse(KNativePointer context, KNativePointer importDeclaration) +void impl_InsertETSImportDeclarationAndParse(KNativePointer context, KNativePointer program, + KNativePointer importDeclaration) { const auto _context = reinterpret_cast(context); + const auto _program = reinterpret_cast(program); const auto _ast = reinterpret_cast(importDeclaration); - GetImpl()->InsertETSImportDeclarationAndParse(_context, _ast); + GetImpl()->InsertETSImportDeclarationAndParse(_context, _program, _ast); return ; } -KOALA_INTEROP_V2(InsertETSImportDeclarationAndParse, KNativePointer, KNativePointer); +KOALA_INTEROP_V3(InsertETSImportDeclarationAndParse, KNativePointer, KNativePointer, KNativePointer); KNativePointer impl_ETSParserGetImportPathManager(KNativePointer contextPtr) { diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 748275bf5..c68a445e5 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -615,7 +615,7 @@ export class Es2pandaNativeModule { throw new Error("Not implemented"); } - _InsertETSImportDeclarationAndParse(context: KNativePointer, importDeclaration: KNativePointer): void { + _InsertETSImportDeclarationAndParse(context: KNativePointer, program: KNativePointer, importDeclaration: KNativePointer): void { throw new Error("Not implemented"); } diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index 2ca2f213b..dc96b3865 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -21,6 +21,7 @@ import { isFunctionDeclaration, isMemberExpression } from "../factory/nodeTests" import { Es2pandaContextState, Es2pandaModifierFlags } from "../../generated/Es2pandaEnums" import type { AstNode } from "../peers/AstNode" import { ClassDefinition, ClassProperty, ETSImportDeclaration, isClassDefinition, isScriptFunction, type AnnotationUsage } from "../../generated" +import { Program } from "../peers/Program" export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { console.log("[TS WRAPPER] PROCEED TO STATE: ", getEnumName(Es2pandaContextState, state)); @@ -111,8 +112,8 @@ export function classDefinitionFlags(node: ClassDefinition): Es2pandaModifierFla } // TODO: Import statements should be inserted to the statements -export function importDeclarationInsert(node: ETSImportDeclaration): void { - global.es2panda._InsertETSImportDeclarationAndParse(global.context, node.peer) +export function importDeclarationInsert(node: ETSImportDeclaration, program: Program): void { + global.es2panda._InsertETSImportDeclarationAndParse(global.context, program.peer, node.peer) } export function hasModifierFlag(node: AstNode, flag: Es2pandaModifierFlags): boolean { -- Gitee From 66ac2c8c32297329c3ebbaad733a10c3e9671aa5 Mon Sep 17 00:00:00 2001 From: seaside_wu Date: Thu, 3 Apr 2025 21:39:59 +0800 Subject: [PATCH 005/123] fix compiler/package-lock.json Signed-off-by: seaside_wu Change-Id: I0ba3383c3027ca9fdc7dc5c353be3ef06dc441d9 --- compiler/package-lock.json | 98 +------------------------------------- 1 file changed, 2 insertions(+), 96 deletions(-) diff --git a/compiler/package-lock.json b/compiler/package-lock.json index 427d0b5dd..3aa764b4f 100644 --- a/compiler/package-lock.json +++ b/compiler/package-lock.json @@ -1538,44 +1538,6 @@ "picomatch": "^2.3.1" } }, - "@sinonjs/commons": { - "version": "3.0.1", - "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/commons/-/commons-3.0.1.tgz", - "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", - "requires": { - "type-detect": "4.0.8" - } - }, - "@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", - "requires": { - "@sinonjs/commons": "^3.0.0" - } - }, - "@sinonjs/samsam": { - "version": "8.0.2", - "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/samsam/-/samsam-8.0.2.tgz", - "integrity": "sha512-v46t/fwnhejRSFTGqbpn9u+LQ9xJDse10gNnPgAcxgdoCDMXj/G2asWAC/8Qs+BAZDicX+MNZouXT1A7c83kVw==", - "requires": { - "@sinonjs/commons": "^3.0.1", - "lodash.get": "^4.4.2", - "type-detect": "^4.1.0" - }, - "dependencies": { - "type-detect": { - "version": "4.1.0", - "resolved": "https://repo.huaweicloud.com/repository/npm/type-detect/-/type-detect-4.1.0.tgz", - "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==" - } - } - }, - "@sinonjs/text-encoding": { - "version": "0.7.3", - "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/text-encoding/-/text-encoding-0.7.3.tgz", - "integrity": "sha512-DE427ROAphMQzU4ENbliGYrBSYPXF+TtLg9S8vzeA+OF4ZKzoDdzfL8sxuMUGS/lgRhM6j1URSk9ghf7Xo1tyA==" - }, "@types/eslint": { "version": "8.40.2", "resolved": "https://repo.huaweicloud.com/repository/npm/@types/eslint/-/eslint-8.40.2.tgz", @@ -3245,11 +3207,6 @@ "graceful-fs": "^4.1.6" } }, - "just-extend": { - "version": "6.2.0", - "resolved": "https://repo.huaweicloud.com/repository/npm/just-extend/-/just-extend-6.2.0.tgz", - "integrity": "sha512-cYofQu2Xpom82S6qD778jBDpwvvy39s1l/hrYij2u9AMdQcGRpaBu6kY4mVhuno5kJVi1DAz4aiphA2WI1/OAw==" - }, "kind-of": { "version": "6.0.3", "resolved": "https://repo.huaweicloud.com/repository/npm/kind-of/-/kind-of-6.0.3.tgz", @@ -3289,11 +3246,6 @@ "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", "dev": true }, - "lodash.get": { - "version": "4.4.2", - "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.get/-/lodash.get-4.4.2.tgz", - "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==" - }, "lodash.merge": { "version": "4.6.2", "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -3571,28 +3523,6 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==" }, - "nise": { - "version": "5.1.9", - "resolved": "https://repo.huaweicloud.com/repository/npm/nise/-/nise-5.1.9.tgz", - "integrity": "sha512-qOnoujW4SV6e40dYxJOb3uvuoPHtmLzIk4TFo+j0jPJoC+5Z9xja5qH5JZobEPsa8+YYphMrOSwnrshEhG2qww==", - "requires": { - "@sinonjs/commons": "^3.0.0", - "@sinonjs/fake-timers": "^11.2.2", - "@sinonjs/text-encoding": "^0.7.2", - "just-extend": "^6.2.0", - "path-to-regexp": "^6.2.1" - }, - "dependencies": { - "@sinonjs/fake-timers": { - "version": "11.3.1", - "resolved": "https://repo.huaweicloud.com/repository/npm/@sinonjs/fake-timers/-/fake-timers-11.3.1.tgz", - "integrity": "sha512-EVJO7nW5M/F5Tur0Rf2z/QoMo+1Ia963RiMtapiQrEWvY0iBUvADo8Beegwjpnle5BHkyHuoxSTW3jF43H1XRA==", - "requires": { - "@sinonjs/commons": "^3.0.1" - } - } - } - }, "node-releases": { "version": "2.0.12", "resolved": "https://repo.huaweicloud.com/repository/npm/node-releases/-/node-releases-2.0.12.tgz", @@ -3701,11 +3631,6 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" }, - "path-to-regexp": { - "version": "6.3.0", - "resolved": "https://repo.huaweicloud.com/repository/npm/path-to-regexp/-/path-to-regexp-6.3.0.tgz", - "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==" - }, "path-type": { "version": "4.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/path-type/-/path-type-4.0.0.tgz", @@ -4005,26 +3930,6 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" }, - "sinon": { - "version": "15.2.0", - "resolved": "https://repo.huaweicloud.com/repository/npm/sinon/-/sinon-15.2.0.tgz", - "integrity": "sha512-nPS85arNqwBXaIsFCkolHjGIkFo+Oxu9vbgmBJizLAhqe6P2o3Qmj3KCUoRkfhHtvgDhZdWD3risLHAUJ8npjw==", - "requires": { - "@sinonjs/commons": "^3.0.0", - "@sinonjs/fake-timers": "^10.3.0", - "@sinonjs/samsam": "^8.0.0", - "diff": "^5.1.0", - "nise": "^5.1.4", - "supports-color": "^7.2.0" - }, - "dependencies": { - "diff": { - "version": "5.2.0", - "resolved": "https://repo.huaweicloud.com/repository/npm/diff/-/diff-5.2.0.tgz", - "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==" - } - } - }, "slash": { "version": "3.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/slash/-/slash-3.0.0.tgz", @@ -4191,7 +4096,8 @@ "type-detect": { "version": "4.0.8", "resolved": "https://repo.huaweicloud.com/repository/npm/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==" + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true }, "type-fest": { "version": "0.20.2", -- Gitee From f9c8fbe218c0e74db345599ed573629fb9e4f56b Mon Sep 17 00:00:00 2001 From: zenghang Date: Tue, 4 Feb 2025 16:31:51 +0800 Subject: [PATCH 006/123] Integrate declgen to ets2bundle Issue: IBNHVK Signed-off-by: zenghang Change-Id: I8911bde90e5f1d7f9737a3711f639a2ae7852eec --- BUILD.gn | 14 +++-- compiler/script/install_declgen.sh | 58 +++++++++++++++++++ compiler/src/ets_checker.ts | 34 ++++++++++- ..._tsc.py => install_arkguard_tsc_declgen.py | 3 +- 4 files changed, 102 insertions(+), 7 deletions(-) create mode 100755 compiler/script/install_declgen.sh rename install_arkguard_tsc.py => install_arkguard_tsc_declgen.py (96%) diff --git a/BUILD.gn b/BUILD.gn index 8bf020a7a..fb218f48d 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -44,7 +44,7 @@ action("build_ets_loader_library") { deps = [ ":components", ":form_components", - ":install_arkguard_tsc", + ":install_arkguard_tsc_declgen", ":server", ] if (sdk_build_public) { @@ -188,7 +188,7 @@ ets_loader_sources = [ ohos_copy("ets_loader") { deps = [ ":build_ets_loader_library", - ":install_arkguard_tsc", + ":install_arkguard_tsc_declgen", ] sources = ets_loader_sources deps += [ ":build_ets_sysResource" ] @@ -275,7 +275,7 @@ ohos_copy("ets_loader_declaration") { ohos_copy("ets_loader_ark") { deps = [ ":build_ets_loader_library", - ":install_arkguard_tsc", + ":install_arkguard_tsc_declgen", ] sources = ets_loader_sources deps += [ ":build_ets_sysResource" ] @@ -370,18 +370,22 @@ ohos_copy("ets_loader_ark_hap") { typescript_dir = get_label_info("//third_party/typescript:build_typescript", "target_out_dir") -action("install_arkguard_tsc") { +action("install_arkguard_tsc_declgen") { + static_core = "//arkcompiler/runtime_core/static_core" deps = [ + "${static_core}/plugins/ets/tools/declgen_ts2sts:build_declgen", "//arkcompiler/ets_frontend/arkguard:build_arkguard", "//third_party/typescript:build_typescript", ] - script = "install_arkguard_tsc.py" + script = "install_arkguard_tsc_declgen.py" args = [ rebase_path("${typescript_dir}/ohos-typescript-4.9.5-r4.tgz"), rebase_path( "${root_out_dir}/obj/arkcompiler/ets_frontend/arkguard/arkguard-1.1.3.tgz"), rebase_path("//developtools/ace_ets2bundle/compiler"), current_os, + rebase_path( + "${root_out_dir}/obj/arkcompiler/runtime_core/static_core/plugins/ets/tools/declgen_ts2sts/panda-declgen-1.0.0.tgz"), ] outputs = [ "${target_out_dir}/${target_name}.stamp" ] } diff --git a/compiler/script/install_declgen.sh b/compiler/script/install_declgen.sh new file mode 100755 index 000000000..ca35365e4 --- /dev/null +++ b/compiler/script/install_declgen.sh @@ -0,0 +1,58 @@ +#!/bin/bash +# 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. + +#!/bin/bash +set -e + +if [ ! -d "../compiler" ]; then + echo "Error: must run this script in ace_ets2bundle/compiler root directory" + exit 1 +fi + +oriDir=$(pwd) + +DECLGEN_ROOT_DIR="../../../arkcompiler/runtime_core/static_core/plugins/ets/tools/declgen_ts2sts" + +cd "$DECLGEN_ROOT_DIR" || { echo "Failed to change directory to $DECLGEN_ROOT_DIR"; exit 1; } + +npm install +npm run build + +# Generate the npm package using `npm pack` +if npm pack; then + tarball=$(ls *.tgz) # Get the generated tarball file name + if [ -f "$tarball" ]; then + # Move the tarball to the original directory + mv "$tarball" "$oriDir/" + + # Go back to the original directory and extract the tarball + cd "$oriDir" + tar -xvzf "$tarball" + + # Rename the extracted directory (assuming it is named after the package) + extracted_dir=$(tar -tf "$tarball" | head -n 1 | cut -f1 -d"/") # Get the extracted folder name + mv "$extracted_dir" "./node_modules/declgen" # Rename to 'declgen' + + # Optionally, remove the tarball after extraction + rm "$tarball" + + echo "Build successfully packed, extracted, and renamed to 'declgen' in $oriDir" + else + echo "Error: No tarball found, cannot proceed" + exit 1 + fi +else + echo "Error: npm pack failed" + exit 1 +fi diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index 51942e5a0..0320a495c 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -103,6 +103,10 @@ import { } from './hvigor_error_code/hvigor_error_info'; import { ErrorCodeModule } from './hvigor_error_code/const/error_code_module'; import { buildErrorInfoFromDiagnostic } from './hvigor_error_code/utils'; +import { + RunnerParms, + generateInteropDecls +} from '../node_modules/declgen/build/src/generateInteropDecls' export interface LanguageServiceCache { service?: ts.LanguageService; @@ -556,7 +560,9 @@ export function serviceChecker(rootFileNames: string[], newLogger: Object = null processBuildHap(cacheFile, rootFileNames, compilationTime, rollupShareObject); MemoryMonitor.stopRecordStage(processBuildHaprrecordInfo); } - + if (rollupShareObject?.projectConfig.mixCompile) { + generateDeclarationFileForSTS(rootFileNames, allResolvedModules); + } if (globalProgram.program && (process.env.watchMode !== 'true' && !projectConfig.isPreview && !projectConfig.hotReload && !projectConfig.coldReload)) { @@ -1812,3 +1818,29 @@ export function resetEtsCheck(): void { targetESVersionChanged = false; fileToIgnoreDiagnostics = undefined; } + +export function generateDeclarationFileForSTS(rootFileNames: string[], allResolvedModules: Set) { + if (!(projectConfig.compileHar || projectConfig.compileShared)) { + return; + } + const unixRootFileNames = rootFileNames.map(path => { + return toUnixPath(path); + }); + + const uniqueFiles = Array.from(new Set([ + ...unixRootFileNames, + ...allResolvedModules + ])); + + const config: RunnerParms = { + inputDirs: [], + inputFiles: uniqueFiles, + outDir: path.resolve(projectConfig.aceModuleBuild, '../etsFortgz/ets'), + rootDir: projectConfig.projectRootPath, + customResolveModuleNames: resolveModuleNames + }; + if (fs.existsSync(config.outDir)) { + fs.rmSync(config.outDir, { recursive: true, force: true }); + } + generateInteropDecls(config); +} \ No newline at end of file diff --git a/install_arkguard_tsc.py b/install_arkguard_tsc_declgen.py similarity index 96% rename from install_arkguard_tsc.py rename to install_arkguard_tsc_declgen.py index 61284e51e..5fb5d0c1b 100755 --- a/install_arkguard_tsc.py +++ b/install_arkguard_tsc_declgen.py @@ -54,10 +54,11 @@ def run(args): arkguard_path = args[1] source_path = args[2] current_os = args[3] + declgen_path = args[4] node_modules_path = os.path.join(source_path, "node_modules") extract(tsc_path, node_modules_path, 'typescript', current_os) extract(arkguard_path, node_modules_path, 'arkguard', current_os) - + extract(declgen_path, node_modules_path, 'declgen', current_os) if __name__ == "__main__": run(sys.argv[1:]) \ No newline at end of file -- Gitee From e4233fc4f1cb728b365dc943f0fb0bc28566b948 Mon Sep 17 00:00:00 2001 From: zenghang Date: Fri, 28 Feb 2025 10:48:58 +0800 Subject: [PATCH 007/123] Declgen supports setting CompilerOptions Issue: IBPM27 Signed-off-by: zenghang Change-Id: I78c03ca45918beac407c30de2f1cc63f22ba61bb --- compiler/src/ets_checker.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index 0320a495c..e68003fda 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -1827,17 +1827,19 @@ export function generateDeclarationFileForSTS(rootFileNames: string[], allResolv return toUnixPath(path); }); + const regex = new RegExp(projectConfig.packageDir); const uniqueFiles = Array.from(new Set([ ...unixRootFileNames, ...allResolvedModules - ])); + ])).filter(file => !regex.test(file)); const config: RunnerParms = { inputDirs: [], inputFiles: uniqueFiles, outDir: path.resolve(projectConfig.aceModuleBuild, '../etsFortgz/ets'), rootDir: projectConfig.projectRootPath, - customResolveModuleNames: resolveModuleNames + customResolveModuleNames: resolveModuleNames, + customCompilerOptions: compilerOptions }; if (fs.existsSync(config.outDir)) { fs.rmSync(config.outDir, { recursive: true, force: true }); -- Gitee From 573e2d15492b49219a7e0181948948393551bc50 Mon Sep 17 00:00:00 2001 From: zenghang Date: Wed, 5 Feb 2025 10:26:16 +0800 Subject: [PATCH 008/123] Extract es2abc from rollup toolchain Issue: IBK3CK Signed-off-by: zenghang Change-Id: I155ffea638e5767f727736f4e268683f59dc5d57 --- .../ark_compiler/common/ark_define.ts | 3 + .../ark_compiler/module/module_mode.ts | 11 +- .../ark_compiler/run_es2abc_standalone.ts | 175 ++++++++++++++++++ .../run_es2abc_standalone.test.ts | 124 +++++++++++++ .../expect/compileContextInfo.json | 14 ++ .../mergeCacheData/expect/sourceMaps.map | 100 ++++++++++ .../originCacheDir1/compileContextInfo.json | 9 + .../originCacheDir1/filesInfo.txt | 3 + .../originCacheDir1/npmEntries.txt | 7 + .../originCacheDir1/sourceMaps.map | 56 ++++++ .../originCacheDir2/compileContextInfo.json | 11 ++ .../originCacheDir2/filesInfo.txt | 3 + .../originCacheDir2/npmEntries.txt | 7 + .../originCacheDir2/sourceMaps.json | 46 +++++ 14 files changed, 568 insertions(+), 1 deletion(-) create mode 100644 compiler/src/fast_build/ark_compiler/run_es2abc_standalone.ts create mode 100644 compiler/test/ark_compiler_ut/run_es2abc_standalone.test.ts create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/expect/compileContextInfo.json create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/expect/sourceMaps.map create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/compileContextInfo.json create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/filesInfo.txt create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/npmEntries.txt create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/sourceMaps.map create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/compileContextInfo.json create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/filesInfo.txt create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/npmEntries.txt create mode 100644 compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/sourceMaps.json diff --git a/compiler/src/fast_build/ark_compiler/common/ark_define.ts b/compiler/src/fast_build/ark_compiler/common/ark_define.ts index ed74f0b17..8f995e375 100644 --- a/compiler/src/fast_build/ark_compiler/common/ark_define.ts +++ b/compiler/src/fast_build/ark_compiler/common/ark_define.ts @@ -120,3 +120,6 @@ export const USE_SHARED_COMMENT: string = '// "use shared"'; export const SEPARATOR_BITWISE_AND: string = '&'; export const SEPARATOR_AT: string = '@'; export const SEPARATOR_SLASH: string = '/'; + +export const GEN_ABC_CMD: string = "genAbcCmd"; +export const GEN_ABC_CMD_FILE_PATH: string = "genAbcCmd.json"; diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts index c14c3c04e..e0753f1f4 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_mode.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -53,7 +53,8 @@ import { ES2ABC, ETS, TS, - JS + JS, + GEN_ABC_CMD } from '../common/ark_define'; import { needAotCompiler, @@ -166,6 +167,7 @@ export class ModuleMode extends CommonMode { compileContextInfoPath: string; abcPaths: string[] = []; byteCodeHar: boolean; + rollupCache: Object; constructor(rollupObject: Object) { super(rollupObject); @@ -198,6 +200,7 @@ export class ModuleMode extends CommonMode { if (this.useNormalizedOHMUrl) { this.compileContextInfoPath = this.generateCompileContextInfo(rollupObject); } + this.rollupCache = rollupObject.cache; } private generateCompileContextInfo(rollupObject: Object): string { @@ -661,6 +664,12 @@ export class ModuleMode extends CommonMode { let errMsg: string = ''; const eventGenDescriptionsForMergedEs2abc = createAndStartEvent(parentEvent, 'generate descriptions for merged es2abc'); stopEvent(eventGenDescriptionsForMergedEs2abc); + + if (this.projectConfig.invokeEs2abcByHvigor) { + this.rollupCache.set(GEN_ABC_CMD, this.cmdArgs); + return; + } + const genAbcCmd: string = this.cmdArgs.join(' '); try { let eventGenAbc: Object; diff --git a/compiler/src/fast_build/ark_compiler/run_es2abc_standalone.ts b/compiler/src/fast_build/ark_compiler/run_es2abc_standalone.ts new file mode 100644 index 000000000..8ec011349 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/run_es2abc_standalone.ts @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import childProcess from 'child_process'; +import { + COMPILE_CONTEXT_INFO_JSON, + FILESINFO_TXT, + GEN_ABC_CMD_FILE_PATH, + MODULES_ABC, + MODULES_CACHE, + NPMENTRIES_TXT, + SOURCEMAPS, + SOURCEMAPS_JSON +} from './common/ark_define'; + +/** + * A script is called by hvigor in a mixed compilation scenario which 1.0 module is not main module,np + * such as module1.2-> module1.0-> module1.2 -> module1.0, compile all 1.0 modules + * and has nothing to do with the ace_ets2bundle process. + */ + +/** + * + * @param cachePathList projectConfig.cachePath of the modules to be merged + * @param targetCachePath The merged target cache directory + * @param aceModuleBuild The aceModuleBuild path of the target module is used to write the abc file to the disk + * @returns erro.toString() + */ +export function run(cachePathList: string[], targetCachePath: string, aceModuleBuild: string): void { + if (!cachePathList || cachePathList.length == 0) { + return + } + mergeCacheData(cachePathList, targetCachePath, FILESINFO_TXT); + mergeCacheData(cachePathList, targetCachePath, MODULES_CACHE); + mergeCacheData(cachePathList, targetCachePath, NPMENTRIES_TXT); + mergeCompileContextInfo(cachePathList, targetCachePath); + mergeSourceMap(cachePathList, targetCachePath); + const cmd: string[] = JSON.parse(fs.readFileSync(path.join(cachePathList[0], GEN_ABC_CMD_FILE_PATH), 'utf-8')); + updateCmd(cmd, targetCachePath, aceModuleBuild); + execCmd(cmd); +} + +export function mergeCacheData(cachePathList: string[], targetCachePath: string, fileName: string): void { + const dataSet: Set = new Set(); + cachePathList.forEach(cachePath => { + const inputFilePath: string = path.join(cachePath, fileName); + if (fs.existsSync(inputFilePath)) { + const fileData: string = fs.readFileSync(inputFilePath).toString(); + fileData.split('\n').forEach(data => { + //eat blank line + if (data) { + dataSet.add(data); + } + }); + } + }); + + const outputFilePath: string = path.join(targetCachePath, fileName); + fs.writeFileSync(outputFilePath, Array.from(dataSet).join('\n')); +} + +function execCmd(cmd: string[]): string { + try { + const result = childProcess.execSync(cmd.join(' '), { + windowsHide: true, + encoding: 'utf-8' + }); + return result; + } catch (error) { + return error.toString(); + } +} + +export function updateCmd(cmd: string[], targetCachePath: string, aceModuleBuild: string) { + for (let i = 0; i < cmd.length; i++) { + if (cmd[i].indexOf("filesInfo.txt") != -1) { + const filesInfoPath: string = path.join(targetCachePath, FILESINFO_TXT); + cmd[i] = `"@${filesInfoPath}"`; + continue; + } + if (cmd[i] === ('--output')) { + const moduleAbcPath = path.join(aceModuleBuild, MODULES_ABC); + cmd[++i] = `"${moduleAbcPath}"`; + continue; + } + if (cmd[i] === ('--cache-file')) { + const cacheFilePath = path.join(targetCachePath, MODULES_CACHE); + cmd[++i] = `"@${cacheFilePath}"`; + continue; + } + if (cmd[i] === ('--npm-module-entry-list')) { + const npmEntriesInfoPath = path.join(targetCachePath, NPMENTRIES_TXT); + cmd[++i] = `"@${npmEntriesInfoPath}"`; + continue; + } + if (cmd[i] === (`--compile-context-info`)) { + const compileContextInfoPath = path.join(targetCachePath, COMPILE_CONTEXT_INFO_JSON); + cmd[++i] = `"${compileContextInfoPath}"`; + continue; + } + } +} + +function deepMerge(target: Object, source: Object): Object { + for (const key of Object.keys(source)) { + if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) { + target[key] = deepMerge(target[key] || {}, source[key]); + } else { + target[key] = source[key]; + } + } + return target; +} + +export function mergeCompileContextInfo(cachePathList: string[], targetCachePath: string) { + const mergedData = { + hspPkgNames: [], + compileEntries: [], + updateVersionInfo: {} + }; + + cachePathList.forEach(cachePath => { + const compileContextPath = path.join(cachePath, COMPILE_CONTEXT_INFO_JSON); + + if (fs.existsSync(compileContextPath)) { + const data = JSON.parse(fs.readFileSync(compileContextPath, 'utf-8')); + + mergedData.hspPkgNames = [...mergedData.hspPkgNames, ...data.hspPkgNames]; + mergedData.compileEntries = [...mergedData.compileEntries, ...data.compileEntries]; + + mergedData.updateVersionInfo = deepMerge(mergedData.updateVersionInfo, data.updateVersionInfo); + } + }); + + const targetPath = path.join(targetCachePath, COMPILE_CONTEXT_INFO_JSON); + fs.writeFileSync(targetPath, JSON.stringify(mergedData, null, 2)); +} + +export function mergeSourceMap(cachePathList: string[], targetCachePath: string) { + const mergedMap: Record = {}; + cachePathList.forEach((item) => { + /** + * Prevent sourcemap.json file from not being generated. + * Some bug scenarios only have one file written to disk. + */ + const possiblePaths = [ + path.join(item, SOURCEMAPS), + path.join(item, SOURCEMAPS_JSON), + ]; + + const sourceMapPath = possiblePaths.find(fs.existsSync); + if (!sourceMapPath) { + return; + } + const sourceMap = JSON.parse(fs.readFileSync(sourceMapPath, 'utf-8')); + Object.assign(mergedMap, sourceMap); + }); + + const outputPath = path.join(targetCachePath, SOURCEMAPS); + fs.writeFileSync(outputPath, JSON.stringify(mergedMap, null, 2), 'utf-8'); +} diff --git a/compiler/test/ark_compiler_ut/run_es2abc_standalone.test.ts b/compiler/test/ark_compiler_ut/run_es2abc_standalone.test.ts new file mode 100644 index 000000000..108aba948 --- /dev/null +++ b/compiler/test/ark_compiler_ut/run_es2abc_standalone.test.ts @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use rollupObject file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import mocha from 'mocha'; +import path from 'path'; +import fs from 'fs'; +import { + expect +} from 'chai'; +import { + COMPILE_CONTEXT_INFO_JSON, + FILESINFO_TXT, + MODULES_CACHE, + NPMENTRIES_TXT, + RELEASE, + SOURCEMAPS, +} from '../../lib/fast_build/ark_compiler/common/ark_define'; +import { + mergeCacheData, + mergeCompileContextInfo, + mergeSourceMap, +} from '../../lib/fast_build/ark_compiler/run_es2abc_standalone'; +import RollUpPluginMock from './mock/rollup_mock/rollup_plugin_mock'; + +let MERGE_CACHE_PATH; +let targetCachePath; + +mocha.describe('test run_es2abc_standalone file api', function () { + mocha.before(function () { + this.rollup = new RollUpPluginMock(); + this.rollup.build(); + MERGE_CACHE_PATH=path.join(this.rollup.share.projectConfig.projectRootPath, '/mergeCacheData') + targetCachePath=path.join(MERGE_CACHE_PATH,'/targetCacheDir') + if (!fs.existsSync(targetCachePath)) { + fs.mkdirSync(targetCachePath, { recursive: true }); + } + }); + + mocha.after(function () { + if (fs.existsSync(targetCachePath)) { + fs.rmSync(targetCachePath, { recursive: true, force: true }); + } + }) + + mocha.it('1-1: test mergeCacheData', function () { + + const cachePathList = [ + path.resolve(MERGE_CACHE_PATH, './originCacheDir1'), + path.resolve(MERGE_CACHE_PATH, './originCacheDir2'), + ]; + const fileNameList = [ + FILESINFO_TXT, + NPMENTRIES_TXT + ] + fileNameList.forEach(fileName => { + mergeCacheData(cachePathList, targetCachePath, fileName); + }) + + fileNameList.forEach(fileName => { + + const targetFilePath = path.resolve(targetCachePath, fileName); + const targetLineCount = countLines(targetFilePath); + + let sumOriginLineCount = 0; + cachePathList.forEach(cacheDir => { + const originFilePath = path.resolve(cacheDir, fileName); + if (fs.existsSync(originFilePath)) { + sumOriginLineCount += countLines(originFilePath); + } + }); + expect(targetLineCount).to.equal(sumOriginLineCount); + }); + }); + + mocha.it('1-2: test mergeSourceMap', function () { + const cachePathList = [ + path.resolve(MERGE_CACHE_PATH, './originCacheDir1'), + path.resolve(MERGE_CACHE_PATH, './originCacheDir2'), + ]; + + mergeSourceMap(cachePathList, targetCachePath) + + const mergedSourceMap = JSON.parse(fs.readFileSync(path.resolve(targetCachePath, SOURCEMAPS), 'utf-8')); + const expectSourceMap = JSON.parse(fs.readFileSync(path.join(MERGE_CACHE_PATH, './expect', SOURCEMAPS), 'utf-8')); + + expect(mergedSourceMap).to.deep.equal(expectSourceMap); + }); + + mocha.it('1-3: test mergeCompileContextInfo', function () { + const cachePathList = [ + path.resolve(MERGE_CACHE_PATH, './originCacheDir1'), + path.resolve(MERGE_CACHE_PATH, './originCacheDir2'), + ]; + + mergeCompileContextInfo(cachePathList, targetCachePath); + + const mergedCompileContext = JSON.parse( + fs.readFileSync(path.resolve(targetCachePath, COMPILE_CONTEXT_INFO_JSON), 'utf-8') + ); + + const expectCompileContext = JSON.parse( + fs.readFileSync(path.join(MERGE_CACHE_PATH, './expect',COMPILE_CONTEXT_INFO_JSON), 'utf-8') + ); + + expect(mergedCompileContext).to.deep.equal(expectCompileContext); + }); +}); + +function countLines(filePath) { + const content = fs.readFileSync(filePath, 'utf-8'); + return content.split(/\r?\n/).filter(line => line !== '').length; +} \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/expect/compileContextInfo.json b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/expect/compileContextInfo.json new file mode 100644 index 000000000..07f011f3c --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/expect/compileContextInfo.json @@ -0,0 +1,14 @@ +{ + "hspPkgNames": [], + "compileEntries": [ + "&entry/src/main/ets/entryability/EntryAbility&", + "&entry/src/main/ets/entrybackupability/EntryBackupAbility&", + "&entry/src/main/ets/pages/Index&", + "&har/src/main/ets/components/a&1.0.0", + "&har/src/main/ets/components/aaa&1.0.0", + "&har/src/main/ets/components/MainPage&1.0.0", + "&har/build/default/generated/profile/default/ModuleInfo&1.0.0", + "&har/Index&1.0.0" + ], + "updateVersionInfo": {} +} \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/expect/sourceMaps.map b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/expect/sourceMaps.map new file mode 100644 index 000000000..f8a55a78b --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/expect/sourceMaps.map @@ -0,0 +1,100 @@ +{ + "har|har|1.0.0|build/default/generated/profile/default/ModuleInfo.js": { + "version": 3, + "file": "ModuleInfo.ts", + "sources": [ + "har/build/default/generated/profile/default/ModuleInfo.ts" + ], + "names": [], + "mappings": "AACA,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACb,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAC,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAe,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAwB,EAAE,CAAA,CAAA;AACjE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAC,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAe,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAwB,EAAE,CAAA,CAAA;", + "entry-package-info": "har|1.0.0" + }, + "har|har|1.0.0|Index.ts": { + "version": 3, + "file": "Index.ets", + "sourceRoot": "", + "sources": [ + "har/Index.ets" + ], + "names": [], + "mappings": "OAAO,EAAE,QAAQ,EAAC,MAAM,EAAE;OACnB,EAAC,CAAC,EAAC", + "entry-package-info": "har|1.0.0" + }, + "har|har|1.0.0|src/main/ets/components/a.ts": { + "version": 3, + "file": "a.ts", + "sourceRoot": "", + "sources": [ + "har/src/main/ets/components/a.ts" + ], + "names": [], + "mappings": "AAEA,MAAM,CAAC,MAAM,IAAI,EAAC,MAAM,GAAC,OAAO,CAAA;AAGhC,MAAM,QAAQ,CAAC,CAAA;IACb,MAAM,CAAC,MAAM,EAAE,GAAC,KAAK,CAAC;IACtB,MAAM,CAAC,MAAM,EAAE,EAAC,MAAM,GAAC,CAAC,CAAC;CAC1B;AAED,MAAM,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC;AACxB,MAAM,CAAC,MAAM,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC5B,MAAM,CAAC,IAAI,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC;AAG9B,SAAS,EAAE,CAAC,CAAC,EAAC,CAAC,EAAC,CAAC,IAAE,CAAC;AACpB,SAAS,EAAE,CAAC,CAAC,EAAC,CAAC,GAAC,CAAC,EAAC,GAAG,CAAC;AAEtB,CAAC;AACD,EAAE,CAAC,CAAC,CAAC,CAAA;AACL,EAAE,CAAC,CAAC,EAAC,CAAC,CAAC,CAAA;AACP,MAAM,SAAS;IACb,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB;AAGD,MAAM,UAAU;IACd,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,MAAM,CAAC;QACnC,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAC7B,OAAO;YACL,IAAI,IAAI,cAAc,CAAC,MAAM,CAAC;gBAC5B,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE;oBACvB,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;iBAC9C;qBAAM;oBACL,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;iBACzC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF;AAED,MAAM,QAAQ,GAAG,IAAI,UAAU,EAAE,CAAC;AAClC,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,mBAAmB;CACnD;AAED,UAAU,GAAG,CAAC,CAAC;IACb,KAAK,EAAE,CAAC,CAAC;IACT,QAAQ,IAAI,CAAC,CAAC;CACf;AAED,MAAM,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG;IAC7B,KAAK,EAAE,EAAE;IACT,QAAQ;QACN,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;CACF,CAAC;AAEF,MAAM,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG;IAC7B,KAAK,EAAE,oBAAoB;IAC3B,QAAQ;QACN,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;CACF,CAAC;AACF,MAAM,MAAM,IAAI,GAAG,MAAM,CAAC;AAE1B,MAAM,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,CAAC,iBAAiB;AAE7C,UAAU,CAAC,CAAA;IACT,MAAM,WAAW,CAAC,CAAA;QAChB,MAAM,UAAU,GAAG,IAAG,IAAI,GAAC,CAAC;KAC7B;IACD,MAAM,CAAC,MAAM,MAAM,EAAC,MAAM,GAAC,CAAC,CAAC;IAC7B,MAAM,SAAS;QACb,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;KACvB;IACD,UAAU,GAAG,CAAC,CAAC;QACb,KAAK,EAAE,CAAC,CAAC;QACT,QAAQ,IAAI,CAAC,CAAC;KACf;IACD,KAAK,MAAM,SAAS;QAClB,EAAE,IAAA;QACF,IAAI,IAAA;QACJ,IAAI,IAAA;QACJ,KAAK,IAAA;KACN;CAEF;AACD,UAAU;AACV,KAAK,EAAE,GAAG,MAAM,GAAG,MAAM,CAAC;AAE1B,UAAU;AACV,KAAK,UAAU,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;AAEnD,MAAM,GAAG,EAAE,UAAU,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC;AAExC,UAAU;AACV,KAAK,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAC/B,KAAK,GAAG,GAAG,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtC,MAAM,GAAG,EAAE,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AAEpD,UAAU;AACV,KAAK,WAAW,GAAG;IAAC,MAAM;IAAE,MAAM;CAAC,CAAC;AAEpC,MAAM,KAAK,EAAE,WAAW,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAEpC,UAAU;AACV,KAAK,OAAO,GAAG;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,OAAO,EAAE,OAAO,GAAG;IACvB,IAAI,EAAE,QAAQ;IACd,KAAK,EAAE,IAAI;CACZ,CAAC;AACF,SAAS;AACT,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC;AAE9D,MAAM;AACN,6CAA6C;AAC7C,MAAM,UAAU,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM;IAC5C,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC;AAED,MAAM,WAAW,CAAC,CAAA;IAChB,MAAM,WAAW,CAAC,CAAA;QAChB,MAAM,UAAU,CAAC,KAAG,CAAC;QACrB,SAAS,CAAC,KAAG,CAAC;KACf;IACD,UAAU,EAAE,CAAA,GAAE;CACf;AAED,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;AAEP,UAAU,EAAE,CAAC;IACX,MAAM,KAAK,GAAG,CAAC,CAAC;CACjB;AAED,KAAK,MAAM;IACT,GAAG,IAAA;IACH,GAAG,IAAA;CACJ;AAED,OAAO,EAAC,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,IAAI,OAAO,EAAC,CAAC;AAGrD,OAAO,UAAU,IAAI,CAAC,EAAE,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EACtD,EAAE,EAAE,EAAE,GACL,GAAG,CAAC;AAGP,SAAS,GAAG,CAAC,GAAG,IAAI;AAEpB,CAAC;AAGD,MAAM,QAAQ,CAAC,CAAC;IACd,MAAM,UAAU,CAAC,KAAI,CAAC;IACtB,SAAU,CAAC,KAAG,CAAC;CAChB;AAED,OAAO,CAAC,MAAM,EAAE,EAAE,KAAK,GAAG,SAAS,GAAG,IAAI,CAAC;AAG3C,MAAM,CAAC,IAAI,KAAK,EAAC;IAAC,IAAI,EAAC,MAAM,CAAC;IAAA,GAAG,EAAC,MAAM,CAAA;CAAC,GAAC;IACxC,IAAI,EAAC,QAAQ;IACb,GAAG,EAAC,EAAE;CACP,CAAA;AAGD,MAAM,MAAM,UAAU,GAAG;IACvB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB,CAAA", + "entry-package-info": "har|1.0.0" + }, + "har|har|1.0.0|src/main/ets/components/aaa.ts": { + "version": 3, + "file": "aaa.ts", + "sourceRoot": "", + "sources": [ + "har/src/main/ets/components/aaa.ts" + ], + "names": [], + "mappings": "", + "entry-package-info": "har|1.0.0" + }, + "har|har|1.0.0|src/main/ets/components/MainPage.ts": { + "version": 3, + "file": "MainPage.ets", + "sourceRoot": "", + "sources": [ + "har/src/main/ets/components/MainPage.ets" + ], + "names": [], + "mappings": ";;;;IAIS,OAAO,GAAE,MAAM;;OAJjB,EAAE,IAAI,EAAE;AAGf,MAAM,OAAQ,QAAQ;IADtB;;;;;sDAE2B,IAAI;;;KAJJ;;;;;;;;;;;;;;;;IAIzB,4CAAgB,MAAM,EAAQ;QAAvB,OAAO;;;QAAP,OAAO,WAAE,MAAM;;;IAEtB;;YACE,GAAG;YAAH,GAAG,CAQF,MAAM,CAAC,MAAM;;;YAPZ,MAAM;YAAN,MAAM,CAKL,KAAK,CAAC,MAAM;;;YAJX,IAAI,QAAC,IAAI,CAAC,OAAO;YAAjB,IAAI,CACD,QAAQ,CAAC,EAAE;YADd,IAAI,CAED,UAAU,CAAC,UAAU,CAAC,IAAI;;QAF7B,IAAI;QADN,MAAM;QADR,GAAG;KASJ;;;;;AAIH,MAAM,CAAC,MAAM,MAAM,EAAC,MAAM,GAAC,YAAY,CAAC", + "entry-package-info": "har|1.0.0" + }, + "entry|entry|1.0.0|src/main/ets/entryability/EntryAbility.ts": { + "version": 3, + "file": "EntryAbility.ets", + "sources": [ + "entry/src/main/ets/entryability/EntryAbility.ets" + ], + "names": [], + "mappings": "YAAS,eAAe,MAAA,mCAAA,CAAA;OAAE,qBAAqB,MAAA,yCAAA,CAAA;OAAE,SAAS,MAAA,6BAAA,CAAA;YAAE,IAAI,MAAA,wBAAA,CAAA;OACvD,KAAK,MAAA,aAAA,CAAA;YACL,MAAM,MAAA,cAAA,CAAA;AAEf,MAAM,CAAC,OAAO,iBAA4B,SAAS;IACjD,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,eAAe,CAAC,WAAW,GAAG,IAAI;QAClE,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE,CAAC,YAAY,CAAC,qBAAqB,CAAC,SAAS,CAAC,kBAAkB,CAAC,CAAC;QACtG,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,kBAAkB,CAAC,CAAC;IAClE,CAAC;IAED,SAAS,IAAI,IAAI;QACf,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,mBAAmB,CAAC,CAAC;IACnE,CAAC;IAED,mBAAmB,CAAC,WAAW,EAAE,MAAM,CAAC,WAAW,GAAG,IAAI;QAExD,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,6BAA6B,CAAC,CAAC;QAE3E,WAAW,CAAC,WAAW,CAAC,aAAa,EAAE,CAAC,GAAG,EAAE,EAAE;YAC7C,IAAI,GAAG,CAAC,IAAI,EAAE;gBACZ,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,+CAA+C,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;gBAC3G,OAAO;aACR;YACD,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,mCAAmC,CAAC,CAAC;QACrE,CAAC,CAAC,CAAC;IACL,CAAC;IAED,oBAAoB,IAAI,IAAI;QAE1B,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,8BAA8B,CAAC,CAAC;IAC9E,CAAC;IAED,YAAY,IAAI,IAAI;QAElB,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,sBAAsB,CAAC,CAAC;IACtE,CAAC;IAED,YAAY,IAAI,IAAI;QAElB,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,sBAAsB,CAAC,CAAC;IACtE,CAAC;CACF", + "sourceRoot": "", + "entry-package-info": "entry|1.0.0" + }, + "entry|entry|1.0.0|src/main/ets/entrybackupability/EntryBackupAbility.ts": { + "version": 3, + "file": "EntryBackupAbility.ets", + "sources": [ + "entry/src/main/ets/entrybackupability/EntryBackupAbility.ets" + ], + "names": [], + "mappings": "OAAS,KAAK,MAAA,aAAA,CAAA;OACL,sBAAsB,MAAA,0CAAA,CAAA;AAAE,OAAA,KAAA,EAAA,iBAAA,aAAa,EAAA,MAAA,0CAAA,CAAA;AAE9C,MAAM,CAAC,OAAO,iBAAkC,sBAAsB;IACpE,KAAK,CAAC,QAAQ;QACZ,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;IAC/C,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,aAAa,EAAE,aAAa;QAC1C,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,yBAAyB,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC;IAC1F,CAAC;CACF", + "sourceRoot": "", + "entry-package-info": "entry|1.0.0" + }, + "entry|entry|1.0.0|src/main/ets/pages/Index.ts": { + "version": 3, + "file": "Index.ets", + "sources": [ + "entry/src/main/ets/pages/Index.ets" + ], + "names": [], + "mappings": ";;;;IAWS,OAAO,GAAE,MAAM,CAAA;;OAXjB,KAAK,EAAE,GAAG,EAAE,oDAAA;AAEnB,MAAM,aAAiB;IACrB,MAAM,CAAC,MAAM,IAAO,MAAM,GAAC,QAAQ,CAAA;IACnC,MAAM,WAAS,MAAM,CAAA;CACtB;AACD,IAAI,KAAK,EAAC,IAAS,GAAC,IAAa,CAAA;OAIrB,SAAA,MAAA;IAFZ,YAAA,MAAA,EAAA,MAAA,EAAA,EAAA,EAAA,KAAA,CAAA,CAAA,EAAA,KAAA,SAAA,EAAA,SAAA;;;;;sDAG2B,GAAG,EAAA,IAAA,EAAA,SAAA,CAAA,CAAA;;;IALG,CAAA;;;;;;;;;;;;;;;;IAK/B,OAAA,CAAA,SAAA,EAAA,wBAAA,CAAgB,MAAM,CAAO,CAAA;QAAtB,OAAO;;;IAAP,IAAA,OAAO,WAAE,MAAM;;;IAEtB,aAAA;;YACE,iBAAiB,CAAA,MAAA,EAAA,CAAA;YAAjB,iBAAiB,CAUhB,MAAM,CAAC,MAAM,CAAA,CAAA;YAVd,iBAAiB,CAWhB,KAAK,CAAC,MAAM,CAAA,CAAA;;;YAVX,IAAI,CAAA,MAAA,CAAC,IAAI,CAAC,OAAO,CAAA,CAAA;YAAjB,IAAI,CACD,EAAE,CAAC,YAAY,CAAA,CAAA;YADlB,IAAI,CAED,QAAQ,CAAC,EAAE,CAAA,CAAA;YAFd,IAAI,CAGD,UAAU,CAAC,UAAU,CAAC,IAAI,CAAA,CAAA;YAH7B,IAAI,CAID,UAAU,CAAC;gBACV,MAAM,EAAE,EAAE,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,aAAa,CAAC,MAAM,EAAE;gBAChE,MAAM,EAAE,EAAE,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,eAAe,CAAC,MAAM,EAAE;aACnE,CAAA,CAAA;;QAPH,IAAI,CAAA,GAAA,EAAA,CAAA;QADN,iBAAiB,CAAA,GAAA,EAAA,CAAA;IAYlB,CAAA;;;;;;;;", + "sourceRoot": "", + "entry-package-info": "entry|1.0.0" + }, + "entry|entry|1.0.0|src/main/ets/pages/a.ts": { + "version": 3, + "file": "test.ts", + "sources": [ + "entry/src/main/ets/pages/test.ts" + ], + "names": [], + "mappings": "AAAA,MAAM,CAAE,MAAM,GAAG,EAAC,MAAM,GAAC,QAAQ,CAAA;AAEjC,QAAQ;IACN,QAAQ,MAAO;CAChB;AACD,UAAU,CAAC,CAAA;CAEV", + "sourceRoot": "", + "entry-package-info": "entry|1.0.0" + } +} \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/compileContextInfo.json b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/compileContextInfo.json new file mode 100644 index 000000000..1e66f2546 --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/compileContextInfo.json @@ -0,0 +1,9 @@ +{ + "hspPkgNames": [], + "compileEntries": [ + "&entry/src/main/ets/entryability/EntryAbility&", + "&entry/src/main/ets/entrybackupability/EntryBackupAbility&", + "&entry/src/main/ets/pages/Index&" + ], + "updateVersionInfo": {} +} \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/filesInfo.txt b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/filesInfo.txt new file mode 100644 index 000000000..238c11ab4 --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/filesInfo.txt @@ -0,0 +1,3 @@ +har22/build/default/cache/default/default@HarCompileArkTS/esmodule/debug/har22/Index.ts;&har22/Index&1.0.0;esm;har22|har22|1.0.0|Index.ts;har22;false +har22/build/default/cache/default/default@HarCompileArkTS/esmodule/debug/har22/src/main/ets/components/MainPage.ts;&har22/src/main/ets/components/MainPage&1.0.0;esm;har22|har22|1.0.0|src/main/ets/components/MainPage.ts;har22;false +har22/build/default/cache/default/default@HarCompileArkTS/esmodule/debug/har22/build/default/generated/profile/default/ModuleInfo.js;&har22/build/default/generated/profile/default/ModuleInfo&1.0.0;esm;har22|har22|1.0.0|build/default/generated/profile/default/ModuleInfo.js;har22;false diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/npmEntries.txt b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/npmEntries.txt new file mode 100644 index 000000000..40520cb91 --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/npmEntries.txt @@ -0,0 +1,7 @@ +@system.app:@native.system.app1 +@ohos.app:@native.ohos.app1 +@system.router:@native.system.router1 +@system.curves:@native.system.curves1 +@ohos.curves:@native.ohos.curves1 +@system.matrix4:@native.system.matrix41 +@ohos.matrix4:@native.ohos.matrix41 diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/sourceMaps.map b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/sourceMaps.map new file mode 100644 index 000000000..c54517a7f --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir1/sourceMaps.map @@ -0,0 +1,56 @@ +{ + "har|har|1.0.0|build/default/generated/profile/default/ModuleInfo.js": { + "version": 3, + "file": "ModuleInfo.ts", + "sources": [ + "har/build/default/generated/profile/default/ModuleInfo.ts" + ], + "names": [], + "mappings": "AACA,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACb,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAC,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAe,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAwB,EAAE,CAAA,CAAA;AACjE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAC,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAe,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAwB,EAAE,CAAA,CAAA;", + "entry-package-info": "har|1.0.0" + }, + "har|har|1.0.0|Index.ts": { + "version": 3, + "file": "Index.ets", + "sourceRoot": "", + "sources": [ + "har/Index.ets" + ], + "names": [], + "mappings": "OAAO,EAAE,QAAQ,EAAC,MAAM,EAAE;OACnB,EAAC,CAAC,EAAC", + "entry-package-info": "har|1.0.0" + }, + "har|har|1.0.0|src/main/ets/components/a.ts": { + "version": 3, + "file": "a.ts", + "sourceRoot": "", + "sources": [ + "har/src/main/ets/components/a.ts" + ], + "names": [], + "mappings": "AAEA,MAAM,CAAC,MAAM,IAAI,EAAC,MAAM,GAAC,OAAO,CAAA;AAGhC,MAAM,QAAQ,CAAC,CAAA;IACb,MAAM,CAAC,MAAM,EAAE,GAAC,KAAK,CAAC;IACtB,MAAM,CAAC,MAAM,EAAE,EAAC,MAAM,GAAC,CAAC,CAAC;CAC1B;AAED,MAAM,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC;AACxB,MAAM,CAAC,MAAM,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC5B,MAAM,CAAC,IAAI,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC;AAG9B,SAAS,EAAE,CAAC,CAAC,EAAC,CAAC,EAAC,CAAC,IAAE,CAAC;AACpB,SAAS,EAAE,CAAC,CAAC,EAAC,CAAC,GAAC,CAAC,EAAC,GAAG,CAAC;AAEtB,CAAC;AACD,EAAE,CAAC,CAAC,CAAC,CAAA;AACL,EAAE,CAAC,CAAC,EAAC,CAAC,CAAC,CAAA;AACP,MAAM,SAAS;IACb,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB;AAGD,MAAM,UAAU;IACd,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,MAAM,CAAC;QACnC,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAC7B,OAAO;YACL,IAAI,IAAI,cAAc,CAAC,MAAM,CAAC;gBAC5B,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE;oBACvB,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;iBAC9C;qBAAM;oBACL,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;iBACzC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF;AAED,MAAM,QAAQ,GAAG,IAAI,UAAU,EAAE,CAAC;AAClC,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,mBAAmB;CACnD;AAED,UAAU,GAAG,CAAC,CAAC;IACb,KAAK,EAAE,CAAC,CAAC;IACT,QAAQ,IAAI,CAAC,CAAC;CACf;AAED,MAAM,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG;IAC7B,KAAK,EAAE,EAAE;IACT,QAAQ;QACN,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;CACF,CAAC;AAEF,MAAM,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG;IAC7B,KAAK,EAAE,oBAAoB;IAC3B,QAAQ;QACN,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;CACF,CAAC;AACF,MAAM,MAAM,IAAI,GAAG,MAAM,CAAC;AAE1B,MAAM,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,CAAC,iBAAiB;AAE7C,UAAU,CAAC,CAAA;IACT,MAAM,WAAW,CAAC,CAAA;QAChB,MAAM,UAAU,GAAG,IAAG,IAAI,GAAC,CAAC;KAC7B;IACD,MAAM,CAAC,MAAM,MAAM,EAAC,MAAM,GAAC,CAAC,CAAC;IAC7B,MAAM,SAAS;QACb,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;KACvB;IACD,UAAU,GAAG,CAAC,CAAC;QACb,KAAK,EAAE,CAAC,CAAC;QACT,QAAQ,IAAI,CAAC,CAAC;KACf;IACD,KAAK,MAAM,SAAS;QAClB,EAAE,IAAA;QACF,IAAI,IAAA;QACJ,IAAI,IAAA;QACJ,KAAK,IAAA;KACN;CAEF;AACD,UAAU;AACV,KAAK,EAAE,GAAG,MAAM,GAAG,MAAM,CAAC;AAE1B,UAAU;AACV,KAAK,UAAU,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;AAEnD,MAAM,GAAG,EAAE,UAAU,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC;AAExC,UAAU;AACV,KAAK,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAC/B,KAAK,GAAG,GAAG,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtC,MAAM,GAAG,EAAE,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AAEpD,UAAU;AACV,KAAK,WAAW,GAAG;IAAC,MAAM;IAAE,MAAM;CAAC,CAAC;AAEpC,MAAM,KAAK,EAAE,WAAW,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAEpC,UAAU;AACV,KAAK,OAAO,GAAG;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,OAAO,EAAE,OAAO,GAAG;IACvB,IAAI,EAAE,QAAQ;IACd,KAAK,EAAE,IAAI;CACZ,CAAC;AACF,SAAS;AACT,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC;AAE9D,MAAM;AACN,6CAA6C;AAC7C,MAAM,UAAU,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM;IAC5C,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC;AAED,MAAM,WAAW,CAAC,CAAA;IAChB,MAAM,WAAW,CAAC,CAAA;QAChB,MAAM,UAAU,CAAC,KAAG,CAAC;QACrB,SAAS,CAAC,KAAG,CAAC;KACf;IACD,UAAU,EAAE,CAAA,GAAE;CACf;AAED,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;AAEP,UAAU,EAAE,CAAC;IACX,MAAM,KAAK,GAAG,CAAC,CAAC;CACjB;AAED,KAAK,MAAM;IACT,GAAG,IAAA;IACH,GAAG,IAAA;CACJ;AAED,OAAO,EAAC,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,IAAI,OAAO,EAAC,CAAC;AAGrD,OAAO,UAAU,IAAI,CAAC,EAAE,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EACtD,EAAE,EAAE,EAAE,GACL,GAAG,CAAC;AAGP,SAAS,GAAG,CAAC,GAAG,IAAI;AAEpB,CAAC;AAGD,MAAM,QAAQ,CAAC,CAAC;IACd,MAAM,UAAU,CAAC,KAAI,CAAC;IACtB,SAAU,CAAC,KAAG,CAAC;CAChB;AAED,OAAO,CAAC,MAAM,EAAE,EAAE,KAAK,GAAG,SAAS,GAAG,IAAI,CAAC;AAG3C,MAAM,CAAC,IAAI,KAAK,EAAC;IAAC,IAAI,EAAC,MAAM,CAAC;IAAA,GAAG,EAAC,MAAM,CAAA;CAAC,GAAC;IACxC,IAAI,EAAC,QAAQ;IACb,GAAG,EAAC,EAAE;CACP,CAAA;AAGD,MAAM,MAAM,UAAU,GAAG;IACvB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB,CAAA", + "entry-package-info": "har|1.0.0" + }, + "har|har|1.0.0|src/main/ets/components/aaa.ts": { + "version": 3, + "file": "aaa.ts", + "sourceRoot": "", + "sources": [ + "har/src/main/ets/components/aaa.ts" + ], + "names": [], + "mappings": "", + "entry-package-info": "har|1.0.0" + }, + "har|har|1.0.0|src/main/ets/components/MainPage.ts": { + "version": 3, + "file": "MainPage.ets", + "sourceRoot": "", + "sources": [ + "har/src/main/ets/components/MainPage.ets" + ], + "names": [], + "mappings": ";;;;IAIS,OAAO,GAAE,MAAM;;OAJjB,EAAE,IAAI,EAAE;AAGf,MAAM,OAAQ,QAAQ;IADtB;;;;;sDAE2B,IAAI;;;KAJJ;;;;;;;;;;;;;;;;IAIzB,4CAAgB,MAAM,EAAQ;QAAvB,OAAO;;;QAAP,OAAO,WAAE,MAAM;;;IAEtB;;YACE,GAAG;YAAH,GAAG,CAQF,MAAM,CAAC,MAAM;;;YAPZ,MAAM;YAAN,MAAM,CAKL,KAAK,CAAC,MAAM;;;YAJX,IAAI,QAAC,IAAI,CAAC,OAAO;YAAjB,IAAI,CACD,QAAQ,CAAC,EAAE;YADd,IAAI,CAED,UAAU,CAAC,UAAU,CAAC,IAAI;;QAF7B,IAAI;QADN,MAAM;QADR,GAAG;KASJ;;;;;AAIH,MAAM,CAAC,MAAM,MAAM,EAAC,MAAM,GAAC,YAAY,CAAC", + "entry-package-info": "har|1.0.0" + } +} \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/compileContextInfo.json b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/compileContextInfo.json new file mode 100644 index 000000000..c23a0a795 --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/compileContextInfo.json @@ -0,0 +1,11 @@ +{ + "hspPkgNames": [], + "compileEntries": [ + "&har/src/main/ets/components/a&1.0.0", + "&har/src/main/ets/components/aaa&1.0.0", + "&har/src/main/ets/components/MainPage&1.0.0", + "&har/build/default/generated/profile/default/ModuleInfo&1.0.0", + "&har/Index&1.0.0" + ], + "updateVersionInfo": {} +} \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/filesInfo.txt b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/filesInfo.txt new file mode 100644 index 000000000..da702d347 --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/filesInfo.txt @@ -0,0 +1,3 @@ +har33/build/default/cache/default/default@HarCompileArkTS/esmodule/debug/har33/Index.ts;&har33/Index&1.0.0;esm;har33|har33|1.0.0|Index.ts;har33;false +har33/build/default/cache/default/default@HarCompileArkTS/esmodule/debug/har33/src/main/ets/components/MainPage.ts;&har33/src/main/ets/components/MainPage&1.0.0;esm;har33|har33|1.0.0|src/main/ets/components/MainPage.ts;har33;false +har33/build/default/cache/default/default@HarCompileArkTS/esmodule/debug/har33/build/default/generated/profile/default/ModuleInfo.js;&har33/build/default/generated/profile/default/ModuleInfo&1.0.0;esm;har33|har33|1.0.0|build/default/generated/profile/default/ModuleInfo.js;har33;false diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/npmEntries.txt b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/npmEntries.txt new file mode 100644 index 000000000..5c9e7b7c8 --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/npmEntries.txt @@ -0,0 +1,7 @@ +@system.app:@native.system.app +@ohos.app:@native.ohos.app +@system.router:@native.system.router +@system.curves:@native.system.curves +@ohos.curves:@native.ohos.curves +@system.matrix4:@native.system.matrix4 +@ohos.matrix4:@native.ohos.matrix4 diff --git a/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/sourceMaps.json b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/sourceMaps.json new file mode 100644 index 000000000..492661a46 --- /dev/null +++ b/compiler/test/ark_compiler_ut/testdata/testcase_def/mergeCacheData/originCacheDir2/sourceMaps.json @@ -0,0 +1,46 @@ +{ + "entry|entry|1.0.0|src/main/ets/entryability/EntryAbility.ts": { + "version": 3, + "file": "EntryAbility.ets", + "sources": [ + "entry/src/main/ets/entryability/EntryAbility.ets" + ], + "names": [], + "mappings": "YAAS,eAAe,MAAA,mCAAA,CAAA;OAAE,qBAAqB,MAAA,yCAAA,CAAA;OAAE,SAAS,MAAA,6BAAA,CAAA;YAAE,IAAI,MAAA,wBAAA,CAAA;OACvD,KAAK,MAAA,aAAA,CAAA;YACL,MAAM,MAAA,cAAA,CAAA;AAEf,MAAM,CAAC,OAAO,iBAA4B,SAAS;IACjD,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,eAAe,CAAC,WAAW,GAAG,IAAI;QAClE,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE,CAAC,YAAY,CAAC,qBAAqB,CAAC,SAAS,CAAC,kBAAkB,CAAC,CAAC;QACtG,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,kBAAkB,CAAC,CAAC;IAClE,CAAC;IAED,SAAS,IAAI,IAAI;QACf,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,mBAAmB,CAAC,CAAC;IACnE,CAAC;IAED,mBAAmB,CAAC,WAAW,EAAE,MAAM,CAAC,WAAW,GAAG,IAAI;QAExD,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,6BAA6B,CAAC,CAAC;QAE3E,WAAW,CAAC,WAAW,CAAC,aAAa,EAAE,CAAC,GAAG,EAAE,EAAE;YAC7C,IAAI,GAAG,CAAC,IAAI,EAAE;gBACZ,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,+CAA+C,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;gBAC3G,OAAO;aACR;YACD,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,mCAAmC,CAAC,CAAC;QACrE,CAAC,CAAC,CAAC;IACL,CAAC;IAED,oBAAoB,IAAI,IAAI;QAE1B,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,8BAA8B,CAAC,CAAC;IAC9E,CAAC;IAED,YAAY,IAAI,IAAI;QAElB,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,sBAAsB,CAAC,CAAC;IACtE,CAAC;IAED,YAAY,IAAI,IAAI;QAElB,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,sBAAsB,CAAC,CAAC;IACtE,CAAC;CACF", + "sourceRoot": "", + "entry-package-info": "entry|1.0.0" + }, + "entry|entry|1.0.0|src/main/ets/entrybackupability/EntryBackupAbility.ts": { + "version": 3, + "file": "EntryBackupAbility.ets", + "sources": [ + "entry/src/main/ets/entrybackupability/EntryBackupAbility.ets" + ], + "names": [], + "mappings": "OAAS,KAAK,MAAA,aAAA,CAAA;OACL,sBAAsB,MAAA,0CAAA,CAAA;AAAE,OAAA,KAAA,EAAA,iBAAA,aAAa,EAAA,MAAA,0CAAA,CAAA;AAE9C,MAAM,CAAC,OAAO,iBAAkC,sBAAsB;IACpE,KAAK,CAAC,QAAQ;QACZ,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;IAC/C,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,aAAa,EAAE,aAAa;QAC1C,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,yBAAyB,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC;IAC1F,CAAC;CACF", + "sourceRoot": "", + "entry-package-info": "entry|1.0.0" + }, + "entry|entry|1.0.0|src/main/ets/pages/Index.ts": { + "version": 3, + "file": "Index.ets", + "sources": [ + "entry/src/main/ets/pages/Index.ets" + ], + "names": [], + "mappings": ";;;;IAWS,OAAO,GAAE,MAAM,CAAA;;OAXjB,KAAK,EAAE,GAAG,EAAE,oDAAA;AAEnB,MAAM,aAAiB;IACrB,MAAM,CAAC,MAAM,IAAO,MAAM,GAAC,QAAQ,CAAA;IACnC,MAAM,WAAS,MAAM,CAAA;CACtB;AACD,IAAI,KAAK,EAAC,IAAS,GAAC,IAAa,CAAA;OAIrB,SAAA,MAAA;IAFZ,YAAA,MAAA,EAAA,MAAA,EAAA,EAAA,EAAA,KAAA,CAAA,CAAA,EAAA,KAAA,SAAA,EAAA,SAAA;;;;;sDAG2B,GAAG,EAAA,IAAA,EAAA,SAAA,CAAA,CAAA;;;IALG,CAAA;;;;;;;;;;;;;;;;IAK/B,OAAA,CAAA,SAAA,EAAA,wBAAA,CAAgB,MAAM,CAAO,CAAA;QAAtB,OAAO;;;IAAP,IAAA,OAAO,WAAE,MAAM;;;IAEtB,aAAA;;YACE,iBAAiB,CAAA,MAAA,EAAA,CAAA;YAAjB,iBAAiB,CAUhB,MAAM,CAAC,MAAM,CAAA,CAAA;YAVd,iBAAiB,CAWhB,KAAK,CAAC,MAAM,CAAA,CAAA;;;YAVX,IAAI,CAAA,MAAA,CAAC,IAAI,CAAC,OAAO,CAAA,CAAA;YAAjB,IAAI,CACD,EAAE,CAAC,YAAY,CAAA,CAAA;YADlB,IAAI,CAED,QAAQ,CAAC,EAAE,CAAA,CAAA;YAFd,IAAI,CAGD,UAAU,CAAC,UAAU,CAAC,IAAI,CAAA,CAAA;YAH7B,IAAI,CAID,UAAU,CAAC;gBACV,MAAM,EAAE,EAAE,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,aAAa,CAAC,MAAM,EAAE;gBAChE,MAAM,EAAE,EAAE,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,eAAe,CAAC,MAAM,EAAE;aACnE,CAAA,CAAA;;QAPH,IAAI,CAAA,GAAA,EAAA,CAAA;QADN,iBAAiB,CAAA,GAAA,EAAA,CAAA;IAYlB,CAAA;;;;;;;;", + "sourceRoot": "", + "entry-package-info": "entry|1.0.0" + }, + "entry|entry|1.0.0|src/main/ets/pages/a.ts": { + "version": 3, + "file": "test.ts", + "sources": [ + "entry/src/main/ets/pages/test.ts" + ], + "names": [], + "mappings": "AAAA,MAAM,CAAE,MAAM,GAAG,EAAC,MAAM,GAAC,QAAQ,CAAA;AAEjC,QAAQ;IACN,QAAQ,MAAO;CAChB;AACD,UAAU,CAAC,CAAA;CAEV", + "sourceRoot": "", + "entry-package-info": "entry|1.0.0" + } +} \ No newline at end of file -- Gitee From b5719557d0e98b839d35d64998243252c562276a Mon Sep 17 00:00:00 2001 From: zenghang Date: Mon, 3 Mar 2025 15:17:20 +0800 Subject: [PATCH 009/123] Add deaclare files for arkui Issue: IBQ5QI Signed-off-by: zenghang Change-Id: Ida7a0dca1d1641f4520cb867a58f3c69b37af351 --- compiler/src/ets_checker.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index e68003fda..ff2e38ca0 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -561,7 +561,7 @@ export function serviceChecker(rootFileNames: string[], newLogger: Object = null MemoryMonitor.stopRecordStage(processBuildHaprrecordInfo); } if (rollupShareObject?.projectConfig.mixCompile) { - generateDeclarationFileForSTS(rootFileNames, allResolvedModules); + generateDeclarationFileForSTS(rootFileNames); } if (globalProgram.program && (process.env.watchMode !== 'true' && !projectConfig.isPreview && @@ -1819,7 +1819,7 @@ export function resetEtsCheck(): void { fileToIgnoreDiagnostics = undefined; } -export function generateDeclarationFileForSTS(rootFileNames: string[], allResolvedModules: Set) { +export function generateDeclarationFileForSTS(rootFileNames: string[]) { if (!(projectConfig.compileHar || projectConfig.compileShared)) { return; } @@ -1830,19 +1830,25 @@ export function generateDeclarationFileForSTS(rootFileNames: string[], allResolv const regex = new RegExp(projectConfig.packageDir); const uniqueFiles = Array.from(new Set([ ...unixRootFileNames, - ...allResolvedModules + /** + * arkui lacks explicit import statements and needs to be manually added to the global rootfile, + * otherwise an error will be reported during the tsc compilation of declgen + */ + ...readDeaclareFiles() ])).filter(file => !regex.test(file)); const config: RunnerParms = { inputDirs: [], inputFiles: uniqueFiles, - outDir: path.resolve(projectConfig.aceModuleBuild, '../etsFortgz/ets'), - rootDir: projectConfig.projectRootPath, + outDir: projectConfig.dependentModuleMap.get(projectConfig.moduleName).declgenV2OutPath, + // use package name as folder name + rootDir: projectConfig.moduleRootPath, customResolveModuleNames: resolveModuleNames, customCompilerOptions: compilerOptions }; if (fs.existsSync(config.outDir)) { fs.rmSync(config.outDir, { recursive: true, force: true }); } + fs.mkdirSync(config.outDir, { recursive: true }); generateInteropDecls(config); } \ No newline at end of file -- Gitee From 115ed2ce0ad5e289059e5db2badb65825bb476fc Mon Sep 17 00:00:00 2001 From: zenghang Date: Wed, 12 Mar 2025 21:47:09 +0800 Subject: [PATCH 010/123] Provide includePath for declgen Issue: IBSX85 Signed-off-by: zenghang Change-Id: Ic113909c1927808642c82f275cd8c3cffe7b3932 --- compiler/src/ets_checker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index ff2e38ca0..fe10ad0e3 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -1844,7 +1844,8 @@ export function generateDeclarationFileForSTS(rootFileNames: string[]) { // use package name as folder name rootDir: projectConfig.moduleRootPath, customResolveModuleNames: resolveModuleNames, - customCompilerOptions: compilerOptions + customCompilerOptions: compilerOptions, + includePaths: [projectConfig.modulePath] }; if (fs.existsSync(config.outDir)) { fs.rmSync(config.outDir, { recursive: true, force: true }); -- Gitee From 78237a48e668ccfe3f0429d937811577e2312889 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Tue, 1 Apr 2025 22:35:36 +0800 Subject: [PATCH 011/123] fix preprocessor Signed-off-by: Jiakai Shi Change-Id: I012fb4f27f50ac37be383837641437cdf10382a4 --- arkui-plugins/common/predefines.ts | 12 +- arkui-plugins/common/program-visitor.ts | 93 +++++++++- arkui-plugins/ui-plugins/name-collector.ts | 88 ++++++++++ .../ui-plugins/preprocessor-transform.ts | 161 ++++++++++++++++-- .../ui-plugins/struct-transformer.ts | 3 +- arkui-plugins/ui-plugins/utils.ts | 19 +-- .../src/arkts-api/factory/nodeFactory.ts | 3 +- koala-wrapper/src/arkts-api/types.ts | 45 +++-- koala-wrapper/src/arkts-api/visitor.ts | 9 +- 9 files changed, 369 insertions(+), 64 deletions(-) create mode 100644 arkui-plugins/ui-plugins/name-collector.ts diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index e1c5281f8..c23026980 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -18,8 +18,13 @@ export const EXTERNAL_SOURCE_PREFIX_NAMES: string[] = [ "escompat" ]; +export const ARKUI_COMPONENT_IMPORT_NAME: string = "@ohos.arkui.component"; + +export const ARKUI_STATEMANAGEMENT_IMPORT_NAME: string = "@ohos.arkui.stateManagement"; + export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ - "@ohos.arkui" + ARKUI_COMPONENT_IMPORT_NAME, + ARKUI_STATEMANAGEMENT_IMPORT_NAME ]; export const IMPORT_SOURCE_MAP: Map> = new Map>([ @@ -46,7 +51,10 @@ export const IMPORT_SOURCE_MAP: Map> = new Map>; + +export interface ProgramHooks { + external?: ProgramHookLifeCycle, + source?: ProgramHookLifeCycle +} + +function flattenVisitorsInHooks( + programHooks?: ProgramHooks, + resetAfterValue?: arkts.Es2pandaContextState +): AbstractVisitor[] { + if (!programHooks) return []; + const flatMapInHook = (config: ProgramHookConfig): AbstractVisitor[] => { + if (!resetAfterValue) return []; + if (!config.resetAfter || (resetAfterValue !== config.resetAfter)) return []; + return config.visitors; + } + return [ + ...Object.values(programHooks.external || {}).flatMap(flatMapInHook), + ...Object.values(programHooks.source || {}).flatMap(flatMapInHook) + ]; +} + +function sortExternalSources(externalSources: arkts.ExternalSource[]): arkts.ExternalSource[] { + return externalSources.sort((a, b) => { + const prefix = ARKUI_COMPONENT_IMPORT_NAME; + const hasPrefixA = a.getName().startsWith(prefix); + const hasPrefixB = b.getName().startsWith(prefix); + + // If both have the prefix, maintain their original order + if (hasPrefixA && hasPrefixB) { + return 0; + } + // If neither has the prefix, maintain their original order + if (!hasPrefixA && !hasPrefixB) { + return 0; + } + // If only one has the prefix, the one with the prefix comes first + return hasPrefixA ? -1 : 1; + }); } export class ProgramVisitor extends AbstractVisitor { @@ -30,6 +79,7 @@ export class ProgramVisitor extends AbstractVisitor { private readonly state: arkts.Es2pandaContextState; private readonly visitors: AbstractVisitor[]; private readonly skipPrefixNames: string[]; + private readonly hooks?: ProgramHooks; private filenames: Map; constructor(options: ProgramVisitorOptions) { @@ -38,6 +88,7 @@ export class ProgramVisitor extends AbstractVisitor { this.state = options.state; this.visitors = options.visitors; this.skipPrefixNames = options.skipPrefixNames ?? []; + this.hooks = options.hooks; this.filenames = new Map(); } @@ -77,7 +128,7 @@ export class ProgramVisitor extends AbstractVisitor { visited.add(currProgram.peer); - for (const externalSource of currProgram.externalSources) { + for (const externalSource of sortExternalSources(currProgram.externalSources)) { // TODO: this is very time-consuming... if (matchPrefix(skipPrefixes, externalSource.getName())) { continue; @@ -96,14 +147,36 @@ export class ProgramVisitor extends AbstractVisitor { let programScript = program.astNode; programScript = this.visitor(programScript, program, this.externalSourceName); + const visitorsToReset = flattenVisitorsInHooks(this.hooks, this.state); + visitorsToReset.forEach((visitor) => visitor.reset()); + return program; } - visitor(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): arkts.EtsScript { + visitor( + node: arkts.AstNode, + program?: arkts.Program, + externalSourceName?: string + ): arkts.EtsScript { + let hook: ProgramHookLifeCycle | undefined; + let script: arkts.EtsScript = node as arkts.EtsScript; let count: number = 0; + const isExternal: boolean = !!externalSourceName; + + // pre-run visitors + hook = isExternal ? this.hooks?.external : this.hooks?.source; + const preVisitors = hook?.pre?.visitors ?? []; + for (const transformer of preVisitors) { + transformer.isExternal = isExternal; + transformer.externalSourceName = externalSourceName; + transformer.program = program; + transformer.visitor(script); + if (!this.hooks?.external?.pre?.resetAfter) transformer.reset(); + } + for (const transformer of this.visitors) { - transformer.isExternal = !!externalSourceName; + transformer.isExternal = isExternal; transformer.externalSourceName = externalSourceName; transformer.program = program; script = transformer.visitor(script) as arkts.EtsScript; @@ -118,6 +191,18 @@ export class ProgramVisitor extends AbstractVisitor { count += 1; } } + + // post-run visitors + hook = isExternal ? this.hooks?.external : this.hooks?.source; + const postVisitors = hook?.post?.visitors ?? []; + for (const transformer of postVisitors) { + transformer.isExternal = isExternal; + transformer.externalSourceName = externalSourceName; + transformer.program = program; + transformer.visitor(script); + if (!this.hooks?.external?.pre?.resetAfter) transformer.reset(); + } + return script; } } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/name-collector.ts b/arkui-plugins/ui-plugins/name-collector.ts new file mode 100644 index 000000000..0609f26b9 --- /dev/null +++ b/arkui-plugins/ui-plugins/name-collector.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "@koalaui/libarkts"; +import { AbstractVisitor } from "../common/abstract-visitor"; +import { hasBuilderLambdaAnnotation } from "./utils"; + +interface ComponentInfo { + argsNum: number; +} + +type ComponentCollection = Map + +export class NameCollector extends AbstractVisitor { + private components: ComponentCollection; + private static instance: NameCollector; + + private constructor() { + super(); + this.components = new Map(); + } + + static getInstance(): NameCollector { + if (!this.instance) { + this.instance = new NameCollector(); + } + return this.instance; + } + + getComponents(): string[] { + return Array.from(this.components.keys()); + } + + getComponentInfo(componentName: string): ComponentInfo | undefined { + return this.components.get(componentName); + } + + collectInfoFromComponentFunction(component: arkts.ScriptFunction): void { + if (!component.id) return; + + const name: string = component.id.name; + const argsNum: number = component.params.length; + this.components.set(name, { argsNum }); + } + + reset(): void { + super.reset(); + this.components.clear(); + } + + findComponentFunction(node: arkts.FunctionDeclaration): arkts.ScriptFunction | undefined { + const isDeclareAndExport: boolean = arkts.hasModifierFlag( + node, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE + | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT + ) + if (!isDeclareAndExport) return undefined; + + const isComponentBuilder = hasBuilderLambdaAnnotation(node); + if (!isComponentBuilder) return undefined; + if (!node.scriptFunction.id) return undefined; + + return node.scriptFunction; + } + + visitor(node: arkts.AstNode): arkts.AstNode { + const newNode = this.visitEachChild(node); + if (arkts.isFunctionDeclaration(newNode)) { + const component = this.findComponentFunction(newNode); + if (!!component) { + this.collectInfoFromComponentFunction(component); + } + } + return newNode; + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 325bfaf33..627502e52 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -25,21 +25,46 @@ import { factory } from "./ui-factory"; import { + ARKUI_COMPONENT_IMPORT_NAME, IMPORT_SOURCE_MAP, OUTPUT_DEPENDENCY_MAP } from "../common/predefines"; +import { + NameCollector +} from "./name-collector"; + +interface MemoImportCollection { + memo: boolean; + memoContextType: boolean; + memoIdType: boolean; +} export class PreprocessorTransformer extends AbstractVisitor { private outNameArr: string[] = []; + private memoNameArr: string[] = []; private structInterfaceImport: arkts.ETSImportDeclaration[] = []; + private memoImportCollection: Partial = {}; + private localComponentNames: string[] = []; + private isMemoImportOnce: boolean = false; + + private readonly nameCollector: NameCollector; + + constructor(options?: VisitorOptions) { + super(options); + this.nameCollector = NameCollector.getInstance(); + } reset(): void { super.reset(); this.outNameArr = []; + this.memoNameArr = []; this.structInterfaceImport = []; + this.memoImportCollection = {}; + this.localComponentNames = []; + this.isMemoImportOnce = false; } - isCustomConponentDecl(node: arkts.CallExpression) { + isCustomConponentDecl(node: arkts.CallExpression): boolean { const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); const nodeName: string = node.expression.dumpSrc(); @@ -49,6 +74,11 @@ export class PreprocessorTransformer extends AbstractVisitor { return false; } + isComponentFunctionCall(node: arkts.CallExpression): boolean { + if (!node || !arkts.isIdentifier(node.expression)) return false; + return this.localComponentNames.includes(node.expression.name); + } + transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { if (arkts.isObjectExpression(node.arguments[0])) { const componentName: string = @@ -66,25 +96,57 @@ export class PreprocessorTransformer extends AbstractVisitor { node, node.expression, node.typeArguments, - [newArg, ...node.arguments.slice(1)], - node.trailingBlock - ); + [newArg, ...node.arguments.slice(1)] + ).setTralingBlock(node.trailingBlock); } else { return node; } } + transformComponentFunctionCall(node: arkts.CallExpression) { + if (!node || !arkts.isIdentifier(node.expression)) return node; + + const componentInfo = this.nameCollector.getComponentInfo(node.expression.name); + if (!componentInfo) return node; + if (componentInfo.argsNum === 0) return node; + if (node.arguments.length >= componentInfo.argsNum - 1) return node; + + const defaultArgs: arkts.UndefinedLiteral[] = []; + let count = 0; + while (count < componentInfo.argsNum - node.arguments.length - 1) { + defaultArgs.push(arkts.factory.createUndefinedLiteral()); + count ++; + } + return arkts.factory.updateCallExpression( + node, + node.expression, + node.typeArguments, + [...node.arguments, ...defaultArgs] + ); + } + addDependencesImport(node: arkts.ETSImportDeclaration): void { + if (!node.source) return; + + const isFromCompImport: boolean = node.source.str === ARKUI_COMPONENT_IMPORT_NAME; const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); - node.specifiers.forEach((item: arkts.AstNode) => { - if (!arkts.isImportSpecifier(item)) return; - + node.specifiers.forEach( + (item: arkts.AstNode) => { + if (!arkts.isImportSpecifier(item) || !item.imported?.name) return; + + const importName: string = item.imported.name; + this.memoImportCollection.memo ||= importName === "memo"; + this.memoImportCollection.memoContextType ||= importName === "__memo_context_type"; + this.memoImportCollection.memoIdType ||= importName === "__memo_id_type"; + if (isFromCompImport && this.nameCollector.getComponents().includes(importName)) { + this.localComponentNames.push(item.local?.name ?? importName) + } + if ( - item.imported?.name && - structCollection.has(item.imported?.name) && + structCollection.has(importName) && this.isExternal === false ) { - const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + item.imported?.name; + const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + importName; const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( node.source?.clone(), [factory.createAdditionalImportSpecifier(interfaceName, interfaceName)], @@ -92,7 +154,7 @@ export class PreprocessorTransformer extends AbstractVisitor { ); this.structInterfaceImport.push(newImport); } else { - this.addImportWithSpecifier(item); + this.addImportWithSpecifier(item, node.source!); } } ); @@ -108,6 +170,14 @@ export class PreprocessorTransformer extends AbstractVisitor { return dependencyName; } + updateSourceDependencyMap(key: string, value: string[]): void { + const newValue: Set = IMPORT_SOURCE_MAP.get(key) ?? new Set(); + for (const v of value) { + newValue.add(v); + } + IMPORT_SOURCE_MAP.set(key, newValue); + } + getOutDependencyName(inputName: string): string[] { const sourceName: string[] = []; if (OUTPUT_DEPENDENCY_MAP.has(inputName)) { @@ -118,11 +188,55 @@ export class PreprocessorTransformer extends AbstractVisitor { return sourceName; } - addImportWithSpecifier(node: arkts.ImportSpecifier): void { - if (!node.imported?.name) { - return; + updateOutDependencyMap(key: string, value: string[]): void { + const oldValue: string[] = OUTPUT_DEPENDENCY_MAP.get(key) ?? []; + const newValue: string[] = [...value, ...oldValue]; + OUTPUT_DEPENDENCY_MAP.set(key, newValue); + } + + clearGenSymInOutDependencyMap(genSymKey: string): void { + if (OUTPUT_DEPENDENCY_MAP.has(genSymKey)) { + OUTPUT_DEPENDENCY_MAP.delete(genSymKey); + } + } + + prepareDependencyMap(node: arkts.ImportSpecifier, source: arkts.StringLiteral): void { + if (!node.imported?.name) return; + + // Handling component imports + const importName: string = node.imported.name; + const sourceName: string = source.str; + if ( + this.nameCollector.getComponents().includes(importName) + && sourceName === ARKUI_COMPONENT_IMPORT_NAME + ) { + const newDependencies = [`${importName}Attribute`]; + this.updateOutDependencyMap(importName, newDependencies); + this.updateSourceDependencyMap(sourceName, newDependencies); + } + } + + prepareMemoImports(): void { + const newDependencies = []; + if (!this.memoImportCollection.memo) { + newDependencies.push("memo"); + } + if (!this.memoImportCollection.memoContextType) { + newDependencies.push("__memo_context_type"); + } + if (!this.memoImportCollection.memoIdType) { + newDependencies.push("__memo_id_type"); } + if (newDependencies.length > 0) { + this.memoNameArr.push(...newDependencies); + this.isMemoImportOnce = true; + } + } + addImportWithSpecifier(node: arkts.ImportSpecifier, source: arkts.StringLiteral): void { + if (!node.imported?.name) return; + + this.prepareDependencyMap(node, source); const outName: string[] = this.getOutDependencyName(node.imported?.name); this.outNameArr.push(...outName); } @@ -131,7 +245,9 @@ export class PreprocessorTransformer extends AbstractVisitor { if (!this.program) { throw Error("Failed to insert import: Transformer has no program"); } - new Set(this.outNameArr).forEach((item: string) => { + + const outNames = new Set([...this.outNameArr, ...this.memoNameArr]); + outNames.forEach((item: string) => { const source: string = this.getSourceDependency(item); const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( arkts.factory.create1StringLiteral(source), @@ -145,13 +261,24 @@ export class PreprocessorTransformer extends AbstractVisitor { }); } + enter(node: arkts.AstNode): void { + if (this.isExternal && arkts.isFunctionDeclaration(node)) { + const component = this.nameCollector.findComponentFunction(node); + if (!!component) this.nameCollector.collectInfoFromComponentFunction(component); + } + } + visitor(node: arkts.AstNode): arkts.AstNode { + this.enter(node); const newNode = this.visitEachChild(node) if (arkts.isCallExpression(newNode) && this.isCustomConponentDecl(newNode)) { return this.transformComponentCall(newNode); - } else if (arkts.isETSImportDeclaration(newNode)) { - this.addDependencesImport(newNode); + } else if (arkts.isCallExpression(newNode) && this.isComponentFunctionCall(newNode)) { + return this.transformComponentFunctionCall(newNode); + } if (arkts.isETSImportDeclaration(node)) { + this.addDependencesImport(node); } else if (arkts.isEtsScript(node)) { + if (!this.isMemoImportOnce) this.prepareMemoImports(); this.updateScriptWithImport(); } return newNode; diff --git a/arkui-plugins/ui-plugins/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-transformer.ts index a12b81a9c..e9f6d73e7 100644 --- a/arkui-plugins/ui-plugins/struct-transformer.ts +++ b/arkui-plugins/ui-plugins/struct-transformer.ts @@ -417,8 +417,7 @@ function transformResource(resourceNode: arkts.CallExpression, projectConfig: Pr resourceNode, arkts.factory.createIdentifier(transformedKey), resourceNode.typeArguments, - newArgs, - resourceNode.trailingBlock + newArgs ); } diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index 74038ff6f..ab9cc8571 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -15,7 +15,6 @@ import * as arkts from '@koalaui/libarkts'; import { isAnnotation } from '../common/arkts-utils'; -import { DecoratorNames, isDecoratorAnnotation } from './property-translators/utils'; export enum CustomComponentNames { ENTRY_ANNOTATION_NAME = 'Entry', @@ -89,7 +88,11 @@ export function isBuilderLambdaAnnotation(node: arkts.AnnotationUsage): boolean return isAnnotation(node, BuilderLambdaNames.ANNOTATION_NAME); } -export function hasBuilderLambdaAnnotation(node: arkts.ScriptFunction | arkts.ETSParameterExpression): boolean { +export type BuilderLambdaAstNode = arkts.ScriptFunction + | arkts.ETSParameterExpression + | arkts.FunctionDeclaration; + +export function hasBuilderLambdaAnnotation(node: BuilderLambdaAstNode): boolean { return node.annotations.some(isBuilderLambdaAnnotation); } @@ -122,14 +125,6 @@ export function findBuilderLambdaInMethod(node: arkts.MethodDefinition): arkts.A return undefined; } -export function isBuilderLambdaFunction(node: arkts.FunctionExpression): boolean { - return hasBuilderLambdaAnnotation(node.scriptFunction); -} - -export function findBuilderLambdaInFunction(node: arkts.FunctionExpression): arkts.AnnotationUsage | undefined { - return findBuilderLambdaAnnotation(node.scriptFunction); -} - export function isBuilderLambdaCall(node: arkts.CallExpression | arkts.Identifier): boolean { const expr = arkts.isIdentifier(node) ? node : node.expression; const decl = arkts.getDecl(expr); @@ -140,7 +135,7 @@ export function isBuilderLambdaCall(node: arkts.CallExpression | arkts.Identifie return isBuilderLambdaMethod(decl); } if (arkts.isFunctionExpression(decl)) { - return isBuilderLambdaFunction(decl); + return hasBuilderLambdaAnnotation(decl.scriptFunction); } return false; } @@ -155,7 +150,7 @@ export function findBuilderLambdaInCall( return findBuilderLambdaInMethod(decl); } if (arkts.isFunctionExpression(decl)) { - return findBuilderLambdaInFunction(decl); + return findBuilderLambdaAnnotation(decl.scriptFunction); } return undefined; } diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index b368f8798..394dad37e 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -126,7 +126,8 @@ export const factory = { get updateCallExpression() { return updateThenAttach( CallExpression.update, - attachModifiers + attachModifiers, + (node: CallExpression, original: CallExpression) => !!original.trailingBlock ? node.setTralingBlock(original.trailingBlock) : node ) }, get createExpressionStatement() { diff --git a/koala-wrapper/src/arkts-api/types.ts b/koala-wrapper/src/arkts-api/types.ts index af688c17d..b4aaae91a 100644 --- a/koala-wrapper/src/arkts-api/types.ts +++ b/koala-wrapper/src/arkts-api/types.ts @@ -165,15 +165,14 @@ export class CallExpression extends Expression { unpackNodeArray(global.generatedEs2panda._TSTypeParameterInstantiationParamsConst(global.context, tsTypeParameterInstantiation.peer)) : undefined this.arguments = unpackNodeArray( global.generatedEs2panda._CallExpressionArguments(global.context, this.peer)) - this.trailingBlock = unpackNode( - global.generatedEs2panda._CallExpressionTrailingBlockConst(global.context, this.peer)) } static create( expression: AstNode, typeArguments: readonly TypeNode[] | undefined, args: readonly AstNode[] | undefined, - trailingBlock: AstNode | undefined = undefined + isOptional: boolean = false, + trailingComma: boolean = false ): CallExpression { const peer = global.generatedEs2panda._CreateCallExpression( global.context, @@ -181,16 +180,10 @@ export class CallExpression extends Expression { passNodeArray(args), args?.length ?? 0, typeArguments ? passNode(TSTypeParameterInstantiation.createTSTypeParameterInstantiation(typeArguments)) : nullptr, - false, - false + isOptional, + trailingComma ) - const call = new CallExpression(peer) - if (trailingBlock) { - global.generatedEs2panda._CallExpressionSetTrailingBlock( - global.context, peer, trailingBlock?.peer - ) - } - return call + return new CallExpression(peer) } static update( @@ -198,7 +191,8 @@ export class CallExpression extends Expression { expression: AstNode, typeArguments: readonly TypeNode[] | undefined, args: readonly AstNode[] | undefined, - trailingBlock: AstNode | undefined = undefined + isOptional: boolean = false, + trailingComma: boolean = false ): CallExpression { const peer = global.es2panda._UpdateCallExpression( global.context, @@ -207,22 +201,27 @@ export class CallExpression extends Expression { passNodeArray(args), args?.length ?? 0, typeArguments ? passNode(TSTypeParameterInstantiation.createTSTypeParameterInstantiation(typeArguments)) : nullptr, - false, - false + isOptional, + trailingComma ) - const call = new CallExpression(peer) - if (trailingBlock) { - global.generatedEs2panda._CallExpressionSetTrailingBlock( - global.context, peer, trailingBlock?.peer - ) - } - return call + return new CallExpression(peer) + } + + get trailingBlock(): BlockStatement | undefined { + return unpackNode( + global.generatedEs2panda._CallExpressionTrailingBlockConst(global.context, this.peer) + ); + } + + setTralingBlock(trailingBlock: BlockStatement | undefined): this { + if (!trailingBlock) return this; + global.generatedEs2panda._CallExpressionSetTrailingBlock(global.context, this.peer, trailingBlock.peer); + return this; } readonly expression: AstNode // Expression readonly typeArguments: readonly TypeNode[] | undefined readonly arguments: readonly Expression[] - readonly trailingBlock: AstNode|undefined // BlockStatement } export class AssignmentExpression extends AstNode { diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index 6fe357673..944f5579f 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -151,13 +151,16 @@ export function visitEachChild( ); } if (isCallExpression(node)) { - return factory.updateCallExpression( + const call = factory.updateCallExpression( node, nodeVisitor(node.expression, visitor), nodesVisitor(node.typeArguments, visitor), - nodesVisitor(node.arguments, visitor), - nodeVisitor(node.trailingBlock, visitor) + nodesVisitor(node.arguments, visitor) ); + if (!!node.trailingBlock) { + call.setTralingBlock(nodeVisitor(node.trailingBlock, visitor)); + } + return call; } if (isFunctionDeclaration(node)) { return factory.updateFunctionDeclaration( -- Gitee From a876b05849d60e23a7319d76747245bebe60b4bf Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 2 Apr 2025 10:12:10 +0800 Subject: [PATCH 012/123] fix if-else builder-lambda transform Signed-off-by: Jiakai Shi Change-Id: I37a7ddcd7a137cca26b86e5e0e7e851126115b2b --- .../ui-plugins/builder-lambda-transformer.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts index dbe3ce61f..be6c04348 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts @@ -154,6 +154,29 @@ function updateContentBodyInBuilderLambda( transformBuilderLambda(statement.expression) ); } + if (arkts.isIfStatement(statement)) { + return arkts.factory.updateIfStatement( + statement, + statement.test, + arkts.isBlockStatement(statement.consequent) + ? arkts.factory.updateBlock( + statement.consequent, + statement.consequent.statements.map( + (st) => updateContentBodyInBuilderLambda(st, isExternal) + ) + ) + : statement.consequent, + !!statement.alternate && arkts.isBlockStatement(statement.alternate) + ? arkts.factory.updateBlock( + statement.alternate, + statement.alternate.statements.map( + (st) => updateContentBodyInBuilderLambda(st, isExternal) + ) + ) + : statement.alternate + ) + } + return statement; } -- Gitee From 957fb01f710c54490c553557a7c5f4bcaf5d311a Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Wed, 2 Apr 2025 15:52:07 +0800 Subject: [PATCH 013/123] update debug dump output dir to cachePath from projectConfig Signed-off-by: fengyuxin Change-Id: I2c240e354f05f33df1bd011e430ea4acbaa3f7f1 --- arkui-plugins/common/debug.ts | 7 ++++--- arkui-plugins/common/plugin-context.ts | 3 ++- arkui-plugins/common/program-visitor.ts | 14 +++++++++++--- arkui-plugins/memo-plugins/index.ts | 8 +++++--- arkui-plugins/ui-plugins/index.ts | 14 +++++++++----- 5 files changed, 31 insertions(+), 15 deletions(-) diff --git a/arkui-plugins/common/debug.ts b/arkui-plugins/common/debug.ts index 7d13d26c8..5f380559a 100644 --- a/arkui-plugins/common/debug.ts +++ b/arkui-plugins/common/debug.ts @@ -30,11 +30,12 @@ function mkDir(filePath: string): void { fs.mkdirSync(filePath); } -export function debugDump(content: string, fileName: string, isInit: boolean): void { +export function debugDump(content: string, fileName: string, isInit: boolean, cachePath: string | undefined): void { if (!isDebugDump) return; - const currentDirectory = process.cwd(); - const outputDir: string = path.resolve(currentDirectory, 'entry', 'build', 'default', 'generated', 'dist', 'cache'); + const outputDir: string = cachePath + ? path.resolve(currentDirectory, cachePath) + : path.resolve(currentDirectory, 'dist', 'cache'); const filePath: string = path.resolve(outputDir, fileName); if (!fs.existsSync(outputDir)) { mkDir(outputDir); diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts index 6c331858c..7da72d863 100644 --- a/arkui-plugins/common/plugin-context.ts +++ b/arkui-plugins/common/plugin-context.ts @@ -54,7 +54,8 @@ export class PluginContext { export interface ProjectConfig { bundleName: string, - moduleName: string + moduleName: string, + cachePath: string } export type PluginHandlerFunction = () => void; diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 2f1ea833c..2e2a242ae 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -18,6 +18,7 @@ import { AbstractVisitor, VisitorOptions } from "./abstract-visitor"; import { matchPrefix } from "./arkts-utils"; import { debugDump, getDumpFileName } from "./debug"; import { ARKUI_COMPONENT_IMPORT_NAME } from "./predefines"; +import { PluginContext } from "./plugin-context"; export interface ProgramVisitorOptions extends VisitorOptions { pluginName: string; @@ -25,6 +26,7 @@ export interface ProgramVisitorOptions extends VisitorOptions { visitors: AbstractVisitor[]; skipPrefixNames: string[]; hooks?: ProgramHooks; + pluginContext: PluginContext; } export interface ProgramHookConfig { @@ -81,6 +83,7 @@ export class ProgramVisitor extends AbstractVisitor { private readonly skipPrefixNames: string[]; private readonly hooks?: ProgramHooks; private filenames: Map; + private pluginContext: PluginContext; constructor(options: ProgramVisitorOptions) { super(options); @@ -90,6 +93,7 @@ export class ProgramVisitor extends AbstractVisitor { this.skipPrefixNames = options.skipPrefixNames ?? []; this.hooks = options.hooks; this.filenames = new Map(); + this.pluginContext = options.pluginContext; } reset(): void { @@ -111,17 +115,20 @@ export class ProgramVisitor extends AbstractVisitor { if (currProgram.peer !== program.peer) { const name: string = this.filenames.get(currProgram.peer)!; + const cachePath: string | undefined = this.pluginContext.getProjectConfig()?.cachePath; debugDump( currProgram.astNode.dumpSrc(), getDumpFileName(this.state, "ORI", undefined, name), - true + true, + cachePath ); const script = this.visitor(currProgram.astNode, currProgram, name); if (script) { debugDump( script.dumpSrc(), getDumpFileName(this.state, this.pluginName, undefined, name), - true + true, + cachePath ); } } @@ -186,7 +193,8 @@ export class ProgramVisitor extends AbstractVisitor { debugDump( script.dumpSrc(), getDumpFileName(this.state, this.pluginName, count, transformer.constructor.name), - true + true, + this.pluginContext.getProjectConfig()?.cachePath ); count += 1; } diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index 841b6410a..e7d75467c 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -33,7 +33,8 @@ export function unmemoizeTransform(): Plugins { let script = program.astNode; if (script) { debugLog("[BEFORE MEMO SCRIPT] script: ", script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 5, "MEMO_AfterCheck_Begin"), true); + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; + debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 5, "MEMO_AfterCheck_Begin"), true, cachePath); const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); const parameterTransformer = new ParameterTransformer({ positionalIdTracker }); @@ -50,14 +51,15 @@ export function unmemoizeTransform(): Plugins { pluginName: unmemoizeTransform.name, state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, visitors: [functionTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, }); program = programVisitor.programVisitor(program); script = program.astNode; debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 6, "MEMO_AfterCheck_End"), true); + debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 6, "MEMO_AfterCheck_End"), true, cachePath); arkts.recheckSubtree(script); this.setArkTSAst(script); diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index e1d778524..bddf14d3d 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -31,8 +31,9 @@ export function uiTransform(): Plugins { let program = arkts.arktsGlobal.compilerContext.program; let script = program.astNode; if (script) { + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; debugLog('[BEFORE PARSED SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true, cachePath); const componentTransformer = new ComponentTransformer(); const preprocessorTransformer = new PreprocessorTransformer(); @@ -40,14 +41,15 @@ export function uiTransform(): Plugins { pluginName: uiTransform.name, state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, visitors: [componentTransformer, preprocessorTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, }); program = programVisitor.programVisitor(program); script = program.astNode; debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), true); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), true, cachePath); this.setArkTSAst(script); console.log('[UI PLUGIN] AFTER PARSED EXIT'); @@ -60,8 +62,9 @@ export function uiTransform(): Plugins { let program = arkts.arktsGlobal.compilerContext.program; let script = program.astNode; if (script) { + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; debugLog('[BEFORE STRUCT SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true, cachePath); const builderLambdaTransformer = new BuilderLambdaTransformer(); const structTransformer = new StructTransformer(this.getProjectConfig()); @@ -70,12 +73,13 @@ export function uiTransform(): Plugins { state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, visitors: [structTransformer, builderLambdaTransformer], skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, }); program = programVisitor.programVisitor(program); script = program.astNode; debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true, cachePath); arkts.recheckSubtree(script); this.setArkTSAst(script); -- Gitee From 6dfda036b7dcfb9af02539f4189522bc2672a971 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 2 Apr 2025 20:04:59 +0800 Subject: [PATCH 014/123] fix else-if in builder-lambda Signed-off-by: Jiakai Shi Change-Id: I835f7dce4ed22b04274e4cafa9d374a917654e63 --- .../ui-plugins/builder-lambda-transformer.ts | 50 +++++++++++-------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts index be6c04348..16052ac2a 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts @@ -140,6 +140,34 @@ function updateFactoryArgInBuilderLambda( ); } +// TODO: very time-consuming... +function updateIfElseContentBodyInBuilderLambda( + statement: arkts.AstNode, + isExternal?: boolean +): arkts.AstNode { + if (arkts.isIfStatement(statement)) { + const alternate = !!statement.alternate + ? updateIfElseContentBodyInBuilderLambda(statement.alternate, isExternal) + : statement.alternate; + const consequence = updateIfElseContentBodyInBuilderLambda(statement.consequent, isExternal); + return arkts.factory.updateIfStatement( + statement, + statement.test, + consequence!, + alternate + ) + } + if (arkts.isBlockStatement(statement)) { + return arkts.factory.updateBlock( + statement, + statement.statements.map( + (st) => updateContentBodyInBuilderLambda(st, isExternal) + ) + ) + } + return statement; +} + function updateContentBodyInBuilderLambda( statement: arkts.Statement, isExternal?: boolean @@ -154,27 +182,9 @@ function updateContentBodyInBuilderLambda( transformBuilderLambda(statement.expression) ); } + // TODO: very time-consuming... if (arkts.isIfStatement(statement)) { - return arkts.factory.updateIfStatement( - statement, - statement.test, - arkts.isBlockStatement(statement.consequent) - ? arkts.factory.updateBlock( - statement.consequent, - statement.consequent.statements.map( - (st) => updateContentBodyInBuilderLambda(st, isExternal) - ) - ) - : statement.consequent, - !!statement.alternate && arkts.isBlockStatement(statement.alternate) - ? arkts.factory.updateBlock( - statement.alternate, - statement.alternate.statements.map( - (st) => updateContentBodyInBuilderLambda(st, isExternal) - ) - ) - : statement.alternate - ) + return updateIfElseContentBodyInBuilderLambda(statement, isExternal); } return statement; -- Gitee From cd2d0786ac6cc5e1750b48d5899c590bf37236f9 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Wed, 2 Apr 2025 23:29:24 +0800 Subject: [PATCH 015/123] modify head file for resource Signed-off-by: y00896775 Change-Id: I7fa2993192fb25618d7c65142ac6c20384fc1e59 --- arkui-plugins/common/predefines.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index c23026980..6b52253f7 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -28,8 +28,7 @@ export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ ]; export const IMPORT_SOURCE_MAP: Map> = new Map>([ - ["@ohos.arkui.component", new Set(["$r", "$rawfile", "ArkReusableStructBase", "Reusable"])], - ["@ohos.arkui.external", new Set(["_r", "_rawfile"])], + ["@ohos.arkui.component", new Set(["$r", "$rawfile", "ArkReusableStructBase", "Reusable", "_r", "_rawfile"])], ["@ohos.arkui.stateManagement", new Set([ "State", "Prop", @@ -39,14 +38,18 @@ export const IMPORT_SOURCE_MAP: Map> = new Map> = new Map = new Map([ @@ -68,5 +72,9 @@ export const OUTPUT_DEPENDENCY_MAP: Map = new Map Date: Thu, 3 Apr 2025 15:42:24 +0800 Subject: [PATCH 016/123] clear gloabl cache Signed-off-by: y00896775 Change-Id: Ibce4ebae6c684d508ee8e922f5d00677784ec8ca --- arkui-plugins/ui-plugins/index.ts | 1 + koala-wrapper/src/arkts-api/visitor.ts | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index bddf14d3d..f9f5d3f50 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -81,6 +81,7 @@ export function uiTransform(): Plugins { debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true, cachePath); + arkts.GlobalInfo.getInfoInstance().reset(); arkts.recheckSubtree(script); this.setArkTSAst(script); console.log('[UI PLUGIN] AFTER CHECKED EXIT'); diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index 944f5579f..2d62b5a42 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -111,6 +111,11 @@ export class GlobalInfo { public setStructInfo(structName: string, info: StructInfo): void { this._structMap.set(structName, info); } + + public reset(): void { + this._structMap.clear(); + this._structCollection.clear(); + } } // TODO: rethink (remove as) -- Gitee From 7dde05d03f989e2d1f5d78e293df2fadb1d44544 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Thu, 3 Apr 2025 01:23:00 +0800 Subject: [PATCH 017/123] add performance Signed-off-by: Jiakai Shi Change-Id: I880849cd5b51f2cfa583c611f1801ab71dce4f05 --- arkui-plugins/common/debug.ts | 3 + arkui-plugins/memo-plugins/index.ts | 9 ++ arkui-plugins/ui-plugins/index.ts | 14 +++ koala-wrapper/src/arkts-api/index.ts | 1 + .../src/arkts-api/utilities/performance.ts | 105 ++++++++++++++++++ 5 files changed, 132 insertions(+) create mode 100644 koala-wrapper/src/arkts-api/utilities/performance.ts diff --git a/arkui-plugins/common/debug.ts b/arkui-plugins/common/debug.ts index 5f380559a..d01119195 100644 --- a/arkui-plugins/common/debug.ts +++ b/arkui-plugins/common/debug.ts @@ -14,9 +14,12 @@ */ import * as fs from 'fs'; import * as path from 'path'; +import * as arkts from '@koalaui/libarkts'; const isDebugLog: boolean = false; const isDebugDump: boolean = false; +const isPerformance: boolean = false; +arkts.Performance.getInstance().skip(!isPerformance); export function getEnumName(enumType: any, value: number): string | undefined { return enumType[value]; diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index e7d75467c..ea39e87bf 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -36,6 +36,8 @@ export function unmemoizeTransform(): Plugins { const cachePath: string | undefined = this.getProjectConfig()?.cachePath; debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 5, "MEMO_AfterCheck_Begin"), true, cachePath); + arkts.Performance.getInstance().createEvent("memo-checked"); + const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); const parameterTransformer = new ParameterTransformer({ positionalIdTracker }); const returnTransformer = new ReturnTransformer(); @@ -58,10 +60,17 @@ export function unmemoizeTransform(): Plugins { program = programVisitor.programVisitor(program); script = program.astNode; + arkts.Performance.getInstance().stopEvent("memo-checked", true); + debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 6, "MEMO_AfterCheck_End"), true, cachePath); + arkts.Performance.getInstance().createEvent("memo-recheck"); arkts.recheckSubtree(script); + arkts.Performance.getInstance().stopEvent("memo-recheck", true); + + arkts.Performance.getInstance().clearAllEvents(); + this.setArkTSAst(script); console.log("[MEMO PLUGIN] AFTER CHECKED EXIT"); return script; diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index f9f5d3f50..e520ef9fb 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -35,6 +35,8 @@ export function uiTransform(): Plugins { debugLog('[BEFORE PARSED SCRIPT] script: ', script.dumpSrc()); debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true, cachePath); + arkts.Performance.getInstance().createEvent("ui-parsed"); + const componentTransformer = new ComponentTransformer(); const preprocessorTransformer = new PreprocessorTransformer(); const programVisitor = new ProgramVisitor({ @@ -48,6 +50,8 @@ export function uiTransform(): Plugins { program = programVisitor.programVisitor(program); script = program.astNode; + arkts.Performance.getInstance().stopEvent("ui-parsed", true); + debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), true, cachePath); @@ -66,6 +70,8 @@ export function uiTransform(): Plugins { debugLog('[BEFORE STRUCT SCRIPT] script: ', script.dumpSrc()); debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true, cachePath); + arkts.Performance.getInstance().createEvent("ui-checked"); + const builderLambdaTransformer = new BuilderLambdaTransformer(); const structTransformer = new StructTransformer(this.getProjectConfig()); const programVisitor = new ProgramVisitor({ @@ -78,11 +84,19 @@ export function uiTransform(): Plugins { program = programVisitor.programVisitor(program); script = program.astNode; + + arkts.Performance.getInstance().stopEvent("ui-checked", true); + debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true, cachePath); arkts.GlobalInfo.getInfoInstance().reset(); + arkts.Performance.getInstance().createEvent("ui-recheck"); arkts.recheckSubtree(script); + arkts.Performance.getInstance().stopEvent("ui-recheck", true); + + arkts.Performance.getInstance().clearAllEvents(); + this.setArkTSAst(script); console.log('[UI PLUGIN] AFTER CHECKED EXIT'); return script; diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index 7656ff330..5182f38e8 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -60,6 +60,7 @@ export * from "../generated/peers/BlockExpression" export * from "./types" export * from "./utilities/private" export * from "./utilities/public" +export * from "./utilities/performance" export * from "./factory/nodeFactory" export * from "./factory/nodeTests" export * from "./visitor" diff --git a/koala-wrapper/src/arkts-api/utilities/performance.ts b/koala-wrapper/src/arkts-api/utilities/performance.ts new file mode 100644 index 000000000..e6c9290d9 --- /dev/null +++ b/koala-wrapper/src/arkts-api/utilities/performance.ts @@ -0,0 +1,105 @@ +interface Event { + name: string, + startTime: number, + endTime?: number, + parentEvent?: string, + duration?: number +} + +function formatTime(ms: number): string { + const milliseconds = Math.floor(ms % 1000); + const seconds = Math.floor((ms / 1000) % 60); + const minutes = Math.floor((ms / (1000 * 60)) % 60); + const hours = Math.floor(ms / (1000 * 60 * 60)); + + return `${pad(hours, 2)}:${pad(minutes, 2)}:${pad(seconds, 2)}:${pad(milliseconds, 3)}`; +} + +function pad(value: number, length: number): string { + return value.toString().padStart(length, '0'); +} + +export class Performance { + private static instance: Performance; + private events: Map; + private scopes: string[]; + private shouldSkip: boolean; + + private constructor() { + this.events = new Map(); + this.scopes = []; + this.shouldSkip = true; + } + + public static getInstance(): Performance { + if (!this.instance) { + this.instance = new Performance(); + } + return this.instance; + } + + skip(shouldSkip: boolean = true): void { + this.shouldSkip = shouldSkip; + } + + createEvent(name: string): Event { + if (this.shouldSkip) return { name: '', startTime: 0 }; + const startTime: number = performance.now(); + const newEvent: Event = { name, startTime }; + this.events.set(name, newEvent); + this.scopes.push(name); + return newEvent; + } + + stopEvent(name: string, shouldLog: boolean = false): Event { + if (this.shouldSkip) return { name: '', startTime: 0 }; + if (!this.events.has(name) || this.scopes.length === 0) { + throw new Error(`Event ${name} is not created.`); + } + if (this.scopes[this.scopes.length - 1] !== name) { + console.warn(`[PERFORMANCE WARNING] Event ${name} early exit.`); + } + this.scopes.pop(); + + const event: Event = this.events.get(name)!; + const endTime: number = performance.now(); + const parentEvent: string = this.scopes[this.scopes.length - 1]; + const duration: number = endTime - event.startTime; + + if (shouldLog) { + console.log(`[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}`); + } + + return { ...event, endTime, parentEvent, duration }; + } + + stopLastEvent(shouldLog: boolean = false): Event { + if (this.shouldSkip) return { name: '', startTime: 0 }; + if (this.scopes.length === 0) { + throw new Error("No last event"); + } + const name: string = this.scopes.pop()!; + if (!this.events.has(name)) { + throw new Error(`Event ${name} is not created.`); + } + + const event: Event = this.events.get(name)!; + const endTime: number = performance.now(); + const parentEvent: string = this.scopes[this.scopes.length - 1]; + const duration: number = endTime - event.startTime; + + if (shouldLog) { + console.log(`[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}`); + } + + return { ...event, endTime, parentEvent, duration }; + } + + clearAllEvents(shouldLog: boolean = false): void { + if (this.shouldSkip) return; + for (let i = 0; i < this.scopes.length; i ++) { + this.stopLastEvent(shouldLog); + } + this.events = new Map(); + } +} \ No newline at end of file -- Gitee From 2799c3d014a5a96d13b74b8b89f52f415e1cdd66 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Thu, 3 Apr 2025 13:55:42 +0800 Subject: [PATCH 018/123] add total duration count Signed-off-by: Jiakai Shi Change-Id: I59f71fc129ba06161c30e0212320fdc8a4f2f46b --- .../src/arkts-api/utilities/performance.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/koala-wrapper/src/arkts-api/utilities/performance.ts b/koala-wrapper/src/arkts-api/utilities/performance.ts index e6c9290d9..813a244f1 100644 --- a/koala-wrapper/src/arkts-api/utilities/performance.ts +++ b/koala-wrapper/src/arkts-api/utilities/performance.ts @@ -24,11 +24,13 @@ export class Performance { private events: Map; private scopes: string[]; private shouldSkip: boolean; + private totalDuration: number; private constructor() { this.events = new Map(); this.scopes = []; this.shouldSkip = true; + this.totalDuration = 0; } public static getInstance(): Performance { @@ -65,9 +67,12 @@ export class Performance { const endTime: number = performance.now(); const parentEvent: string = this.scopes[this.scopes.length - 1]; const duration: number = endTime - event.startTime; + this.totalDuration += duration; if (shouldLog) { - console.log(`[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}`); + console.log( + `[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}, total: ${formatTime(this.totalDuration)}` + ); } return { ...event, endTime, parentEvent, duration }; @@ -87,9 +92,12 @@ export class Performance { const endTime: number = performance.now(); const parentEvent: string = this.scopes[this.scopes.length - 1]; const duration: number = endTime - event.startTime; + this.totalDuration += duration; if (shouldLog) { - console.log(`[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}`); + console.log( + `[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}, total: ${formatTime(this.totalDuration)}` + ); } return { ...event, endTime, parentEvent, duration }; @@ -102,4 +110,8 @@ export class Performance { } this.events = new Map(); } + + clearTotalDuration(): void { + this.totalDuration = 0; + } } \ No newline at end of file -- Gitee From c7d84b903fa8f4a06562d3089b86317a34c1f451 Mon Sep 17 00:00:00 2001 From: wuhailong Date: Thu, 20 Feb 2025 16:59:58 +0800 Subject: [PATCH 019/123] adapt arkts evolution Issue: #IBTQ0B Signed-off-by: wuhailong Change-Id: I37e1a651757203edc4a1c6a9e91e55178470933c --- compiler/package.json | 2 + compiler/src/ark_utils.ts | 64 ++++++++- compiler/src/ets_checker.ts | 51 ++++++++ .../ark_compiler/module/module_mode.ts | 29 ++++- .../ark_compiler/module/module_source_file.ts | 5 +- .../ets_ui/rollup-plugin-ets-checker.ts | 23 +++- compiler/src/pre_define.ts | 4 +- compiler/src/process_module_files.ts | 7 +- .../test/ark_compiler_ut/ets_checker.test.ts | 123 +++++++++++++++++- .../mock/rollup_mock/common.ts | 5 +- .../mock/rollup_mock/project_config.ts | 21 ++- .../module/ohmUrl/ohmUrl.test.ts | 41 +++++- .../utils/processProjectConfig.ts | 1 + 13 files changed, 356 insertions(+), 20 deletions(-) diff --git a/compiler/package.json b/compiler/package.json index c9ebc37e3..bee0baf64 100644 --- a/compiler/package.json +++ b/compiler/package.json @@ -37,11 +37,13 @@ "@babel/preset-env": "7.20.2", "@babel/preset-typescript": "7.18.6", "@babel/runtime": "7.20.13", + "@types/proxyquire": "^1.3.31", "@typescript-eslint/parser": "5.51.0", "babel-loader": "9.1.2", "chai": "4.3.7", "eslint": "8.34.0", "mocha": "10.2.0", + "proxyquire": "^2.1.3", "uglify-js": "3.17.4" }, "dependencies": { diff --git a/compiler/src/ark_utils.ts b/compiler/src/ark_utils.ts index 70674432f..ff3c41efb 100644 --- a/compiler/src/ark_utils.ts +++ b/compiler/src/ark_utils.ts @@ -48,6 +48,7 @@ import { EXTNAME_CJS, EXTNAME_ABC, EXTNAME_ETS, + EXTNAME_D_ETS, EXTNAME_TS_MAP, EXTNAME_JS_MAP, ESMODULE, @@ -103,11 +104,36 @@ export const SRC_MAIN: string = 'src/main'; export let newSourceMaps: Object = {}; +interface DeclFileConfig { + declPath: string; + ohmUrl: string; +} + +interface DeclFilesConfig { + packageName: string; + files: { + [filePath: string]: DeclFileConfig; + } +} + +export interface ArkTsEvolutionModule { + language: string; // "1.1" | "1.2" + pkgName: string; + moduleName: string; + modulePath: string; + declgenV1OutPath?: string; + declgenV2OutPath?: string; + declgenBridgeCodePath?: string; + declFilesPath?: string; +} + +export let pkgDeclFilesConfig: { [pkgName: string]: DeclFilesConfig } = {} + export const packageCollection: Map> = new Map(); // Splicing ohmurl or record name based on filePath and context information table. export function getNormalizedOhmUrlByFilepath(filePath: string, projectConfig: Object, logger: Object, pkgParams: Object, importerFile: string): string { - const { pkgName, pkgPath, isRecordName } = pkgParams; + const { pkgName, moduleName, pkgPath, isRecordName, isArkTsEvolution } = pkgParams; // rollup uses commonjs plugin to handle commonjs files, // the commonjs files are prefixed with '\x00' and need to be removed. if (filePath.startsWith('\x00')) { @@ -123,6 +149,7 @@ export function getNormalizedOhmUrlByFilepath(filePath: string, projectConfig: O // case6: /library/index.ts // ---> @normalized:N&&&/entry/ets/xxx/yyy& let pkgInfo = projectConfig.pkgContextInfo[pkgName]; + let arkTsEvolutionModuleInfo = projectConfig.dependentModuleMap.get(moduleName); if (!pkgInfo || !pkgPath) { const errInfo: LogData = LogDataFactory.newInstance( ErrorCode.ETS2BUNDLE_EXTERNAL_FAILED_TO_RESOLVE_OHM_URL, @@ -136,15 +163,45 @@ export function getNormalizedOhmUrlByFilepath(filePath: string, projectConfig: O logger.printError(errInfo); return filePath; } - let projectFilePath: string = unixFilePath.replace(toUnixPath(pkgPath), ''); - let recordName = `${pkgInfo.bundleName}&${pkgName}${projectFilePath}&${pkgInfo.version}`; + let declgenBridgeCodePath: string; + let declgenV2OutPath: string; + let isNeedGenerateDeclFilesConfig: boolean = false; + if (isArkTsEvolution && arkTsEvolutionModuleInfo && arkTsEvolutionModuleInfo.declgenBridgeCodePath) { + declgenBridgeCodePath = toUnixPath(arkTsEvolutionModuleInfo.declgenBridgeCodePath); + } + if (!isArkTsEvolution && arkTsEvolutionModuleInfo && arkTsEvolutionModuleInfo.declgenV2OutPath) { + declgenV2OutPath = toUnixPath(arkTsEvolutionModuleInfo.declgenV2OutPath); + isNeedGenerateDeclFilesConfig = true; + } + let projectFilePath: string = declgenBridgeCodePath && unixFilePath.startsWith(declgenBridgeCodePath + '/') ? + unixFilePath.replace(toUnixPath(path.join(declgenBridgeCodePath, moduleName)) + '/', '') : + unixFilePath.replace(toUnixPath(pkgPath) + '/', ''); + const recordName: string = `${pkgInfo.bundleName}&${pkgName}/${projectFilePath}&${pkgInfo.version}`; if (isRecordName) { // record name style: &/entry/ets/xxx/yyy& + if (isNeedGenerateDeclFilesConfig) { + if (!pkgDeclFilesConfig[pkgName]) { + pkgDeclFilesConfig[pkgName] = { packageName: pkgName, files: {}} + } + const packageInfo = getPackageInfo(projectConfig.aceModuleJsonPath); + const ohmUrl: string = `${pkgInfo.isSO ? 'Y' : 'N'}&${moduleName}&${packageInfo[0]}&${pkgName}/${projectFilePath}&${pkgInfo.version}`; + const declFileInfo: Object = { projectFilePath, declgenV2OutPath, ohmUrl: `@normalized:${ohmUrl}` }; + addDeclFilesConfig(pkgDeclFilesConfig[pkgName], declFileInfo); + } return recordName; } return `${pkgInfo.isSO ? 'Y' : 'N'}&${pkgInfo.moduleName}&${recordName}`; } +function addDeclFilesConfig(declFilesConfig: DeclFilesConfig, declFileInfo: Object): void { + const { projectFilePath, declgenV2OutPath, ohmUrl } = declFileInfo; + if (declFilesConfig.files[projectFilePath]) { + return; + } + const declPath: string = path.join(declgenV2OutPath, projectFilePath) + EXTNAME_D_ETS; + declFilesConfig.files[projectFilePath] = { declPath, ohmUrl } +} + export function getOhmUrlByFilepath(filePath: string, projectConfig: Object, logger: Object, namespace?: string, importerFile?: string): string { // remove '\x00' from the rollup virtual commonjs file's filePath @@ -953,6 +1010,7 @@ export function cleanUpUtilsObjects(): void { newSourceMaps = {}; nameCacheMap.clear(); packageCollection.clear(); + pkgDeclFilesConfig = {}; } export function getHookEventFactory(share: Object, pluginName: string, hookName: string): Object { diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index fe10ad0e3..9e4ce761e 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -46,6 +46,7 @@ import { ESMODULE, EXTNAME_D_ETS, EXTNAME_JS, + EXTNAME_ETS, FOREACH_LAZYFOREACH, COMPONENT_IF, TS_WATCH_END_MSG, @@ -107,6 +108,7 @@ import { RunnerParms, generateInteropDecls } from '../node_modules/declgen/build/src/generateInteropDecls' +import { ArkTsEvolutionModule } from './ark_utils'; export interface LanguageServiceCache { service?: ts.LanguageService; @@ -123,6 +125,8 @@ export const TSC_SYSTEM_CODE = '105'; export const MAX_FLOW_DEPTH_DEFAULT_VALUE = 2000; export const MAX_FLOW_DEPTH_MAXIMUM_VALUE = 65535; +export let arkTsEvolutionModuleMap: Map = new Map(); + export function readDeaclareFiles(): string[] { const declarationsFileNames: string[] = []; fs.readdirSync(path.resolve(__dirname, '../declarations')) @@ -1080,6 +1084,29 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string } else { resolvedModules.push(result.resolvedModule); } + } else if (result.resolvedModule.resolvedFileName && /\.ets$/.test(result.resolvedModule.resolvedFileName) && + !/\.d\.ets$/.test(result.resolvedModule.resolvedFileName) && arkTsEvolutionModuleMap.size !== 0) { + // When result has a value and the path parsed is the source code file path of module 1.2, + // the parsing result needs to be modified to the glue code path of module 1.2 + let staticDeclFileExist: boolean = false; + const resolvedFileName: string = toUnixPath(result.resolvedModule.resolvedFileName); + for (const [pkgName, arkTsEvolutionModuleInfo] of arkTsEvolutionModuleMap) { + const modulePath: string = toUnixPath(arkTsEvolutionModuleInfo.modulePath); + const declgenV1OutPath: string = toUnixPath(arkTsEvolutionModuleInfo.declgenV1OutPath); + const declgenBridgeCodePath: string = toUnixPath(arkTsEvolutionModuleInfo.declgenBridgeCodePath); + if (resolvedFileName.startsWith(modulePath + '/') && !resolvedFileName.startsWith(declgenBridgeCodePath + '/')) { + const resultDETSPath: string = + resolvedFileName.replace(modulePath, toUnixPath(path.join(declgenV1OutPath, pkgName))).replace(EXTNAME_ETS, EXTNAME_D_ETS); + if (ts.sys.fileExists(resultDETSPath)) { + resolvedModules.push(getResolveModule(resultDETSPath, EXTNAME_D_ETS)); + staticDeclFileExist = true; + break; + } + } + } + if (!staticDeclFileExist) { + resolvedModules.push(result.resolvedModule); + } } else { resolvedModules.push(result.resolvedModule); } @@ -1124,6 +1151,7 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string path.resolve(__dirname, '../node_modules', moduleName + '/index.js'); const DETSModulePath: string = path.resolve(path.dirname(containingFile), /\.d\.ets$/.test(moduleName) ? moduleName : moduleName + EXTNAME_D_ETS); + const arktsEvoDeclFilePath: string = getArktsEvoDeclFilePath(moduleName); if (ts.sys.fileExists(modulePath)) { resolvedModules.push(getResolveModule(modulePath, '.d.ts')); } else if (ts.sys.fileExists(systemDETSModulePath)) { @@ -1138,6 +1166,8 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string resolvedModules.push(getResolveModule(fileModulePath, '.js')); } else if (ts.sys.fileExists(DETSModulePath)) { resolvedModules.push(getResolveModule(DETSModulePath, '.d.ets')); + } else if (ts.sys.fileExists(arktsEvoDeclFilePath)) { + resolvedModules.push(getResolveModule(arktsEvoDeclFilePath, '.d.ets')); } else { const srcIndex: number = projectConfig.projectPath.indexOf('src' + path.sep + 'main'); let DETSModulePathFromModule: string; @@ -1173,6 +1203,26 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string return resolvedModulesCache.get(path.resolve(containingFile)); } +function getArktsEvoDeclFilePath(moduleRequest: string): string { + let staticDeclFilePath: string = moduleRequest; + for (const [moduleName, arkTsEvolutionModuleInfo] of arkTsEvolutionModuleMap) { + const declgenV1OutPath: string = toUnixPath(arkTsEvolutionModuleInfo.declgenV1OutPath); + if (moduleRequest === moduleName) { + staticDeclFilePath = path.join(declgenV1OutPath, moduleName, 'Index.d.ets'); + break; + } else if (moduleRequest.startsWith(moduleName + '/')) { + staticDeclFilePath = + moduleRequest.replace(moduleName, toUnixPath(path.join(declgenV1OutPath, moduleName, 'src/main/ets'))) + EXTNAME_D_ETS; + break; + } + } + return staticDeclFilePath; +} + +export function cleanUpArkTsEvolutionModuleMap(): void { + arkTsEvolutionModuleMap = new Map(); +} + export interface ResolveModuleInfo { modulePath: string; isEts: boolean; @@ -1817,6 +1867,7 @@ export function resetEtsCheck(): void { dirExistsCache.clear(); targetESVersionChanged = false; fileToIgnoreDiagnostics = undefined; + cleanUpArkTsEvolutionModuleMap(); } export function generateDeclarationFileForSTS(rootFileNames: string[]) { diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts index e0753f1f4..582150086 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_mode.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -92,13 +92,16 @@ import { createAndStartEvent, stopEvent, transformOhmurlToPkgName, - transformOhmurlToRecordName + transformOhmurlToRecordName, + ArkTsEvolutionModule, + pkgDeclFilesConfig } from '../../../ark_utils'; import { generateAot, FaultHandler } from '../../../gen_aot'; import { + ARK_TS_1_2, NATIVE_MODULE } from '../../../pre_define'; import { @@ -244,8 +247,10 @@ export class ModuleMode extends CommonMode { } const pkgParams = { pkgName: metaInfo.pkgName, + moduleName: metaInfo.moduleName, pkgPath: metaInfo.pkgPath, - isRecordName: true + isRecordName: true, + isArkTsEvolution: metaInfo.language === ARK_TS_1_2 }; let recordName: string = getNormalizedOhmUrlByFilepath(moduleId, this.projectConfig, this.logger, pkgParams, undefined); @@ -301,10 +306,24 @@ export class ModuleMode extends CommonMode { prepareForCompilation(rollupObject: Object, parentEvent: Object): void { const eventPrepareForCompilation = createAndStartEvent(parentEvent, 'preparation for compilation'); this.collectModuleFileList(rollupObject, rollupObject.getModuleIds()); + this.writeDeclFilesConfigJson(rollupObject.share.projectConfig.dependentModuleMap); this.removeCacheInfo(rollupObject); stopEvent(eventPrepareForCompilation); } + // Write the declaration file information of the 1.1 module file to the disk of the corresponding module + writeDeclFilesConfigJson(dependentModuleMap: Map): void { + for (const pkgName in pkgDeclFilesConfig) { + const arkTsEvolutionModuleInfo = dependentModuleMap.get(pkgName); + if (!arkTsEvolutionModuleInfo?.declFilesPath) { + return; + } + const declFilesConfigFile: string = toUnixPath(arkTsEvolutionModuleInfo.declFilesPath); + mkdirsSync(path.dirname(declFilesConfigFile)); + fs.writeFileSync(declFilesConfigFile, JSON.stringify(pkgDeclFilesConfig[pkgName], null, 2), 'utf-8'); + } + } + collectModuleFileList(module: Object, fileList: IterableIterator): void { const recordInfo = MemoryMonitor.recordStage(MemoryDefine.PKG_ENTRY_INFOS_MODULE_INFOS); let moduleInfos: Map = new Map(); @@ -494,7 +513,7 @@ export class ModuleMode extends CommonMode { let moduleName: string = metaInfo.moduleName; let recordName: string = ''; - let cacheFilePath: string = + let cacheFilePath: string = metaInfo.language === ARK_TS_1_2 ? originalFilePath : this.genFileCachePath(filePath, this.projectConfig.projectRootPath, this.projectConfig.cachePath, metaInfo); let packageName: string = ''; @@ -502,8 +521,10 @@ export class ModuleMode extends CommonMode { packageName = metaInfo.pkgName; const pkgParams = { pkgName: packageName, + moduleName: metaInfo.moduleName, pkgPath: metaInfo.pkgPath, - isRecordName: true + isRecordName: true, + isArkTsEvolution: metaInfo.language === ARK_TS_1_2 }; recordName = getNormalizedOhmUrlByFilepath(filePath, this.projectConfig, this.logger, pkgParams, undefined); } else { diff --git a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts index c6b75a9d6..407761880 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts @@ -52,6 +52,7 @@ import { } from '../common/ob_config_resolver'; import { ORIGIN_EXTENTION } from '../process_mock'; import { + ARK_TS_1_2, TRANSFORMED_MOCK_CONFIG, USER_DEFINE_MOCK_CONFIG } from '../../../pre_define'; @@ -495,8 +496,10 @@ export class ModuleSourceFile { private static spliceNormalizedOhmurl(moduleInfo: Object, filePath: string, importerFile?: string): string { const pkgParams = { pkgName: moduleInfo.meta.pkgName, + moduleName: moduleInfo.meta.moduleName, pkgPath: moduleInfo.meta.pkgPath, - isRecordName: false + isRecordName: false, + isArkTsEvolution: moduleInfo.meta.language === ARK_TS_1_2 }; const ohmUrl: string = getNormalizedOhmUrlByFilepath(filePath, ModuleSourceFile.projectConfig, ModuleSourceFile.logger, pkgParams, diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts index c17bb5c78..b0583dc4c 100644 --- a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts @@ -30,14 +30,19 @@ import { runArkTSLinter, targetESVersionChanged, collectFileToIgnoreDiagnostics, - TSC_SYSTEM_CODE + TSC_SYSTEM_CODE, + arkTsEvolutionModuleMap, + cleanUpArkTsEvolutionModuleMap, } from '../../ets_checker'; -import { TS_WATCH_END_MSG } from '../../pre_define'; +import { + ARK_TS_1_2, + TS_WATCH_END_MSG +} from '../../pre_define'; import { setChecker, startTimeStatisticsLocation, stopTimeStatisticsLocation, - CompilationTimeStatistics + CompilationTimeStatistics, } from '../../utils'; import { configureSyscapInfo, @@ -47,6 +52,7 @@ import { MemoryMonitor } from '../meomry_monitor/rollup-plugin-memory-monitor'; import { MemoryDefine } from '../meomry_monitor/memory_define'; import { LINTER_SUBSYSTEM_CODE } from '../../hvigor_error_code/hvigor_error_info'; import { ErrorCodeModule } from '../../hvigor_error_code/const/error_code_module'; +import { ArkTsEvolutionModule } from '../../ark_utils'; export let tsWatchEmitter: EventEmitter | undefined = undefined; export let tsWatchEndPromise: Promise; @@ -57,6 +63,9 @@ export function etsChecker() { name: 'etsChecker', buildStart() { const recordInfo = MemoryMonitor.recordStage(MemoryDefine.ROLLUP_PLUGIN_BUILD_START); + if (this.share.projectConfig.dependentModuleMap) { + collectArkTSEvolutionModuleInfo(this.share.projectConfig.dependentModuleMap); + } const compilationTime: CompilationTimeStatistics = new CompilationTimeStatistics(this.share, 'etsChecker', 'buildStart'); if (process.env.watchMode === 'true' && process.env.triggerTsWatch === 'true') { tsWatchEmitter = new EventEmitter(); @@ -155,3 +164,11 @@ function rootFileNamesCollect(rootFileNames: string[]): void { rootFileNames.push(path.resolve(fileName)); }); } + +function collectArkTSEvolutionModuleInfo(dependentModuleMap: Map): void { + for (const [moduleName, arkTsEvolutionModuleInfo] of dependentModuleMap) { + if (arkTsEvolutionModuleInfo?.declgenV1OutPath && arkTsEvolutionModuleInfo.language === ARK_TS_1_2) { + arkTsEvolutionModuleMap.set(moduleName, arkTsEvolutionModuleInfo); + } + } +} \ No newline at end of file diff --git a/compiler/src/pre_define.ts b/compiler/src/pre_define.ts index b3d1a940d..23f1a548a 100644 --- a/compiler/src/pre_define.ts +++ b/compiler/src/pre_define.ts @@ -644,4 +644,6 @@ export const USE_SHARED_STORAGE: string = 'useSharedStorage'; export const ARKTS_MODULE_PREFIX: string = '@arkts'; export const ARKTS_MODULE_NAME: string = 'arkts'; export const COLD_RELOAD_MODE: string = 'coldReload'; -export const INTEGRATED_HSP: string = 'integratedHsp'; \ No newline at end of file +export const INTEGRATED_HSP: string = 'integratedHsp'; + +export const ARK_TS_1_2: string = '1.2'; diff --git a/compiler/src/process_module_files.ts b/compiler/src/process_module_files.ts index b016860f5..fe1079a2b 100644 --- a/compiler/src/process_module_files.ts +++ b/compiler/src/process_module_files.ts @@ -21,6 +21,7 @@ import { SourceMapGenerator } from './fast_build/ark_compiler/generate_sourcemap import { EXTNAME_TS, EXTNAME_ETS, + ARK_TS_1_2 } from './pre_define'; import { genTemporaryPath, @@ -59,7 +60,9 @@ export async function writeFileSyncByNode(node: ts.SourceFile, projectConfig: Ob * Note: current realization is related to the moduleId mechanism in the rollup framework, which is needed to be reconsidered to improve the code robustness. * In the current realization, when moduleId mechanism is changed, there would be a compilation error. */ - let temporaryFile: string = genTemporaryPath(moduleId ? moduleId : node.fileName, projectConfig.projectPath, process.env.cachePath, + let filePath: string = moduleId ? moduleId : node.fileName; + // When the file is glue code for a ArkTS1.2 module, use the path to the glue code. + let temporaryFile: string = metaInfo.language === ARK_TS_1_2 ? filePath : genTemporaryPath(filePath, projectConfig.projectPath, process.env.cachePath, projectConfig, metaInfo); if (temporaryFile.length === 0) { return; @@ -67,7 +70,7 @@ export async function writeFileSyncByNode(node: ts.SourceFile, projectConfig: Ob if (temporaryFile.endsWith(EXTNAME_ETS)) { temporaryFile = temporaryFile.replace(/\.ets$/, EXTNAME_TS); } - let relativeFilePath = getRelativeSourcePath(moduleId ? moduleId : node.fileName, projectConfig.projectRootPath, metaInfo?.belongProjectPath); + let relativeFilePath = getRelativeSourcePath(filePath, projectConfig.projectRootPath, metaInfo?.belongProjectPath); let sourceMaps: Object; if (process.env.compileTool === 'rollup') { const key = sourceMapGenerator.isNewSourceMaps() ? moduleId! : relativeFilePath; diff --git a/compiler/test/ark_compiler_ut/ets_checker.test.ts b/compiler/test/ark_compiler_ut/ets_checker.test.ts index d76aadf11..65583b0b4 100644 --- a/compiler/test/ark_compiler_ut/ets_checker.test.ts +++ b/compiler/test/ark_compiler_ut/ets_checker.test.ts @@ -18,8 +18,15 @@ import fs from 'fs'; import path from 'path'; import { expect } from 'chai'; import * as ts from 'typescript'; +import sinon from 'sinon'; +import proxyquire from 'proxyquire'; -import { EXPECT_INDEX_ETS } from './mock/rollup_mock/path_config'; +import { + DEFAULT_ENTRY, + DEFAULT_PROJECT, + EXPECT_INDEX_ETS, + PROJECT_ROOT +} from './mock/rollup_mock/path_config'; import RollUpPluginMock from './mock/rollup_mock/rollup_plugin_mock'; import { addLocalPackageSet, @@ -30,12 +37,16 @@ import { serviceChecker, getMaxFlowDepth, MAX_FLOW_DEPTH_DEFAULT_VALUE + resolveModuleNames as resolveModuleNamesMain, + arkTsEvolutionModuleMap, + cleanUpArkTsEvolutionModuleMap } from '../../lib/ets_checker'; import { TS_BUILD_INFO_SUFFIX } from '../../lib/pre_define'; import { globalProgram, projectConfig } from '../../main'; +import { mkdirsSync } from '../../lib/utils'; mocha.describe('test ets_checker file api', function () { mocha.before(function () { @@ -187,6 +198,116 @@ mocha.describe('test ets_checker file api', function () { let program: ts.Program = ts.createProgram(fileNames, compilerOptions); expect(program.getEmitHost()).to.not.be.undefined; }); + + mocha.it('2-1: test resolveModuleNames parse 1.2 module declaration files', function () { + const code: string = 'import { a } from "har";\nconsole.log(a);\n'; + const moduleNames: string[] = [ + 'har', + 'har/test' + ]; + arkTsEvolutionModuleMap.set('har', { + language: '1.2', + packageName: 'har', + moduleName: 'har', + modulePath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/har`, + declgenV1OutPath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/har/build/default/intermediates/declgen/default/declgenV1`, + declgenBridgeCodePath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/har/build/default/intermediates/declgen/default/bridgecode` + }) + const filePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/${DEFAULT_ENTRY}/src/main/entryability/test.ets`; + const arktsEvoIndexDeclFilePath: string = `${arkTsEvolutionModuleMap.get('har').declgenV1OutPath}/har/Index.d.ets`; + const arktsEvoTestDeclFilePath: string = `${arkTsEvolutionModuleMap.get('har').declgenV1OutPath}/har/src/main/ets/test.d.ets`; + fs.writeFileSync(filePath, code); + mkdirsSync(path.dirname(arktsEvoIndexDeclFilePath)); + mkdirsSync(path.dirname(arktsEvoTestDeclFilePath)); + fs.writeFileSync(arktsEvoIndexDeclFilePath, ''); + fs.writeFileSync(arktsEvoTestDeclFilePath, ''); + const resolvedModules = resolveModuleNamesMain(moduleNames, filePath); + expect(resolvedModules[0].resolvedFileName === arktsEvoIndexDeclFilePath).to.be.true; + expect(resolvedModules[1].resolvedFileName === arktsEvoTestDeclFilePath).to.be.true; + fs.unlinkSync(filePath); + fs.unlinkSync(arktsEvoIndexDeclFilePath); + fs.unlinkSync(arktsEvoTestDeclFilePath); + cleanUpArkTsEvolutionModuleMap(); + }); + + mocha.it('2-2: test resolveModuleNames parse the 1.2 module declaration file that the 1.1 module depends on (packageName)', function () { + const moduleNames: string[] = ['testhar']; + arkTsEvolutionModuleMap.set('har', { + language: '1.2', + packageName: 'testhar', + moduleName: 'testhar', + modulePath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar`, + declgenV1OutPath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/build/default/intermediates/declgen/default/declgenV1`, + declgenBridgeCodePath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/build/default/intermediates/declgen/default/bridgecode` + }) + const filePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/${DEFAULT_ENTRY}/src/main/entryability/test.ets`; + const arktsEvoIndexFilePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/Index.ets`; + const arktsEvoIndexDeclFilePath: string = `${arkTsEvolutionModuleMap.get('har').declgenV1OutPath}/testhar/Index.d.ets`; + const resolveModuleNameStub = sinon.stub(ts, 'resolveModuleName').returns({ + resolvedModule: { + resolvedFileName: arktsEvoIndexFilePath, + extension: '.ets', + isExternalLibraryImport: false, + } + }); + const mockedTs = { + ...require('typescript'), + resolveModuleName: resolveModuleNameStub + }; + let resolveModuleNames; + ({ resolveModuleNames } = proxyquire('../../lib/ets_checker', { + 'typescript': mockedTs + })); + fs.writeFileSync(filePath, ''); + mkdirsSync(path.dirname(arktsEvoIndexFilePath)); + mkdirsSync(path.dirname(arktsEvoIndexDeclFilePath)); + fs.writeFileSync(arktsEvoIndexFilePath, ''); + fs.writeFileSync(arktsEvoIndexDeclFilePath, ''); + const resolvedModules = resolveModuleNames(moduleNames, filePath); + expect(resolvedModules[0].resolvedFileName === arktsEvoIndexDeclFilePath); + fs.unlinkSync(filePath); + fs.unlinkSync(arktsEvoIndexDeclFilePath); + resolveModuleNameStub.restore(); + }); + + mocha.it('2-3: test resolveModuleNames parse the 1.2 module declaration file that the 1.1 module depends on', function () { + const moduleNames: string[] = ['testhar/src/main/ets/test']; + arkTsEvolutionModuleMap.set('har', { + language: '1.2', + packageName: 'testhar', + moduleName: 'testhar', + modulePath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar`, + declgenV1OutPath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/build/default/intermediates/declgen/default/declgenV1`, + declgenBridgeCodePath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/build/default/intermediates/declgen/default/bridgecode` + }) + const filePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/${DEFAULT_ENTRY}/src/main/entryability/test.ets`; + const arktsEvoTestFilePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/src/main/ets/test.ets`; + const arktsEvoTestDeclFilePath: string = `${arkTsEvolutionModuleMap.get('har').declgenV1OutPath}/testhar/src/main/ets/test.d.ets`; + const resolveModuleNameStub = sinon.stub(ts, 'resolveModuleName').returns({ + resolvedModule: { + resolvedFileName: arktsEvoTestFilePath, + extension: '.ets', + isExternalLibraryImport: false, + } + }); + const mockedTs = { + ...require('typescript'), + resolveModuleName: resolveModuleNameStub + }; + let resolveModuleNames; + ({ resolveModuleNames } = proxyquire('../../lib/ets_checker', { 'typescript': mockedTs })); + + fs.writeFileSync(filePath, ''); + mkdirsSync(path.dirname(arktsEvoTestFilePath)); + mkdirsSync(path.dirname(arktsEvoTestDeclFilePath)); + fs.writeFileSync(arktsEvoTestFilePath, ''); + fs.writeFileSync(arktsEvoTestDeclFilePath, ''); + const resolvedModules = resolveModuleNames(moduleNames, filePath); + expect(resolvedModules[0].resolvedFileName === arktsEvoTestDeclFilePath); + fs.unlinkSync(filePath); + fs.unlinkSync(arktsEvoTestDeclFilePath); + resolveModuleNameStub.restore(); + }); }); mocha.describe('getMaxFlowDepth', () => { diff --git a/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts b/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts index 1feceb88e..aa0c7c34e 100644 --- a/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts +++ b/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts @@ -79,4 +79,7 @@ export const LOADER_AOTMODE: string = 'loader_aotMode.json'; export const UPDATESOURCEMAP: string = 'updateSourceMap.json'; export const ENTRYABILITY_JS: string = 'entry/src/main/entryability/EntryAbility.js'; export const TEST: string = 'test'; -export const NEWFILE: string = 'newFile'; \ No newline at end of file +export const NEWFILE: string = 'newFile'; + +export const DECLFILESPATH: string = '/entry/build/default/intermediates/loader_out/default/etsFortgz/decl-fileInfo.json'; +export const DECLGENV2OUTPATH: string = '/entry/build/default/intermediates/declgen/default/declgenV2'; \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/mock/rollup_mock/project_config.ts b/compiler/test/ark_compiler_ut/mock/rollup_mock/project_config.ts index 90fe1b8e2..243038c36 100644 --- a/compiler/test/ark_compiler_ut/mock/rollup_mock/project_config.ts +++ b/compiler/test/ark_compiler_ut/mock/rollup_mock/project_config.ts @@ -30,14 +30,16 @@ import { NODE_JS_PATH, PORT_DEFAULT, ENTRY_MODULE_VERSION_DEFAULT, - SDK_VERSION_STAGE + SDK_VERSION_STAGE, + DECLFILESPATH, + DECLGENV2OUTPATH } from "./common"; import { ESMODULE, OHPM, RELEASE } from "../../../../lib/fast_build/ark_compiler/common/ark_define"; -import EntryAbility from "../../testdata/expect/expect_EntryAbility"; +import { ArkTsEvolutionModule } from "../../../../lib/ark_utils"; interface IArkProjectConfig { projectRootPath: string, @@ -131,6 +133,7 @@ class ProjectConfig { widgetCompile: boolean; arkRouterMap: Array; declarationEntry: Array; + dependentModuleMap: Map; constructor(buildMode: string) { this.watchMode = 'false'; @@ -145,10 +148,12 @@ class ProjectConfig { this.hspNameOhmMap = {}; this.arkRouterMap = []; this.declarationEntry = []; + this.dependentModuleMap = new Map(); } public scan(testcase: string) { this.initPath(`${PROJECT_ROOT}/${testcase}`); + this.setDependentModuleMap(); } public setPreview(isPreview: boolean) { @@ -261,6 +266,18 @@ class ProjectConfig { this.port = PORT_DEFAULT; this.aceSoPath = `${this.projectTopDir}/entry/preview/cache/nativeDependencies.txt`; } + + private setDependentModuleMap() { + const arkTsEvolutionModuleInfo = { + language: '1.1', + pkgName: this.entryModuleName, + moduleName: this.entryModuleName, + modulePath: this.modulePath, + declgenV2OutPath: DECLGENV2OUTPATH, + declFilesPath: DECLFILESPATH + } + this.dependentModuleMap.set(this.entryModuleName, arkTsEvolutionModuleInfo) + } } export { ProjectConfig, IArkProjectConfig } diff --git a/compiler/test/ark_compiler_ut/module/ohmUrl/ohmUrl.test.ts b/compiler/test/ark_compiler_ut/module/ohmUrl/ohmUrl.test.ts index 7f09e32a6..2c3b21542 100644 --- a/compiler/test/ark_compiler_ut/module/ohmUrl/ohmUrl.test.ts +++ b/compiler/test/ark_compiler_ut/module/ohmUrl/ohmUrl.test.ts @@ -22,7 +22,8 @@ import { getOhmUrlByExternalPackage, getOhmUrlBySystemApiOrLibRequest, getNormalizedOhmUrlByFilepath, - getNormalizedOhmUrlByAliasName + getNormalizedOhmUrlByAliasName, + pkgDeclFilesConfig } from '../../../../lib/ark_utils'; import { PACKAGES } from '../../../../lib/pre_define'; import projectConfig from '../../utils/processProjectConfig'; @@ -40,6 +41,10 @@ import { LogData, LogDataFactory } from '../../../../lib/fast_build/ark_compiler/logger'; +import { + DECLGENV2OUTPATH, + INDEX_SOURCE_PATH +} from '../../mock/rollup_mock/common'; const PRVIEW_MOCK_CONFIG : Object = { // system api mock @@ -963,7 +968,6 @@ mocha.describe('generate ohmUrl', function () { 'json5': undefined }; const filePath: string = `${projectConfig.projectRootPath}/entry/oh_modules/json5/dist/index.js`; - const moduleName: string = 'entry'; const importerFile: string = 'importTest.ts'; const errInfo: LogData = LogDataFactory.newInstance( ErrorCode.ETS2BUNDLE_EXTERNAL_FAILED_TO_RESOLVE_OHM_URL, @@ -1386,5 +1390,38 @@ mocha.describe('generate ohmUrl', function () { CommonLogger.destroyInstance(); this.rollup.share.getHvigorConsoleLogger = getHvigorConsoleLogger; loggerStub.restore(); + + mocha.it('generate declFilesInfo in mixed compilation', function () { + this.rollup.build(); + pkgDeclFilesConfig['entry'] = { + packageName: 'entry', + files: {} + }; + const pkgParams = { + pkgName: 'entry', + moduleName: 'entry', + pkgPath: `${projectConfig.projectRootPath}/entry`, + isRecordName: true, + isArkTsEvolution: false + }; + this.rollup.share.projectConfig.pkgContextInfo = { + 'entry': { + 'packageName': 'entry', + 'bundleName': '', + 'moduleName': '', + 'version': '', + 'entryPath': 'Index.ets', + 'isSO': false + } + }; + const filePath: string = `${projectConfig.projectRootPath}/${INDEX_SOURCE_PATH}`; + const logger = this.rollup.share.getLogger(GEN_ABC_PLUGIN_NAME); + const expectDeclPath: string = `${DECLGENV2OUTPATH}/src/main/pages/Index.d.ets`; + const expectOhmUrl: string = `@normalized:N&entry&com.example.app&entry/src/main/pages/Index&`; + getNormalizedOhmUrlByFilepath(filePath, this.rollup.share.projectConfig, logger, pkgParams); + expect(pkgDeclFilesConfig['entry'].files.length !== 0).to.be.true; + expect(pkgDeclFilesConfig['entry'].files['src/main/pages/Index'].length !== 0).to.be.true; + expect(pkgDeclFilesConfig['entry'].files['src/main/pages/Index'].declPath === expectDeclPath).to.be.true; + expect(pkgDeclFilesConfig['entry'].files['src/main/pages/Index'].ohmUrl === expectOhmUrl).to.be.true; }); }); \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/utils/processProjectConfig.ts b/compiler/test/ark_compiler_ut/utils/processProjectConfig.ts index f98af7e8f..b7a643395 100644 --- a/compiler/test/ark_compiler_ut/utils/processProjectConfig.ts +++ b/compiler/test/ark_compiler_ut/utils/processProjectConfig.ts @@ -46,5 +46,6 @@ projectConfig.pkgContextInfo = { projectConfig.dependencyAliasMap = new Map([ ['library', '@bundle:UtTestApplication/sharedLibrary/ets/index'] ]); +projectConfig.dependentModuleMap = new Map(); export default projectConfig; \ No newline at end of file -- Gitee From 111bbd35ff78a3a6081d3d183c7f4d1b8b562636 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 2 Apr 2025 20:53:31 +0800 Subject: [PATCH 020/123] support get context ptr from lsp Signed-off-by: Jiakai Shi Change-Id: Id0ad35241da451baa5a953b7ad5387e22f3c24b5 --- arkui-plugins/common/plugin-context.ts | 30 ++++++++++++++++--- arkui-plugins/common/program-visitor.ts | 8 ++--- .../memo-plugins/import-transformer.ts | 2 +- arkui-plugins/memo-plugins/index.ts | 11 +++++-- .../memo-plugins/memo-transformer.ts | 2 +- arkui-plugins/ui-plugins/index.ts | 19 ++++++++---- koala-wrapper/src/arkts-api/index.ts | 1 + koala-wrapper/src/arkts-api/static/global.ts | 12 +++++--- .../src/arkts-api/static/globalUtils.ts | 25 ++++++++++++++++ .../src/arkts-api/utilities/performance.ts | 15 ++++++++++ 10 files changed, 102 insertions(+), 23 deletions(-) create mode 100644 koala-wrapper/src/arkts-api/static/globalUtils.ts diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts index 7da72d863..eb110a8bc 100644 --- a/arkui-plugins/common/plugin-context.ts +++ b/arkui-plugins/common/plugin-context.ts @@ -15,30 +15,44 @@ import * as arkts from "@koalaui/libarkts" -// TODO: move this to arkts-api +// This is the same plugin-context in the build-system. export class PluginContext { private ast: arkts.EtsScript | undefined; private program: arkts.Program | undefined; private projectConfig: ProjectConfig | undefined; + private contextPtr: number | undefined; constructor() { this.ast = undefined; this.program = undefined; this.projectConfig = undefined; + this.contextPtr = undefined; } + /** + * @deprecated + */ public setArkTSAst(ast: arkts.EtsScript): void { this.ast = ast; } - + + /** + * @deprecated + */ public getArkTSAst(): arkts.EtsScript | undefined { return this.ast; } - + + /** + * @deprecated + */ public setArkTSProgram(program: arkts.Program): void { this.program = program; } - + + /** + * @deprecated + */ public getArkTSProgram(): arkts.Program | undefined { return this.program; } @@ -50,6 +64,14 @@ export class PluginContext { public getProjectConfig(): ProjectConfig | undefined { return this.projectConfig; } + + public setContextPtr(ptr: number): void { + this.contextPtr = ptr; + } + + public getContextPtr(): number | undefined { + return this.contextPtr; + } } export interface ProjectConfig { diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 2e2a242ae..937c503b6 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -26,7 +26,7 @@ export interface ProgramVisitorOptions extends VisitorOptions { visitors: AbstractVisitor[]; skipPrefixNames: string[]; hooks?: ProgramHooks; - pluginContext: PluginContext; + pluginContext?: PluginContext; } export interface ProgramHookConfig { @@ -83,7 +83,7 @@ export class ProgramVisitor extends AbstractVisitor { private readonly skipPrefixNames: string[]; private readonly hooks?: ProgramHooks; private filenames: Map; - private pluginContext: PluginContext; + private pluginContext?: PluginContext; constructor(options: ProgramVisitorOptions) { super(options); @@ -115,7 +115,7 @@ export class ProgramVisitor extends AbstractVisitor { if (currProgram.peer !== program.peer) { const name: string = this.filenames.get(currProgram.peer)!; - const cachePath: string | undefined = this.pluginContext.getProjectConfig()?.cachePath; + const cachePath: string | undefined = this.pluginContext?.getProjectConfig()?.cachePath; debugDump( currProgram.astNode.dumpSrc(), getDumpFileName(this.state, "ORI", undefined, name), @@ -194,7 +194,7 @@ export class ProgramVisitor extends AbstractVisitor { script.dumpSrc(), getDumpFileName(this.state, this.pluginName, count, transformer.constructor.name), true, - this.pluginContext.getProjectConfig()?.cachePath + this.pluginContext?.getProjectConfig()?.cachePath ); count += 1; } diff --git a/arkui-plugins/memo-plugins/import-transformer.ts b/arkui-plugins/memo-plugins/import-transformer.ts index 4821e9c94..65e6adc4c 100644 --- a/arkui-plugins/memo-plugins/import-transformer.ts +++ b/arkui-plugins/memo-plugins/import-transformer.ts @@ -20,7 +20,7 @@ import { factory } from "./memo-factory" export class ImportTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { if (node instanceof arkts.EtsScript) { - factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext.program); + factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext?.program); return arkts.factory.updateEtsScript( node, node.statements diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index ea39e87bf..4e0043833 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -29,9 +29,11 @@ export function unmemoizeTransform(): Plugins { name: 'memo-plugin', checked(this: PluginContext) { console.log("[MEMO PLUGIN] AFTER CHECKED ENTER"); - let program = arkts.arktsGlobal.compilerContext.program; - let script = program.astNode; - if (script) { + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + let script = program.astNode; + debugLog("[BEFORE MEMO SCRIPT] script: ", script.dumpSrc()); const cachePath: string | undefined = this.getProjectConfig()?.cachePath; debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 5, "MEMO_AfterCheck_Begin"), true, cachePath); @@ -76,6 +78,9 @@ export function unmemoizeTransform(): Plugins { return script; } console.log("[MEMO PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM"); + }, + clean() { + arkts.arktsGlobal.clearContext(); } } } \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/memo-transformer.ts b/arkui-plugins/memo-plugins/memo-transformer.ts index 118f294ef..a0c0191e9 100644 --- a/arkui-plugins/memo-plugins/memo-transformer.ts +++ b/arkui-plugins/memo-plugins/memo-transformer.ts @@ -39,7 +39,7 @@ export default function memoTransformer( const returnTransformer = new ReturnTransformer() const signatureTransformer = new SignatureTransformer() const functionTransformer = new FunctionTransformer({ positionalIdTracker, parameterTransformer, returnTransformer, signatureTransformer }) - factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext.program); + factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext?.program); return functionTransformer.visitor( arkts.factory.updateEtsScript( node, diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index e520ef9fb..1ea707e6b 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -28,9 +28,11 @@ export function uiTransform(): Plugins { name: 'ui-plugin', parsed(this: PluginContext) { console.log('[UI PLUGIN] AFTER PARSED ENTER'); - let program = arkts.arktsGlobal.compilerContext.program; - let script = program.astNode; - if (script) { + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + let script = program.astNode; + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; debugLog('[BEFORE PARSED SCRIPT] script: ', script.dumpSrc()); debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true, cachePath); @@ -63,9 +65,11 @@ export function uiTransform(): Plugins { }, checked(this: PluginContext) { console.log('[UI PLUGIN] AFTER CHECKED ENTER'); - let program = arkts.arktsGlobal.compilerContext.program; - let script = program.astNode; - if (script) { + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + let script = program.astNode; + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; debugLog('[BEFORE STRUCT SCRIPT] script: ', script.dumpSrc()); debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true, cachePath); @@ -103,5 +107,8 @@ export function uiTransform(): Plugins { } console.log('[UI PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); }, + clean() { + arkts.arktsGlobal.clearContext(); + } }; } diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index 5182f38e8..463ae2730 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -73,4 +73,5 @@ export * from "./peers/Program" export * from "./peers/ImportPathManager" export * from "./peers/SourcePosition" export * from "./to-be-generated/MemberExpression" +export * from "./static/globalUtils" export { global as arktsGlobal } from "./static/global"; diff --git a/koala-wrapper/src/arkts-api/static/global.ts b/koala-wrapper/src/arkts-api/static/global.ts index 80504c6bc..551b6c83f 100644 --- a/koala-wrapper/src/arkts-api/static/global.ts +++ b/koala-wrapper/src/arkts-api/static/global.ts @@ -18,7 +18,7 @@ import { KNativePointer } from "@koalaui/interop" import { initEs2panda, Es2pandaNativeModule, initGeneratedEs2panda } from "../../Es2pandaNativeModule" import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from "../../generated/Es2pandaNativeModule" import { initInterop, InteropNativeModule } from "../../InteropNativeModule" -import { Context } from "../peers/Context" +import type { Context } from "../peers/Context" export class global { public static filePath: string = "./plugins/input/main.sts" @@ -39,11 +39,15 @@ export class global { // TODO: rename to contextPeer public static get context(): KNativePointer { - return global.compilerContext.peer ?? throwError('Global.context not initialized') + return global.compilerContext?.peer ?? throwError('Global.context not initialized') } - // TODO: rename to context when the pointer valued one is eliminated - public static compilerContext: Context + // unsafe - could be undefined + public static compilerContext: Context | undefined + + public static clearContext(): void { + this.compilerContext = undefined; + } private static _es2panda: Es2pandaNativeModule | undefined = undefined public static get es2panda(): Es2pandaNativeModule { diff --git a/koala-wrapper/src/arkts-api/static/globalUtils.ts b/koala-wrapper/src/arkts-api/static/globalUtils.ts new file mode 100644 index 000000000..5d1b4b2dd --- /dev/null +++ b/koala-wrapper/src/arkts-api/static/globalUtils.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KNativePointer } from "@koalaui/interop"; +import { Context } from "../peers/Context"; +import { global } from "./global"; + +export function getOrUpdateGlobalContext(peer: KNativePointer): Context { + if (!global.compilerContext || global.context !== peer) { + global.compilerContext = new Context(peer); + } + return global.compilerContext; +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/utilities/performance.ts b/koala-wrapper/src/arkts-api/utilities/performance.ts index 813a244f1..bafe9df5d 100644 --- a/koala-wrapper/src/arkts-api/utilities/performance.ts +++ b/koala-wrapper/src/arkts-api/utilities/performance.ts @@ -1,3 +1,18 @@ +/* + * Copyright (c) 2022-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. + */ + interface Event { name: string, startTime: number, -- Gitee From 89ecf615fb81b2db50b6a36bc008c105d13eafbe Mon Sep 17 00:00:00 2001 From: wuhailong Date: Sun, 23 Mar 2025 21:30:46 +0800 Subject: [PATCH 021/123] Solve issues of mix project compilation Issue: #IBVD8N Signed-off-by: wuhailong Change-Id: I0ccdb3380b40a767cef0139d5bfe4cb248eefa00 --- compiler/package.json | 1 - compiler/src/ark_utils.ts | 79 ++------ compiler/src/ets_checker.ts | 55 ++---- .../ark_compiler/module/module_mode.ts | 51 +++-- .../ark_compiler/module/module_source_file.ts | 33 +++- .../ark_compiler/rollup-plugin-gen-abc.ts | 2 + .../ets_ui/rollup-plugin-ets-checker.ts | 22 +-- compiler/src/pre_define.ts | 3 +- compiler/src/process_arkts_evolution.ts | 186 ++++++++++++++++++ compiler/src/process_module_files.ts | 6 +- .../common/process_arkts_evolution.test.ts | 118 +++++++++++ .../test/ark_compiler_ut/ets_checker.test.ts | 26 +-- .../mock/rollup_mock/common.ts | 3 +- .../mock/rollup_mock/project_config.ts | 8 +- .../module/ohmUrl/ohmUrl.test.ts | 40 +--- 15 files changed, 417 insertions(+), 216 deletions(-) create mode 100644 compiler/src/process_arkts_evolution.ts create mode 100644 compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts diff --git a/compiler/package.json b/compiler/package.json index bee0baf64..ccdb99ec2 100644 --- a/compiler/package.json +++ b/compiler/package.json @@ -37,7 +37,6 @@ "@babel/preset-env": "7.20.2", "@babel/preset-typescript": "7.18.6", "@babel/runtime": "7.20.13", - "@types/proxyquire": "^1.3.31", "@typescript-eslint/parser": "5.51.0", "babel-loader": "9.1.2", "chai": "4.3.7", diff --git a/compiler/src/ark_utils.ts b/compiler/src/ark_utils.ts index ff3c41efb..8aead7287 100644 --- a/compiler/src/ark_utils.ts +++ b/compiler/src/ark_utils.ts @@ -104,36 +104,22 @@ export const SRC_MAIN: string = 'src/main'; export let newSourceMaps: Object = {}; -interface DeclFileConfig { - declPath: string; - ohmUrl: string; -} - -interface DeclFilesConfig { - packageName: string; - files: { - [filePath: string]: DeclFileConfig; - } -} - -export interface ArkTsEvolutionModule { - language: string; // "1.1" | "1.2" - pkgName: string; - moduleName: string; - modulePath: string; - declgenV1OutPath?: string; - declgenV2OutPath?: string; - declgenBridgeCodePath?: string; - declFilesPath?: string; -} - -export let pkgDeclFilesConfig: { [pkgName: string]: DeclFilesConfig } = {} - export const packageCollection: Map> = new Map(); // Splicing ohmurl or record name based on filePath and context information table. export function getNormalizedOhmUrlByFilepath(filePath: string, projectConfig: Object, logger: Object, pkgParams: Object, importerFile: string): string { - const { pkgName, moduleName, pkgPath, isRecordName, isArkTsEvolution } = pkgParams; + const { pkgName, pkgPath, isRecordName } = pkgParams; + const { projectFilePath, pkgInfo } = getPkgInfo(filePath, projectConfig, logger, pkgPath, pkgName, importerFile); + const recordName: string = `${pkgInfo.bundleName}&${pkgName}/${projectFilePath}&${pkgInfo.version}`; + if (isRecordName) { + // record name style: &/entry/ets/xxx/yyy& + return recordName; + } + return `${pkgInfo.isSO ? 'Y' : 'N'}&${pkgInfo.moduleName}&${recordName}`; +} + +export function getPkgInfo(filePath: string, projectConfig: Object, logger: Object, pkgPath: string, + pkgName: string, importerFile?: string): Object { // rollup uses commonjs plugin to handle commonjs files, // the commonjs files are prefixed with '\x00' and need to be removed. if (filePath.startsWith('\x00')) { @@ -149,7 +135,6 @@ export function getNormalizedOhmUrlByFilepath(filePath: string, projectConfig: O // case6: /library/index.ts // ---> @normalized:N&&&/entry/ets/xxx/yyy& let pkgInfo = projectConfig.pkgContextInfo[pkgName]; - let arkTsEvolutionModuleInfo = projectConfig.dependentModuleMap.get(moduleName); if (!pkgInfo || !pkgPath) { const errInfo: LogData = LogDataFactory.newInstance( ErrorCode.ETS2BUNDLE_EXTERNAL_FAILED_TO_RESOLVE_OHM_URL, @@ -163,43 +148,8 @@ export function getNormalizedOhmUrlByFilepath(filePath: string, projectConfig: O logger.printError(errInfo); return filePath; } - let declgenBridgeCodePath: string; - let declgenV2OutPath: string; - let isNeedGenerateDeclFilesConfig: boolean = false; - if (isArkTsEvolution && arkTsEvolutionModuleInfo && arkTsEvolutionModuleInfo.declgenBridgeCodePath) { - declgenBridgeCodePath = toUnixPath(arkTsEvolutionModuleInfo.declgenBridgeCodePath); - } - if (!isArkTsEvolution && arkTsEvolutionModuleInfo && arkTsEvolutionModuleInfo.declgenV2OutPath) { - declgenV2OutPath = toUnixPath(arkTsEvolutionModuleInfo.declgenV2OutPath); - isNeedGenerateDeclFilesConfig = true; - } - let projectFilePath: string = declgenBridgeCodePath && unixFilePath.startsWith(declgenBridgeCodePath + '/') ? - unixFilePath.replace(toUnixPath(path.join(declgenBridgeCodePath, moduleName)) + '/', '') : - unixFilePath.replace(toUnixPath(pkgPath) + '/', ''); - const recordName: string = `${pkgInfo.bundleName}&${pkgName}/${projectFilePath}&${pkgInfo.version}`; - if (isRecordName) { - // record name style: &/entry/ets/xxx/yyy& - if (isNeedGenerateDeclFilesConfig) { - if (!pkgDeclFilesConfig[pkgName]) { - pkgDeclFilesConfig[pkgName] = { packageName: pkgName, files: {}} - } - const packageInfo = getPackageInfo(projectConfig.aceModuleJsonPath); - const ohmUrl: string = `${pkgInfo.isSO ? 'Y' : 'N'}&${moduleName}&${packageInfo[0]}&${pkgName}/${projectFilePath}&${pkgInfo.version}`; - const declFileInfo: Object = { projectFilePath, declgenV2OutPath, ohmUrl: `@normalized:${ohmUrl}` }; - addDeclFilesConfig(pkgDeclFilesConfig[pkgName], declFileInfo); - } - return recordName; - } - return `${pkgInfo.isSO ? 'Y' : 'N'}&${pkgInfo.moduleName}&${recordName}`; -} - -function addDeclFilesConfig(declFilesConfig: DeclFilesConfig, declFileInfo: Object): void { - const { projectFilePath, declgenV2OutPath, ohmUrl } = declFileInfo; - if (declFilesConfig.files[projectFilePath]) { - return; - } - const declPath: string = path.join(declgenV2OutPath, projectFilePath) + EXTNAME_D_ETS; - declFilesConfig.files[projectFilePath] = { declPath, ohmUrl } + const projectFilePath: string = unixFilePath.replace(toUnixPath(pkgPath) + '/', ''); + return { projectFilePath, pkgInfo }; } export function getOhmUrlByFilepath(filePath: string, projectConfig: Object, logger: Object, namespace?: string, @@ -1010,7 +960,6 @@ export function cleanUpUtilsObjects(): void { newSourceMaps = {}; nameCacheMap.clear(); packageCollection.clear(); - pkgDeclFilesConfig = {}; } export function getHookEventFactory(share: Object, pluginName: string, hookName: string): Object { diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index 9e4ce761e..40e2fec41 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -107,8 +107,11 @@ import { buildErrorInfoFromDiagnostic } from './hvigor_error_code/utils'; import { RunnerParms, generateInteropDecls -} from '../node_modules/declgen/build/src/generateInteropDecls' -import { ArkTsEvolutionModule } from './ark_utils'; +} from '../node_modules/declgen/build/src/generateInteropDecls'; +import { + arkTSEvolutionModuleMap, + getArkTSEvoDeclFilePath +} from './process_arkts_evolution'; export interface LanguageServiceCache { service?: ts.LanguageService; @@ -125,8 +128,6 @@ export const TSC_SYSTEM_CODE = '105'; export const MAX_FLOW_DEPTH_DEFAULT_VALUE = 2000; export const MAX_FLOW_DEPTH_MAXIMUM_VALUE = 65535; -export let arkTsEvolutionModuleMap: Map = new Map(); - export function readDeaclareFiles(): string[] { const declarationsFileNames: string[] = []; fs.readdirSync(path.resolve(__dirname, '../declarations')) @@ -1085,26 +1086,17 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string resolvedModules.push(result.resolvedModule); } } else if (result.resolvedModule.resolvedFileName && /\.ets$/.test(result.resolvedModule.resolvedFileName) && - !/\.d\.ets$/.test(result.resolvedModule.resolvedFileName) && arkTsEvolutionModuleMap.size !== 0) { + !/\.d\.ets$/.test(result.resolvedModule.resolvedFileName) && arkTSEvolutionModuleMap.size !== 0) { // When result has a value and the path parsed is the source code file path of module 1.2, // the parsing result needs to be modified to the glue code path of module 1.2 - let staticDeclFileExist: boolean = false; + let arktsEvoDeclFilePathExist: boolean = false; const resolvedFileName: string = toUnixPath(result.resolvedModule.resolvedFileName); - for (const [pkgName, arkTsEvolutionModuleInfo] of arkTsEvolutionModuleMap) { - const modulePath: string = toUnixPath(arkTsEvolutionModuleInfo.modulePath); - const declgenV1OutPath: string = toUnixPath(arkTsEvolutionModuleInfo.declgenV1OutPath); - const declgenBridgeCodePath: string = toUnixPath(arkTsEvolutionModuleInfo.declgenBridgeCodePath); - if (resolvedFileName.startsWith(modulePath + '/') && !resolvedFileName.startsWith(declgenBridgeCodePath + '/')) { - const resultDETSPath: string = - resolvedFileName.replace(modulePath, toUnixPath(path.join(declgenV1OutPath, pkgName))).replace(EXTNAME_ETS, EXTNAME_D_ETS); - if (ts.sys.fileExists(resultDETSPath)) { - resolvedModules.push(getResolveModule(resultDETSPath, EXTNAME_D_ETS)); - staticDeclFileExist = true; - break; - } - } + const resultDETSPath: string = getArkTSEvoDeclFilePath({ moduleRequest: '', resolvedFileName }); + if (ts.sys.fileExists(resultDETSPath)) { + resolvedModules.push(getResolveModule(resultDETSPath, EXTNAME_D_ETS)); + arktsEvoDeclFilePathExist = true; } - if (!staticDeclFileExist) { + if (!arktsEvoDeclFilePathExist) { resolvedModules.push(result.resolvedModule); } } else { @@ -1151,7 +1143,7 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string path.resolve(__dirname, '../node_modules', moduleName + '/index.js'); const DETSModulePath: string = path.resolve(path.dirname(containingFile), /\.d\.ets$/.test(moduleName) ? moduleName : moduleName + EXTNAME_D_ETS); - const arktsEvoDeclFilePath: string = getArktsEvoDeclFilePath(moduleName); + const arktsEvoDeclFilePath: string = getArkTSEvoDeclFilePath({ moduleRequest: moduleName, resolvedFileName: '' }); if (ts.sys.fileExists(modulePath)) { resolvedModules.push(getResolveModule(modulePath, '.d.ts')); } else if (ts.sys.fileExists(systemDETSModulePath)) { @@ -1203,26 +1195,6 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string return resolvedModulesCache.get(path.resolve(containingFile)); } -function getArktsEvoDeclFilePath(moduleRequest: string): string { - let staticDeclFilePath: string = moduleRequest; - for (const [moduleName, arkTsEvolutionModuleInfo] of arkTsEvolutionModuleMap) { - const declgenV1OutPath: string = toUnixPath(arkTsEvolutionModuleInfo.declgenV1OutPath); - if (moduleRequest === moduleName) { - staticDeclFilePath = path.join(declgenV1OutPath, moduleName, 'Index.d.ets'); - break; - } else if (moduleRequest.startsWith(moduleName + '/')) { - staticDeclFilePath = - moduleRequest.replace(moduleName, toUnixPath(path.join(declgenV1OutPath, moduleName, 'src/main/ets'))) + EXTNAME_D_ETS; - break; - } - } - return staticDeclFilePath; -} - -export function cleanUpArkTsEvolutionModuleMap(): void { - arkTsEvolutionModuleMap = new Map(); -} - export interface ResolveModuleInfo { modulePath: string; isEts: boolean; @@ -1867,7 +1839,6 @@ export function resetEtsCheck(): void { dirExistsCache.clear(); targetESVersionChanged = false; fileToIgnoreDiagnostics = undefined; - cleanUpArkTsEvolutionModuleMap(); } export function generateDeclarationFileForSTS(rootFileNames: string[]) { diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts index 582150086..24fbbed14 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_mode.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -93,15 +93,13 @@ import { stopEvent, transformOhmurlToPkgName, transformOhmurlToRecordName, - ArkTsEvolutionModule, - pkgDeclFilesConfig } from '../../../ark_utils'; import { generateAot, FaultHandler } from '../../../gen_aot'; import { - ARK_TS_1_2, + ARKTS_1_2, NATIVE_MODULE } from '../../../pre_define'; import { @@ -119,6 +117,13 @@ import { LogData, LogDataFactory } from '../logger'; +import { + addDeclFilesConfig, + ArkTSEvolutionModule, + getDeclgenBridgeCodePath, + pkgDeclFilesConfig, + arkTSModuleMap +} from '../../../process_arkts_evolution'; export class ModuleInfo { filePath: string; @@ -245,12 +250,13 @@ export class ModuleMode extends CommonMode { ); this.logger.printErrorAndExit(errInfo); } + const isArkTSEvolution: boolean = metaInfo.language === ARKTS_1_2; + const pkgPath: string = isArkTSEvolution ? + path.join(getDeclgenBridgeCodePath(metaInfo.moduleName), metaInfo.moduleName) : metaInfo.pkgPath; const pkgParams = { pkgName: metaInfo.pkgName, - moduleName: metaInfo.moduleName, - pkgPath: metaInfo.pkgPath, + pkgPath, isRecordName: true, - isArkTsEvolution: metaInfo.language === ARK_TS_1_2 }; let recordName: string = getNormalizedOhmUrlByFilepath(moduleId, this.projectConfig, this.logger, pkgParams, undefined); @@ -306,22 +312,23 @@ export class ModuleMode extends CommonMode { prepareForCompilation(rollupObject: Object, parentEvent: Object): void { const eventPrepareForCompilation = createAndStartEvent(parentEvent, 'preparation for compilation'); this.collectModuleFileList(rollupObject, rollupObject.getModuleIds()); - this.writeDeclFilesConfigJson(rollupObject.share.projectConfig.dependentModuleMap); + if (rollupObject.share.projectConfig.dependentModuleMap) { + this.writeDeclFilesConfigJson(rollupObject.share.projectConfig.entryModuleName); + } this.removeCacheInfo(rollupObject); stopEvent(eventPrepareForCompilation); } // Write the declaration file information of the 1.1 module file to the disk of the corresponding module - writeDeclFilesConfigJson(dependentModuleMap: Map): void { - for (const pkgName in pkgDeclFilesConfig) { - const arkTsEvolutionModuleInfo = dependentModuleMap.get(pkgName); - if (!arkTsEvolutionModuleInfo?.declFilesPath) { - return; - } - const declFilesConfigFile: string = toUnixPath(arkTsEvolutionModuleInfo.declFilesPath); - mkdirsSync(path.dirname(declFilesConfigFile)); - fs.writeFileSync(declFilesConfigFile, JSON.stringify(pkgDeclFilesConfig[pkgName], null, 2), 'utf-8'); + writeDeclFilesConfigJson(moduleName: string): void { + if (!arkTSModuleMap.size) { + return; } + const arkTSEvolutionModuleInfo: ArkTSEvolutionModule = arkTSModuleMap.get(moduleName); + const declFilesConfigFile: string = toUnixPath(arkTSEvolutionModuleInfo.declFilesPath); + const packageName: string = arkTSEvolutionModuleInfo.packageName; + mkdirsSync(path.dirname(declFilesConfigFile)); + fs.writeFileSync(declFilesConfigFile, JSON.stringify(pkgDeclFilesConfig[packageName], null, 2), 'utf-8'); } collectModuleFileList(module: Object, fileList: IterableIterator): void { @@ -513,20 +520,24 @@ export class ModuleMode extends CommonMode { let moduleName: string = metaInfo.moduleName; let recordName: string = ''; - let cacheFilePath: string = metaInfo.language === ARK_TS_1_2 ? originalFilePath : + let cacheFilePath: string = metaInfo.language === ARKTS_1_2 ? originalFilePath : this.genFileCachePath(filePath, this.projectConfig.projectRootPath, this.projectConfig.cachePath, metaInfo); let packageName: string = ''; if (this.useNormalizedOHMUrl) { packageName = metaInfo.pkgName; + const isArkTSEvolution: boolean = metaInfo.language === ARKTS_1_2; + const pkgPath: string = isArkTSEvolution ? + path.join(getDeclgenBridgeCodePath(metaInfo.moduleName), metaInfo.moduleName) : metaInfo.pkgPath; const pkgParams = { pkgName: packageName, - moduleName: metaInfo.moduleName, - pkgPath: metaInfo.pkgPath, + pkgPath, isRecordName: true, - isArkTsEvolution: metaInfo.language === ARK_TS_1_2 }; recordName = getNormalizedOhmUrlByFilepath(filePath, this.projectConfig, this.logger, pkgParams, undefined); + if (!isArkTSEvolution) { + addDeclFilesConfig(originalFilePath, metaInfo.moduleName, this.projectConfig, this.logger, pkgPath, packageName); + } } else { recordName = getOhmUrlByFilepath(filePath, this.projectConfig, this.logger, moduleName); if (isPackageModules) { diff --git a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts index 407761880..2da04973d 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts @@ -52,7 +52,8 @@ import { } from '../common/ob_config_resolver'; import { ORIGIN_EXTENTION } from '../process_mock'; import { - ARK_TS_1_2, + ARKTS_1_2, + ESMODULE, TRANSFORMED_MOCK_CONFIG, USER_DEFINE_MOCK_CONFIG } from '../../../pre_define'; @@ -78,6 +79,11 @@ import { ErrorCode } from '../error_code'; import { checkIfJsImportingArkts } from '../check_import_module'; +import { + getDeclgenBridgeCodePath, + writeBridgeCodeFileSyncByNode +} from '../../../process_arkts_evolution'; + const ROLLUP_IMPORT_NODE: string = 'ImportDeclaration'; const ROLLUP_EXPORTNAME_NODE: string = 'ExportNamedDeclaration'; const ROLLUP_EXPORTALL_NODE: string = 'ExportAllDeclaration'; @@ -91,6 +97,7 @@ export class ModuleSourceFile { private source: string | ts.SourceFile; private metaInfo: Object; private isSourceNode: boolean = false; + private isArkTSEvolution: boolean = false; private static projectConfig: Object; private static logger: CommonLogger; private static mockConfigInfo: Object = {}; @@ -110,6 +117,9 @@ export class ModuleSourceFile { if (typeof this.source !== 'string') { this.isSourceNode = true; } + if (metaInfo?.language === ARKTS_1_2) { + this.isArkTSEvolution = true; + } } static setProcessMock(rollupObject: Object): void { @@ -411,12 +421,16 @@ export class ModuleSourceFile { } private async writeSourceFile(parentEvent: Object): Promise { - if (this.isSourceNode && !isJsSourceFile(this.moduleId)) { - await writeFileSyncByNode( this.source, ModuleSourceFile.projectConfig, this.metaInfo, - this.moduleId, parentEvent, printObfLogger); + if (!this.isArkTSEvolution) { + if (this.isSourceNode && !isJsSourceFile(this.moduleId)) { + await writeFileSyncByNode( this.source, ModuleSourceFile.projectConfig, this.metaInfo, + this.moduleId, parentEvent, ModuleSourceFile.logger); + } else { + await writeFileContentToTempDir(this.moduleId, this.source, ModuleSourceFile.projectConfig, + ModuleSourceFile.logger, parentEvent, this.metaInfo); + } } else { - await writeFileContentToTempDir(this.moduleId, this.source, ModuleSourceFile.projectConfig, - printObfLogger, parentEvent, this.metaInfo); + await writeBridgeCodeFileSyncByNode( this.source, this.moduleId); } } @@ -494,12 +508,13 @@ export class ModuleSourceFile { } private static spliceNormalizedOhmurl(moduleInfo: Object, filePath: string, importerFile?: string): string { + const isArkTSEvolution: boolean = moduleInfo.meta.language === ARKTS_1_2; + const pkgPath: string = isArkTSEvolution ? + path.join(getDeclgenBridgeCodePath(moduleInfo.meta.moduleName), moduleInfo.meta.moduleName) : moduleInfo.meta.pkgPath; const pkgParams = { pkgName: moduleInfo.meta.pkgName, - moduleName: moduleInfo.meta.moduleName, - pkgPath: moduleInfo.meta.pkgPath, + pkgPath, isRecordName: false, - isArkTsEvolution: moduleInfo.meta.language === ARK_TS_1_2 }; const ohmUrl: string = getNormalizedOhmUrlByFilepath(filePath, ModuleSourceFile.projectConfig, ModuleSourceFile.logger, pkgParams, diff --git a/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts b/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts index 99bcf140a..08415ffeb 100644 --- a/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts +++ b/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts @@ -27,6 +27,7 @@ import { cleanUpUtilsObjects, writeDeclarationFiles } from '../../ark_utils'; import { cleanUpKitImportObjects } from '../../process_kit_import'; import { cleanUpFilesList } from './utils'; import { CommonLogger } from './logger'; +import { cleanUpProcessArkTSEvolutionObj } from '../../process_arkts_evolution'; export function genAbc() { return { @@ -73,6 +74,7 @@ export function genAbc() { ModuleSourceFile.cleanUpObjects(); cleanSharedModuleSet(); CommonLogger.destroyInstance(); + cleanUpProcessArkTSEvolutionObj(); } }; } diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts index b0583dc4c..46aecc9e8 100644 --- a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts @@ -29,15 +29,9 @@ import { emitBuildInfo, runArkTSLinter, targetESVersionChanged, - collectFileToIgnoreDiagnostics, - TSC_SYSTEM_CODE, - arkTsEvolutionModuleMap, - cleanUpArkTsEvolutionModuleMap, + collectFileToIgnoreDiagnostics } from '../../ets_checker'; -import { - ARK_TS_1_2, - TS_WATCH_END_MSG -} from '../../pre_define'; +import { TS_WATCH_END_MSG } from '../../pre_define'; import { setChecker, startTimeStatisticsLocation, @@ -52,7 +46,7 @@ import { MemoryMonitor } from '../meomry_monitor/rollup-plugin-memory-monitor'; import { MemoryDefine } from '../meomry_monitor/memory_define'; import { LINTER_SUBSYSTEM_CODE } from '../../hvigor_error_code/hvigor_error_info'; import { ErrorCodeModule } from '../../hvigor_error_code/const/error_code_module'; -import { ArkTsEvolutionModule } from '../../ark_utils'; +import { collectArkTSEvolutionModuleInfo } from '../../process_arkts_evolution'; export let tsWatchEmitter: EventEmitter | undefined = undefined; export let tsWatchEndPromise: Promise; @@ -64,7 +58,7 @@ export function etsChecker() { buildStart() { const recordInfo = MemoryMonitor.recordStage(MemoryDefine.ROLLUP_PLUGIN_BUILD_START); if (this.share.projectConfig.dependentModuleMap) { - collectArkTSEvolutionModuleInfo(this.share.projectConfig.dependentModuleMap); + collectArkTSEvolutionModuleInfo(this.share); } const compilationTime: CompilationTimeStatistics = new CompilationTimeStatistics(this.share, 'etsChecker', 'buildStart'); if (process.env.watchMode === 'true' && process.env.triggerTsWatch === 'true') { @@ -163,12 +157,4 @@ function rootFileNamesCollect(rootFileNames: string[]): void { entryFiles.forEach((fileName: string) => { rootFileNames.push(path.resolve(fileName)); }); -} - -function collectArkTSEvolutionModuleInfo(dependentModuleMap: Map): void { - for (const [moduleName, arkTsEvolutionModuleInfo] of dependentModuleMap) { - if (arkTsEvolutionModuleInfo?.declgenV1OutPath && arkTsEvolutionModuleInfo.language === ARK_TS_1_2) { - arkTsEvolutionModuleMap.set(moduleName, arkTsEvolutionModuleInfo); - } - } } \ No newline at end of file diff --git a/compiler/src/pre_define.ts b/compiler/src/pre_define.ts index 23f1a548a..086fdd19e 100644 --- a/compiler/src/pre_define.ts +++ b/compiler/src/pre_define.ts @@ -646,4 +646,5 @@ export const ARKTS_MODULE_NAME: string = 'arkts'; export const COLD_RELOAD_MODE: string = 'coldReload'; export const INTEGRATED_HSP: string = 'integratedHsp'; -export const ARK_TS_1_2: string = '1.2'; +export const ARKTS_1_2: string = '1.2'; +export const ARKTS_1_1: string = '1.1'; diff --git a/compiler/src/process_arkts_evolution.ts b/compiler/src/process_arkts_evolution.ts new file mode 100644 index 000000000..55cdc5556 --- /dev/null +++ b/compiler/src/process_arkts_evolution.ts @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import ts from 'typescript'; + +import { + EXTNAME_ETS, + EXTNAME_D_ETS, + ARKTS_1_1, + ARKTS_1_2 +} from './pre_define'; +import { + toUnixPath, + mkdirsSync +} from './utils'; +import { + red, + reset +} from './fast_build/ark_compiler/common/ark_define'; +import { getPkgInfo } from './ark_utils'; + +interface DeclFileConfig { + declPath: string; + ohmUrl: string; +} + +interface DeclFilesConfig { + packageName: string; + files: { + [filePath: string]: DeclFileConfig; + } +} + +export interface ArkTSEvolutionModule { + language: string; // "1.1" | "1.2" + packageName: string; + moduleName: string; + modulePath: string; + declgenV1OutPath?: string; + declgenV2OutPath?: string; + declgenBridgeCodePath?: string; + declFilesPath?: string; +} + +interface ResolvedFileInfo { + moduleRequest: string; + resolvedFileName: string; +} + +export let pkgDeclFilesConfig: { [pkgName: string]: DeclFilesConfig } = {}; + +export let arkTSModuleMap: Map = new Map(); + +export let arkTSEvolutionModuleMap: Map = new Map(); + +export let arkTSHybridModuleMap: Map = new Map(); + +export function addDeclFilesConfig(filePath: string, moduleName: string, projectConfig: Object, + logger: Object, pkgPath: string, pkgName: string): void { + const { projectFilePath, pkgInfo } = getPkgInfo(filePath, projectConfig, logger, pkgPath, pkgName); + const declgenV2OutPath: string = getDeclgenV2OutPath(moduleName); + if (!declgenV2OutPath) { + return; + } + if (!pkgDeclFilesConfig[pkgName]) { + pkgDeclFilesConfig[pkgName] = { packageName: pkgName, files: {} }; + } + if (pkgDeclFilesConfig[pkgName].files[projectFilePath]) { + return; + } + const isSO: string = pkgInfo.isSO ? 'Y' : 'N'; + // The module name of the entry module of the project during the current compilation process. + const mainModuleName: string = projectConfig.mainModuleName; + const bundleName: string = projectConfig.bundleName; + const normalizedFilePath: string = `${pkgName}/${projectFilePath}`; + const declPath: string = path.join(toUnixPath(declgenV2OutPath), projectFilePath) + EXTNAME_D_ETS; + const ohmUrl: string = `${isSO}&${mainModuleName}&${bundleName}&${normalizedFilePath}&${pkgInfo.version}`; + pkgDeclFilesConfig[pkgName].files[projectFilePath] = { declPath, ohmUrl: `@normalized:${ohmUrl}` }; +} + +export function getArkTSEvoDeclFilePath(resolvedFileInfo: ResolvedFileInfo): string { + const { moduleRequest, resolvedFileName } = resolvedFileInfo; + let arktsEvoDeclFilePath: string = moduleRequest; + for (const [moduleName, arkTSEvolutionModuleInfo] of arkTSEvolutionModuleMap) { + const declgenV1OutPath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenV1OutPath); + const modulePath: string = toUnixPath(arkTSEvolutionModuleInfo.modulePath); + const declgenBridgeCodePath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenBridgeCodePath); + if (resolvedFileName && resolvedFileName.startsWith(modulePath + '/') && + !resolvedFileName.startsWith(declgenBridgeCodePath + '/')) { + arktsEvoDeclFilePath = resolvedFileName + .replace(modulePath, toUnixPath(path.join(declgenV1OutPath, moduleName))) + .replace(EXTNAME_ETS, EXTNAME_D_ETS); + break; + } + if (moduleRequest === moduleName) { + arktsEvoDeclFilePath = path.join(declgenV1OutPath, moduleName, 'Index.d.ets'); + break; + } + if (moduleRequest.startsWith(moduleName + '/')) { + arktsEvoDeclFilePath = moduleRequest.replace( + moduleName, + toUnixPath(path.join(declgenV1OutPath, moduleName, 'src/main/ets')) + ) + EXTNAME_D_ETS; + break; + } + } + return arktsEvoDeclFilePath; +} + +export function collectArkTSEvolutionModuleInfo(share: Object): void { + if (!share.projectConfig.useNormalizedOHMUrl) { + share.throwArkTsCompilerError(red, 'ArkTS:ERROR: Failed to compile mixed project.\n' + + 'Error Message: Failed to compile mixed project because useNormalizedOHMUrl is false.\n' + + 'Solutions: > Check whether useNormalizedOHMUrl is true.', reset); + } + // dependentModuleMap Contents eg. + // 1.2 hap -> 1.1 har: It contains the information of 1.1 har + // 1.1 hap -> 1.2 har -> 1.1 har : There is information about 3 modules. + for (const [moduleName, dependentModuleInfo] of share.projectConfig.dependentModuleMap) { + if (dependentModuleInfo.language === ARKTS_1_2) { + if (dependentModuleInfo.declgenV1OutPath && dependentModuleInfo.declgenBridgeCodePath) { + arkTSEvolutionModuleMap.set(moduleName, dependentModuleInfo); + } else { + share.throwArkTsCompilerError(red, 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + + `Error Message: Failed to collect arkTs evolution module "${moduleName}" info from rollup.`, reset); + } + } else if (dependentModuleInfo.language === ARKTS_1_1) { + if (dependentModuleInfo.declgenV2OutPath && dependentModuleInfo.declFilesPath) { + arkTSModuleMap.set(moduleName, dependentModuleInfo); + } else { + share.throwArkTsCompilerError(red, 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + + `Error Message: Failed to collect arkTs evolution module "${moduleName}" info from rollup.`, reset); + } + } else { + arkTSHybridModuleMap.set(moduleName, dependentModuleInfo); + } + } +} + +export function cleanUpProcessArkTSEvolutionObj(): void { + arkTSModuleMap = new Map(); + arkTSEvolutionModuleMap = new Map(); + arkTSHybridModuleMap = new Map(); + pkgDeclFilesConfig = {}; +} + +export async function writeBridgeCodeFileSyncByNode(node: ts.SourceFile, moduleId: string): Promise { + const printer: ts.Printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed }); + const writer: ts.EmitTextWriter = ts.createTextWriter( + // @ts-ignore + ts.getNewLineCharacter({ newLine: ts.NewLineKind.LineFeed, removeComments: false })); + printer.writeFile(node, writer, undefined); + mkdirsSync(path.dirname(moduleId)); + fs.writeFileSync(moduleId, writer.getText()); +} + +export function getDeclgenBridgeCodePath(moduleName: string): string { + if (arkTSEvolutionModuleMap.size && arkTSEvolutionModuleMap.get(moduleName)) { + const arkTSEvolutionModuleInfo: ArkTSEvolutionModule = arkTSEvolutionModuleMap.get(moduleName); + return arkTSEvolutionModuleInfo.declgenBridgeCodePath; + } + return ''; +} + +function getDeclgenV2OutPath(moduleName: string): string { + if (arkTSModuleMap.size && arkTSModuleMap.get(moduleName)) { + const arkTsModuleInfo: ArkTSEvolutionModule = arkTSModuleMap.get(moduleName); + return arkTsModuleInfo.declgenV2OutPath; + } + return ''; +} + diff --git a/compiler/src/process_module_files.ts b/compiler/src/process_module_files.ts index fe1079a2b..bdc7e8e7e 100644 --- a/compiler/src/process_module_files.ts +++ b/compiler/src/process_module_files.ts @@ -20,8 +20,7 @@ import fs from 'fs'; import { SourceMapGenerator } from './fast_build/ark_compiler/generate_sourcemap'; import { EXTNAME_TS, - EXTNAME_ETS, - ARK_TS_1_2 + EXTNAME_ETS } from './pre_define'; import { genTemporaryPath, @@ -61,8 +60,7 @@ export async function writeFileSyncByNode(node: ts.SourceFile, projectConfig: Ob * In the current realization, when moduleId mechanism is changed, there would be a compilation error. */ let filePath: string = moduleId ? moduleId : node.fileName; - // When the file is glue code for a ArkTS1.2 module, use the path to the glue code. - let temporaryFile: string = metaInfo.language === ARK_TS_1_2 ? filePath : genTemporaryPath(filePath, projectConfig.projectPath, process.env.cachePath, + let temporaryFile: string = genTemporaryPath(filePath, projectConfig.projectPath, process.env.cachePath, projectConfig, metaInfo); if (temporaryFile.length === 0) { return; diff --git a/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts b/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts new file mode 100644 index 000000000..cde7e4eae --- /dev/null +++ b/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use rollupObject file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { expect } from 'chai'; +import mocha from 'mocha'; +import sinon from 'sinon'; + +import { + collectArkTSEvolutionModuleInfo, + addDeclFilesConfig, + pkgDeclFilesConfig, + arkTSModuleMap +} from '../../../lib/process_arkts_evolution'; +import RollUpPluginMock from '../mock/rollup_mock/rollup_plugin_mock'; +import { + BUNDLE_NAME_DEFAULT, + HAR_DECLGENV2OUTPATH +} from '../mock/rollup_mock/common'; + +mocha.describe('process arkts evolution tests', function () { + mocha.before(function () { + this.rollup = new RollUpPluginMock(); + }); + + mocha.after(() => { + delete this.rollup; + }); + + mocha.it('1-1: test error message of collectArkTSEvolutionModuleInfo (useNormalizedOHMUrl is false)', function () { + this.rollup.build(); + this.rollup.share.projectConfig.useNormalizedOHMUrl = false; + this.rollup.share.projectConfig.dependentModuleMap.set('evohar', { language: '1.2' }); + const throwArkTsCompilerErrorStub = sinon.stub(this.rollup.share, 'throwArkTsCompilerError'); + try { + collectArkTSEvolutionModuleInfo(this.rollup.share); + } catch(e) { + } + const errMsg: string = 'ArkTS:ERROR: Failed to compile mixed project.\n' + + `Error Message: Failed to compile mixed project because useNormalizedOHMUrl is false.\n` + + 'Solutions: > Check whether useNormalizedOHMUrl is true.'; + expect(throwArkTsCompilerErrorStub.getCall(0).args[1] === errMsg).to.be.true; + throwArkTsCompilerErrorStub.restore(); + }); + + mocha.it('1-2: test error message of collectArkTSEvolutionModuleInfo (1.2 module information is incorrect)', function () { + this.rollup.build(); + this.rollup.share.projectConfig.useNormalizedOHMUrl = true; + this.rollup.share.projectConfig.dependentModuleMap.set('evohar', { language: '1.2' }); + const throwArkTsCompilerErrorStub = sinon.stub(this.rollup.share, 'throwArkTsCompilerError'); + try { + collectArkTSEvolutionModuleInfo(this.rollup.share); + } catch(e) { + } + const errMsg: string = 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + + `Error Message: Failed to collect arkTs evolution module "evohar" info from rollup.`; + expect(throwArkTsCompilerErrorStub.getCall(0).args[1] === errMsg).to.be.true; + throwArkTsCompilerErrorStub.restore(); + }); + + mocha.it('1-3: test error message of collectArkTSEvolutionModuleInfo (1.1 module information is incorrect)', function () { + this.rollup.build(); + this.rollup.share.projectConfig.useNormalizedOHMUrl = true; + this.rollup.share.projectConfig.dependentModuleMap.set('har', { language: '1.1' }); + const throwArkTsCompilerErrorStub = sinon.stub(this.rollup.share, 'throwArkTsCompilerError'); + try { + collectArkTSEvolutionModuleInfo(this.rollup.share); + } catch(e) { + } + const errMsg: string = 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + + `Error Message: Failed to collect arkTs evolution module "har" info from rollup.`; + expect(throwArkTsCompilerErrorStub.getCall(0).args[1] === errMsg).to.be.true; + throwArkTsCompilerErrorStub.restore(); + }); + + mocha.it('2-1: test generate declFilesInfo in mixed compilation', function () { + pkgDeclFilesConfig['har'] = { + packageName: 'har', + files: {} + }; + const filePath = '/har/Index.ets' + const projectConfig = { + mainModuleName: 'entry', + bundleName: BUNDLE_NAME_DEFAULT, + pkgContextInfo: { + 'har': { + packageName: 'har', + version: '1.0.0', + isSO: false + } + } + } + arkTSModuleMap.set('har', { + language: '1.1', + pkgName: 'har', + declgenV2OutPath: HAR_DECLGENV2OUTPATH + }) + addDeclFilesConfig(filePath, 'har', projectConfig, undefined, '/har', 'har'); + const expectDeclPath: string = `${HAR_DECLGENV2OUTPATH}/Index.d.ets`; + const expectOhmUrl: string = `@normalized:N&entry&${BUNDLE_NAME_DEFAULT}&har/Index&1.0.0`; + expect(pkgDeclFilesConfig['har'].files.length !== 0).to.be.true; + expect(pkgDeclFilesConfig['har'].files['Index'].length !== 0).to.be.true; + expect(pkgDeclFilesConfig['har'].files['Index'].declPath === expectDeclPath).to.be.true; + expect(pkgDeclFilesConfig['har'].files['Index'].ohmUrl === expectOhmUrl).to.be.true; + arkTSModuleMap.clear(); + }); +}); \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/ets_checker.test.ts b/compiler/test/ark_compiler_ut/ets_checker.test.ts index 65583b0b4..0a143534d 100644 --- a/compiler/test/ark_compiler_ut/ets_checker.test.ts +++ b/compiler/test/ark_compiler_ut/ets_checker.test.ts @@ -36,10 +36,8 @@ import { resetEtsCheck, serviceChecker, getMaxFlowDepth, - MAX_FLOW_DEPTH_DEFAULT_VALUE - resolveModuleNames as resolveModuleNamesMain, - arkTsEvolutionModuleMap, - cleanUpArkTsEvolutionModuleMap + MAX_FLOW_DEPTH_DEFAULT_VALUE, + resolveModuleNames as resolveModuleNamesMain } from '../../lib/ets_checker'; import { TS_BUILD_INFO_SUFFIX } from '../../lib/pre_define'; import { @@ -47,6 +45,10 @@ import { projectConfig } from '../../main'; import { mkdirsSync } from '../../lib/utils'; +import { + arkTSEvolutionModuleMap, + cleanUpProcessArkTSEvolutionObj +} from '../../lib/process_arkts_evolution'; mocha.describe('test ets_checker file api', function () { mocha.before(function () { @@ -205,7 +207,7 @@ mocha.describe('test ets_checker file api', function () { 'har', 'har/test' ]; - arkTsEvolutionModuleMap.set('har', { + arkTSEvolutionModuleMap.set('har', { language: '1.2', packageName: 'har', moduleName: 'har', @@ -214,8 +216,8 @@ mocha.describe('test ets_checker file api', function () { declgenBridgeCodePath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/har/build/default/intermediates/declgen/default/bridgecode` }) const filePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/${DEFAULT_ENTRY}/src/main/entryability/test.ets`; - const arktsEvoIndexDeclFilePath: string = `${arkTsEvolutionModuleMap.get('har').declgenV1OutPath}/har/Index.d.ets`; - const arktsEvoTestDeclFilePath: string = `${arkTsEvolutionModuleMap.get('har').declgenV1OutPath}/har/src/main/ets/test.d.ets`; + const arktsEvoIndexDeclFilePath: string = `${arkTSEvolutionModuleMap.get('har').declgenV1OutPath}/har/Index.d.ets`; + const arktsEvoTestDeclFilePath: string = `${arkTSEvolutionModuleMap.get('har').declgenV1OutPath}/har/src/main/ets/test.d.ets`; fs.writeFileSync(filePath, code); mkdirsSync(path.dirname(arktsEvoIndexDeclFilePath)); mkdirsSync(path.dirname(arktsEvoTestDeclFilePath)); @@ -227,12 +229,12 @@ mocha.describe('test ets_checker file api', function () { fs.unlinkSync(filePath); fs.unlinkSync(arktsEvoIndexDeclFilePath); fs.unlinkSync(arktsEvoTestDeclFilePath); - cleanUpArkTsEvolutionModuleMap(); + cleanUpProcessArkTSEvolutionObj(); }); mocha.it('2-2: test resolveModuleNames parse the 1.2 module declaration file that the 1.1 module depends on (packageName)', function () { const moduleNames: string[] = ['testhar']; - arkTsEvolutionModuleMap.set('har', { + arkTSEvolutionModuleMap.set('har', { language: '1.2', packageName: 'testhar', moduleName: 'testhar', @@ -242,7 +244,7 @@ mocha.describe('test ets_checker file api', function () { }) const filePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/${DEFAULT_ENTRY}/src/main/entryability/test.ets`; const arktsEvoIndexFilePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/Index.ets`; - const arktsEvoIndexDeclFilePath: string = `${arkTsEvolutionModuleMap.get('har').declgenV1OutPath}/testhar/Index.d.ets`; + const arktsEvoIndexDeclFilePath: string = `${arkTSEvolutionModuleMap.get('har').declgenV1OutPath}/testhar/Index.d.ets`; const resolveModuleNameStub = sinon.stub(ts, 'resolveModuleName').returns({ resolvedModule: { resolvedFileName: arktsEvoIndexFilePath, @@ -272,7 +274,7 @@ mocha.describe('test ets_checker file api', function () { mocha.it('2-3: test resolveModuleNames parse the 1.2 module declaration file that the 1.1 module depends on', function () { const moduleNames: string[] = ['testhar/src/main/ets/test']; - arkTsEvolutionModuleMap.set('har', { + arkTSEvolutionModuleMap.set('har', { language: '1.2', packageName: 'testhar', moduleName: 'testhar', @@ -282,7 +284,7 @@ mocha.describe('test ets_checker file api', function () { }) const filePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/${DEFAULT_ENTRY}/src/main/entryability/test.ets`; const arktsEvoTestFilePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/src/main/ets/test.ets`; - const arktsEvoTestDeclFilePath: string = `${arkTsEvolutionModuleMap.get('har').declgenV1OutPath}/testhar/src/main/ets/test.d.ets`; + const arktsEvoTestDeclFilePath: string = `${arkTSEvolutionModuleMap.get('har').declgenV1OutPath}/testhar/src/main/ets/test.d.ets`; const resolveModuleNameStub = sinon.stub(ts, 'resolveModuleName').returns({ resolvedModule: { resolvedFileName: arktsEvoTestFilePath, diff --git a/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts b/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts index aa0c7c34e..123f315d9 100644 --- a/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts +++ b/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts @@ -82,4 +82,5 @@ export const TEST: string = 'test'; export const NEWFILE: string = 'newFile'; export const DECLFILESPATH: string = '/entry/build/default/intermediates/loader_out/default/etsFortgz/decl-fileInfo.json'; -export const DECLGENV2OUTPATH: string = '/entry/build/default/intermediates/declgen/default/declgenV2'; \ No newline at end of file +export const DECLGENV2OUTPATH: string = '/entry/build/default/intermediates/declgen/default/declgenV2'; +export const HAR_DECLGENV2OUTPATH: string = '/har/build/default/intermediates/declgen/default/declgenV2'; \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/mock/rollup_mock/project_config.ts b/compiler/test/ark_compiler_ut/mock/rollup_mock/project_config.ts index 243038c36..fc63322da 100644 --- a/compiler/test/ark_compiler_ut/mock/rollup_mock/project_config.ts +++ b/compiler/test/ark_compiler_ut/mock/rollup_mock/project_config.ts @@ -39,7 +39,7 @@ import { OHPM, RELEASE } from "../../../../lib/fast_build/ark_compiler/common/ark_define"; -import { ArkTsEvolutionModule } from "../../../../lib/ark_utils"; +import { ArkTSEvolutionModule } from "../../../../lib/process_arkts_evolution"; interface IArkProjectConfig { projectRootPath: string, @@ -133,7 +133,7 @@ class ProjectConfig { widgetCompile: boolean; arkRouterMap: Array; declarationEntry: Array; - dependentModuleMap: Map; + dependentModuleMap: Map; constructor(buildMode: string) { this.watchMode = 'false'; @@ -268,7 +268,7 @@ class ProjectConfig { } private setDependentModuleMap() { - const arkTsEvolutionModuleInfo = { + const arkTSEvolutionModuleInfo = { language: '1.1', pkgName: this.entryModuleName, moduleName: this.entryModuleName, @@ -276,7 +276,7 @@ class ProjectConfig { declgenV2OutPath: DECLGENV2OUTPATH, declFilesPath: DECLFILESPATH } - this.dependentModuleMap.set(this.entryModuleName, arkTsEvolutionModuleInfo) + this.dependentModuleMap.set(this.entryModuleName, arkTSEvolutionModuleInfo) } } diff --git a/compiler/test/ark_compiler_ut/module/ohmUrl/ohmUrl.test.ts b/compiler/test/ark_compiler_ut/module/ohmUrl/ohmUrl.test.ts index 2c3b21542..edf6d1c49 100644 --- a/compiler/test/ark_compiler_ut/module/ohmUrl/ohmUrl.test.ts +++ b/compiler/test/ark_compiler_ut/module/ohmUrl/ohmUrl.test.ts @@ -22,8 +22,7 @@ import { getOhmUrlByExternalPackage, getOhmUrlBySystemApiOrLibRequest, getNormalizedOhmUrlByFilepath, - getNormalizedOhmUrlByAliasName, - pkgDeclFilesConfig + getNormalizedOhmUrlByAliasName } from '../../../../lib/ark_utils'; import { PACKAGES } from '../../../../lib/pre_define'; import projectConfig from '../../utils/processProjectConfig'; @@ -41,10 +40,6 @@ import { LogData, LogDataFactory } from '../../../../lib/fast_build/ark_compiler/logger'; -import { - DECLGENV2OUTPATH, - INDEX_SOURCE_PATH -} from '../../mock/rollup_mock/common'; const PRVIEW_MOCK_CONFIG : Object = { // system api mock @@ -1390,38 +1385,5 @@ mocha.describe('generate ohmUrl', function () { CommonLogger.destroyInstance(); this.rollup.share.getHvigorConsoleLogger = getHvigorConsoleLogger; loggerStub.restore(); - - mocha.it('generate declFilesInfo in mixed compilation', function () { - this.rollup.build(); - pkgDeclFilesConfig['entry'] = { - packageName: 'entry', - files: {} - }; - const pkgParams = { - pkgName: 'entry', - moduleName: 'entry', - pkgPath: `${projectConfig.projectRootPath}/entry`, - isRecordName: true, - isArkTsEvolution: false - }; - this.rollup.share.projectConfig.pkgContextInfo = { - 'entry': { - 'packageName': 'entry', - 'bundleName': '', - 'moduleName': '', - 'version': '', - 'entryPath': 'Index.ets', - 'isSO': false - } - }; - const filePath: string = `${projectConfig.projectRootPath}/${INDEX_SOURCE_PATH}`; - const logger = this.rollup.share.getLogger(GEN_ABC_PLUGIN_NAME); - const expectDeclPath: string = `${DECLGENV2OUTPATH}/src/main/pages/Index.d.ets`; - const expectOhmUrl: string = `@normalized:N&entry&com.example.app&entry/src/main/pages/Index&`; - getNormalizedOhmUrlByFilepath(filePath, this.rollup.share.projectConfig, logger, pkgParams); - expect(pkgDeclFilesConfig['entry'].files.length !== 0).to.be.true; - expect(pkgDeclFilesConfig['entry'].files['src/main/pages/Index'].length !== 0).to.be.true; - expect(pkgDeclFilesConfig['entry'].files['src/main/pages/Index'].declPath === expectDeclPath).to.be.true; - expect(pkgDeclFilesConfig['entry'].files['src/main/pages/Index'].ohmUrl === expectOhmUrl).to.be.true; }); }); \ No newline at end of file -- Gitee From 6b3816b11b34a3e95ffe50cdd38b70487b3a5a39 Mon Sep 17 00:00:00 2001 From: lixingchi1 Date: Mon, 7 Apr 2025 14:34:50 +0800 Subject: [PATCH 022/123] 1.2 use 1.1 sync to 0328 Signed-off-by: lixingchi1 --- compiler/src/ets_checker.ts | 2 + compiler/src/import_whiteList.ts | 1626 +++++++++++++++++++++ compiler/src/process_interop_ui.ts | 325 ++++ compiler/test/interop_ui/demo/index.d.ets | 24 + compiler/test/interop_ui/package.json | 11 + compiler/test/interop_ui/test.js | 23 + 6 files changed, 2011 insertions(+) create mode 100644 compiler/src/import_whiteList.ts create mode 100644 compiler/src/process_interop_ui.ts create mode 100644 compiler/test/interop_ui/demo/index.d.ets create mode 100644 compiler/test/interop_ui/package.json create mode 100644 compiler/test/interop_ui/test.js diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index 40e2fec41..87e0b0ca8 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -112,6 +112,7 @@ import { arkTSEvolutionModuleMap, getArkTSEvoDeclFilePath } from './process_arkts_evolution'; +import { processInteropUI } from './process_interop_ui'; export interface LanguageServiceCache { service?: ts.LanguageService; @@ -567,6 +568,7 @@ export function serviceChecker(rootFileNames: string[], newLogger: Object = null } if (rollupShareObject?.projectConfig.mixCompile) { generateDeclarationFileForSTS(rootFileNames); + processInteropUI(projectConfig.dependentModuleMap?.get(projectConfig.moduleName)?.declgenV2OutPath); } if (globalProgram.program && (process.env.watchMode !== 'true' && !projectConfig.isPreview && diff --git a/compiler/src/import_whiteList.ts b/compiler/src/import_whiteList.ts new file mode 100644 index 000000000..6ab881ba3 --- /dev/null +++ b/compiler/src/import_whiteList.ts @@ -0,0 +1,1626 @@ +/* + * 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. + */ + +export const whiteList: Set = new Set([ + 'ASTCResource', + 'AbilityComponent', + 'AbilityComponentAttribute', + 'AbstractProperty', + 'AccelerationOptions', + 'AccessibilityAction', + 'AccessibilityActionInterceptResult', + 'AccessibilityCallback', + 'AccessibilityHoverEvent', + 'AccessibilityHoverType', + 'AccessibilityOptions', + 'AccessibilityRoleType', + 'AccessibilitySamePageMode', + 'ActionSheet', + 'ActionSheetButtonOptions', + 'ActionSheetOffset', + 'ActionSheetOptions', + 'AdaptiveColor', + 'AdsBlockedDetails', + 'Affinity', + 'AlertDialog', + 'AlertDialogButtonBaseOptions', + 'AlertDialogButtonOptions', + 'AlertDialogParam', + 'AlertDialogParamWithButtons', + 'AlertDialogParamWithConfirm', + 'AlertDialogParamWithOptions', + 'AlignRuleOption', + 'Alignment', + 'AlphabetIndexer', + 'AlphabetIndexerAttribute', + 'AlphabetIndexerOptions', + 'AnchoredColorMode', + 'AnimatableArithmetic', + 'AnimatableExtend', + 'AnimateParam', + 'AnimationExtender', + 'AnimationMode', + 'AnimationRange', + 'AnimationStatus', + 'Animator', + 'AnimatorAttribute', + 'AnimatorInterface', + 'AppRotation', + 'AppStorage', + 'AppearSymbolEffect', + 'Area', + 'ArrowPointPosition', + 'ArrowPosition', + 'ArrowStyle', + 'AttributeModifier', + 'AutoCapitalizationMode', + 'AutoPlayOptions', + 'AvailableLayoutArea', + 'AvoidanceMode', + 'Axis', + 'AxisAction', + 'AxisEvent', + 'AxisModel', + 'BackgroundBlurStyleOptions', + 'BackgroundBrightnessOptions', + 'BackgroundColorStyle', + 'BackgroundEffectOptions', + 'BackgroundImageOptions', + 'Badge', + 'BadgeAttribute', + 'BadgeParam', + 'BadgeParamWithNumber', + 'BadgeParamWithString', + 'BadgePosition', + 'BadgeStyle', + 'BarGridColumnOptions', + 'BarMode', + 'BarPosition', + 'BarState', + 'BarStyle', + 'BarrierDirection', + 'BarrierStyle', + 'BaseCustomComponent', + 'BaseEvent', + 'BaseGestureEvent', + 'BaseHandlerOptions', + 'BaseShape', + 'BaseSpan', + 'BaselineOffsetStyle', + 'Bias', + 'BindOptions', + 'Blank', + 'BlankAttribute', + 'BlendApplyType', + 'BlendMode', + 'Blender', + 'BlurOptions', + 'BlurStyle', + 'BlurStyleActivePolicy', + 'BlurStyleOptions', + 'BoardStyle', + 'BorderImageOption', + 'BorderOptions', + 'BorderRadiuses', + 'BorderStyle', + 'BottomTabBarStyle', + 'BounceSymbolEffect', + 'BreakPoints', + 'BreakpointsReference', + 'Builder', + 'BuilderAttachment', + 'BuilderAttachmentInterface', + 'BuilderParam', + 'BusinessError', + 'Button', + 'ButtonAttribute', + 'ButtonConfiguration', + 'ButtonIconOptions', + 'ButtonOptions', + 'ButtonRole', + 'ButtonStyle', + 'ButtonStyleMode', + 'ButtonTriggerClickCallback', + 'ButtonType', + 'CacheMode', + 'Calendar', + 'CalendarAlign', + 'CalendarAttribute', + 'CalendarController', + 'CalendarDay', + 'CalendarDialogOptions', + 'CalendarOptions', + 'CalendarPicker', + 'CalendarPickerAttribute', + 'CalendarPickerDialog', + 'CalendarRequestedData', + 'CalendarSelectedDate', + 'Callback', + 'CallbackBuffer', + 'CallbackKind', + 'CallbackResource', + 'CallbackResourceHolder', + 'CancelButtonOptions', + 'CancelButtonStyle', + 'CancelButtonSymbolOptions', + 'Canvas', + 'CanvasAttribute', + 'CanvasDirection', + 'CanvasFillRule', + 'CanvasGradient', + 'CanvasLineCap', + 'CanvasLineJoin', + 'CanvasOptions', + 'CanvasPath', + 'CanvasPattern', + 'CanvasRenderer', + 'CanvasRenderingContext2D', + 'CanvasTextAlign', + 'CanvasTextBaseline', + 'CapsuleStyleOptions', + 'CaretOffset', + 'CaretStyle', + 'ChainAnimationOptions', + 'ChainEdgeEffect', + 'ChainStyle', + 'ChainWeightOptions', + 'CheckBoxConfiguration', + 'CheckBoxShape', + 'Checkbox', + 'CheckboxAttribute', + 'CheckboxGroup', + 'CheckboxGroupAttribute', + 'CheckboxGroupOptions', + 'CheckboxGroupResult', + 'CheckboxOptions', + 'ChildHitFilterOption', + 'ChildrenMainSize', + 'Circle', + 'CircleAttribute', + 'CircleOptions', + 'CircleShape', + 'CircleStyleOptions', + 'ClickEffect', + 'ClickEffectLevel', + 'ClickEvent', + 'ClientAuthenticationHandler', + 'CloseSwipeActionOptions', + 'Color', + 'ColorContent', + 'ColorFilter', + 'ColorMetrics', + 'ColorMode', + 'ColorStop', + 'ColoringStrategy', + 'Column', + 'ColumnAttribute', + 'ColumnOptions', + 'ColumnOptionsV2', + 'ColumnSplit', + 'ColumnSplitAttribute', + 'ColumnSplitDividerStyle', + 'CommonAttribute', + 'CommonConfiguration', + 'CommonMethod', + 'CommonProgressStyleOptions', + 'CommonShape', + 'CommonShapeMethod', + 'CommonTransition', + 'Component', + 'Component3D', + 'Component3DAttribute', + 'ComponentContent', + 'ComponentOptions', + 'ComponentRoot', + 'ComponentV2', + 'Computed', + 'ComputedBarAttribute', + 'Concurrent', + 'Configuration', + 'ConsoleMessage', + 'ConstraintSizeOptions', + 'Consume', + 'Consumer', + 'ContainerSpan', + 'ContainerSpanAttribute', + 'Content', + 'ContentClipMode', + 'ContentCoverOptions', + 'ContentDidScrollCallback', + 'ContentModifier', + 'ContentSlot', + 'ContentSlotAttribute', + 'ContentType', + 'Context', + 'ContextMenu', + 'ContextMenuAnimationOptions', + 'ContextMenuEditStateFlags', + 'ContextMenuInputFieldType', + 'ContextMenuMediaType', + 'ContextMenuOptions', + 'ContextMenuSourceType', + 'ControlSize', + 'ControllerHandler', + 'CopyEvent', + 'CopyOptions', + 'Counter', + 'CounterAttribute', + 'CrownAction', + 'CrownEvent', + 'CrownSensitivity', + 'CurrentDayStyle', + 'Curve', + 'CustomBuilder', + 'CustomComponent', + 'CustomComponentV2', + 'CustomDialog', + 'CustomDialogController', + 'CustomDialogControllerOptions', + 'CustomNodeBuilder', + 'CustomPopupOptions', + 'CustomSpan', + 'CustomSpanDrawInfo', + 'CustomSpanMeasureInfo', + 'CustomSpanMetrics', + 'CustomTheme', + 'CutEvent', + 'DataAddOperation', + 'DataChangeListener', + 'DataChangeOperation', + 'DataDeleteOperation', + 'DataExchangeOperation', + 'DataMoveOperation', + 'DataOperation', + 'DataOperationType', + 'DataPanel', + 'DataPanelAttribute', + 'DataPanelConfiguration', + 'DataPanelOptions', + 'DataPanelShadowOptions', + 'DataPanelType', + 'DataReloadOperation', + 'DataResubmissionHandler', + 'DatePicker', + 'DatePickerAttribute', + 'DatePickerDialog', + 'DatePickerDialogOptions', + 'DatePickerMode', + 'DatePickerOptions', + 'DatePickerResult', + 'DateRange', + 'DateTimeOptions', + 'DecorationStyle', + 'DecorationStyleInterface', + 'DecorationStyleResult', + 'Degree', + 'DeleteValue', + 'Deserializer', + 'DialogAlignment', + 'DialogButtonDirection', + 'DialogButtonStyle', + 'DialogDisplayMode', + 'DigitIndicator', + 'Dimension', + 'Direction', + 'DirectionalEdgesT', + 'DisableSymbolEffect', + 'DisappearSymbolEffect', + 'DismissContentCoverAction', + 'DismissContinueReason', + 'DismissDialogAction', + 'DismissFollowUpAction', + 'DismissMenuAction', + 'DismissPopupAction', + 'DismissReason', + 'DismissSheetAction', + 'DistributionType', + 'DisturbanceFieldOptions', + 'DisturbanceFieldShape', + 'Divider', + 'DividerAttribute', + 'DividerMode', + 'DividerOptions', + 'DividerStyle', + 'DividerStyleOptions', + 'DotIndicator', + 'DoubleAnimationParam', + 'DpiFollowStrategy', + 'DragBehavior', + 'DragEvent', + 'DragInteractionOptions', + 'DragItemInfo', + 'DragPointCoordinate', + 'DragPreviewLiftingScale', + 'DragPreviewMode', + 'DragPreviewOptions', + 'DragResult', + 'DraggingSizeChangeEffect', + 'DrawContext', + 'DrawModifier', + 'DrawableDescriptor', + 'DrawingCanvas', + 'DrawingColorFilter', + 'DrawingLattice', + 'DrawingRenderingContext', + 'DropOptions', + 'DynamicNode', + 'DynamicRangeMode', + 'EclipseStyleOptions', + 'Edge', + 'EdgeColors', + 'EdgeEffect', + 'EdgeEffectOptions', + 'EdgeOutlineStyles', + 'EdgeOutlineWidths', + 'EdgeStyles', + 'EdgeWidth', + 'EdgeWidths', + 'Edges', + 'EditMenuOptions', + 'EditMode', + 'EditableTextChangeValue', + 'EditableTextOnChangeCallback', + 'EffectComponent', + 'EffectComponentAttribute', + 'EffectDirection', + 'EffectEdge', + 'EffectFillStyle', + 'EffectScope', + 'EffectType', + 'Ellipse', + 'EllipseAttribute', + 'EllipseOptions', + 'EllipseShape', + 'EllipsisMode', + 'EmbeddedComponent', + 'EmbeddedComponentAttribute', + 'EmbeddedDpiFollowStrategy', + 'EmbeddedOptions', + 'EmbeddedType', + 'EmbeddedWindowModeFollowStrategy', + 'EmitterOptions', + 'EmitterParticleOptions', + 'EmitterProperty', + 'EnterKeyType', + 'Entry', + 'EntryOptions', + 'EnvPropsOptions', + 'Environment', + 'ErrorCallback', + 'Event', + 'EventEmulator', + 'EventLocationInfo', + 'EventQueryType', + 'EventResult', + 'EventTarget', + 'EventTargetInfo', + 'ExchangeIndex', + 'ExchangeKey', + 'ExpandedMenuItemOptions', + 'ExpectedFrameRateRange', + 'Extend', + 'FP', + 'FadingEdgeOptions', + 'FileSelectorMode', + 'FileSelectorParam', + 'FileSelectorResult', + 'FillMode', + 'Filter', + 'FingerInfo', + 'FinishCallbackType', + 'FirstMeaningfulPaint', + 'Flex', + 'FlexAlign', + 'FlexAttribute', + 'FlexDirection', + 'FlexOptions', + 'FlexSpaceOptions', + 'FlexWrap', + 'FlowItem', + 'FlowItemAttribute', + 'FocusAxisEvent', + 'FocusBoxStyle', + 'FocusController', + 'FocusDrawLevel', + 'FocusMovement', + 'FocusPriority', + 'FocusWrapMode', + 'FoldStatus', + 'FolderStack', + 'FolderStackAttribute', + 'FolderStackOptions', + 'Font', + 'FontInfo', + 'FontOptions', + 'FontSettingOptions', + 'FontStyle', + 'FontWeight', + 'ForEach', + 'ForEachAttribute', + 'ForegroundBlurStyleOptions', + 'ForegroundEffectOptions', + 'FormCallbackInfo', + 'FormComponent', + 'FormComponentAttribute', + 'FormDimension', + 'FormInfo', + 'FormLink', + 'FormLinkAttribute', + 'FormLinkOptions', + 'FormRenderingMode', + 'FormShape', + 'FractionStop', + 'FrameNode', + 'FrictionMotion', + 'FullScreenEnterEvent', + 'FullScreenExitHandler', + 'FullscreenInfo', + 'FunctionKey', + 'Gauge', + 'GaugeAttribute', + 'GaugeConfiguration', + 'GaugeIndicatorOptions', + 'GaugeOptions', + 'GaugeShadowOptions', + 'GeometryInfo', + 'GeometryTransitionOptions', + 'Gesture', + 'GestureControl', + 'GestureEvent', + 'GestureGroup', + 'GestureGroupGestureHandlerOptions', + 'GestureGroupHandler', + 'GestureHandler', + 'GestureInfo', + 'GestureJudgeResult', + 'GestureMask', + 'GestureMode', + 'GestureModifier', + 'GesturePriority', + 'GestureRecognizer', + 'GestureRecognizerJudgeBeginCallback', + 'GestureRecognizerState', + 'GestureStyle', + 'GestureType', + 'GetItemMainSizeByIndex', + 'GradientDirection', + 'Grid', + 'GridAttribute', + 'GridCol', + 'GridColAttribute', + 'GridColColumnOption', + 'GridColOptions', + 'GridContainer', + 'GridContainerAttribute', + 'GridContainerOptions', + 'GridDirection', + 'GridItem', + 'GridItemAlignment', + 'GridItemAttribute', + 'GridItemOptions', + 'GridItemStyle', + 'GridLayoutOptions', + 'GridRow', + 'GridRowAttribute', + 'GridRowColumnOption', + 'GridRowDirection', + 'GridRowOptions', + 'GridRowSizeOption', + 'GuideLinePosition', + 'GuideLineStyle', + 'GutterOption', + 'HapticFeedbackMode', + 'Header', + 'HeightBreakpoint', + 'HierarchicalSymbolEffect', + 'HistoricalPoint', + 'HitTestMode', + 'HitTestType', + 'HorizontalAlign', + 'HoverCallback', + 'HoverEffect', + 'HoverEvent', + 'HoverEventParam', + 'HoverModeAreaType', + 'HttpAuthHandler', + 'Hyperlink', + 'HyperlinkAttribute', + 'ICurve', + 'IDataSource', + 'IMonitor', + 'IMonitorValue', + 'IPropertySubscriber', + 'ISinglePropertyChangeSubscriber', + 'IconOptions', + 'IlluminatedType', + 'Image', + 'ImageAIOptions', + 'ImageAnalyzerConfig', + 'ImageAnalyzerController', + 'ImageAnalyzerType', + 'ImageAnimator', + 'ImageAnimatorAttribute', + 'ImageAttachment', + 'ImageAttachmentInterface', + 'ImageAttachmentLayoutStyle', + 'ImageAttribute', + 'ImageBitmap', + 'ImageCompleteCallback', + 'ImageContent', + 'ImageData', + 'ImageError', + 'ImageErrorCallback', + 'ImageFit', + 'ImageFrameInfo', + 'ImageInterpolation', + 'ImageLoadResult', + 'ImageModifier', + 'ImageParticleParameters', + 'ImageRenderMode', + 'ImageRepeat', + 'ImageRotateOrientation', + 'ImageSize', + 'ImageSmoothingQuality', + 'ImageSourceSize', + 'ImageSpan', + 'ImageSpanAlignment', + 'ImageSpanAttribute', + 'IndexerAlign', + 'Indicator', + 'IndicatorComponent', + 'IndicatorComponentAttribute', + 'IndicatorComponentController', + 'IndicatorStyle', + 'InputCounterOptions', + 'InputType', + 'InsertValue', + 'IntelligentTrackingPreventionDetails', + 'IntentionCode', + 'InteractionHand', + 'InterceptionModeCallback', + 'InterceptionShowCallback', + 'Interop', + 'InvertOptions', + 'IsolatedComponent', + 'IsolatedComponentAttribute', + 'IsolatedOptions', + 'ItemAlign', + 'ItemDragEventHandler', + 'ItemDragInfo', + 'ItemState', + 'JavaScriptProxy', + 'JsGeolocation', + 'JsResult', + 'KVMContext', + 'KeyEvent', + 'KeyProcessingMode', + 'KeySource', + 'KeyType', + 'KeyboardAppearance', + 'KeyboardAvoidMode', + 'KeyboardOptions', + 'KeyframeAnimateParam', + 'KeyframeState', + 'LPX', + 'LabelStyle', + 'LargestContentfulPaint', + 'LaunchMode', + 'LayoutBorderInfo', + 'LayoutChild', + 'LayoutDirection', + 'LayoutInfo', + 'LayoutManager', + 'LayoutMode', + 'LayoutPolicy', + 'LayoutSafeAreaEdge', + 'LayoutSafeAreaType', + 'LayoutStyle', + 'Layoutable', + 'LazyForEach', + 'LazyForEachAttribute', + 'LazyForEachOps', + 'LazyGridLayoutAttribute', + 'LazyVGridLayout', + 'LazyVGridLayoutAttribute', + 'LeadingMarginPlaceholder', + 'Length', + 'LengthConstrain', + 'LengthMetrics', + 'LengthMetricsUnit', + 'LengthUnit', + 'LetterSpacingStyle', + 'LightSource', + 'Line', + 'LineAttribute', + 'LineBreakStrategy', + 'LineCapStyle', + 'LineHeightStyle', + 'LineJoinStyle', + 'LineMetrics', + 'LineOptions', + 'LineSpacingOptions', + 'LinearGradient', + 'LinearGradientBlurOptions', + 'LinearGradientOptions', + 'LinearIndicator', + 'LinearIndicatorAttribute', + 'LinearIndicatorController', + 'LinearIndicatorStartOptions', + 'LinearIndicatorStyle', + 'LinearStyleOptions', + 'Link', + 'List', + 'ListAttribute', + 'ListDividerOptions', + 'ListItem', + 'ListItemAlign', + 'ListItemAttribute', + 'ListItemGroup', + 'ListItemGroupArea', + 'ListItemGroupAttribute', + 'ListItemGroupOptions', + 'ListItemGroupStyle', + 'ListItemOptions', + 'ListItemStyle', + 'ListOptions', + 'ListScroller', + 'LoadCommittedDetails', + 'Loader', + 'LoadingProgress', + 'LoadingProgressAttribute', + 'LoadingProgressConfiguration', + 'LoadingProgressStyle', + 'Local', + 'LocalBuilder', + 'LocalStorage', + 'LocalStorageLink', + 'LocalStorageProp', + 'LocalizedAlignRuleOptions', + 'LocalizedAlignment', + 'LocalizedBarrierDirection', + 'LocalizedBarrierStyle', + 'LocalizedBorderRadiuses', + 'LocalizedDragPointCoordinate', + 'LocalizedEdgeColors', + 'LocalizedEdgeWidths', + 'LocalizedEdges', + 'LocalizedHorizontalAlignParam', + 'LocalizedMargin', + 'LocalizedPadding', + 'LocalizedPosition', + 'LocalizedVerticalAlignParam', + 'LocationButton', + 'LocationButtonAttribute', + 'LocationButtonOnClickResult', + 'LocationButtonOptions', + 'LocationDescription', + 'LocationIconStyle', + 'LongPressGesture', + 'LongPressGestureEvent', + 'LongPressGestureHandler', + 'LongPressGestureHandlerOptions', + 'LongPressGestureParams', + 'LongPressRecognizer', + 'LunarSwitchStyle', + 'Margin', + 'MarkStyle', + 'Marquee', + 'MarqueeAttribute', + 'MarqueeOptions', + 'MarqueeStartPolicy', + 'MarqueeState', + 'MarqueeUpdateStrategy', + 'Materialized', + 'Matrix2D', + 'MaxLinesMode', + 'MaxLinesOptions', + 'Measurable', + 'MeasureOptions', + 'MeasureResult', + 'MediaCachedImage', + 'MediaCachedImageAttribute', + 'Memo', + 'Menu', + 'MenuAlignType', + 'MenuAttribute', + 'MenuElement', + 'MenuItem', + 'MenuItemAttribute', + 'MenuItemConfiguration', + 'MenuItemGroup', + 'MenuItemGroupAttribute', + 'MenuItemGroupOptions', + 'MenuItemOptions', + 'MenuItemOptionsV2', + 'MenuMaskType', + 'MenuOnAppearCallback', + 'MenuOptions', + 'MenuOutlineOptions', + 'MenuPolicy', + 'MenuPreviewMode', + 'MenuType', + 'MessageLevel', + 'MixedMode', + 'ModalMode', + 'ModalTransition', + 'ModelType', + 'ModifierKey', + 'Monitor', + 'MonthData', + 'MoreButtonOptions', + 'MotionBlurAnchor', + 'MotionBlurOptions', + 'MotionPathOptions', + 'MouseAction', + 'MouseButton', + 'MouseEvent', + 'MoveIndex', + 'MultiShadowOptions', + 'MutableStyledString', + 'NativeEmbedDataInfo', + 'NativeEmbedInfo', + 'NativeEmbedStatus', + 'NativeEmbedTouchInfo', + 'NativeEmbedVisibilityInfo', + 'NativeMediaPlayerConfig', + 'NativeXComponentParameters', + 'NavBar', + 'NavBarPosition', + 'NavContentInfo', + 'NavDestination', + 'NavDestinationActiveReason', + 'NavDestinationAttribute', + 'NavDestinationCommonTitle', + 'NavDestinationContext', + 'NavDestinationCustomTitle', + 'NavDestinationInfo', + 'NavDestinationMode', + 'NavDestinationTransition', + 'NavExtender', + 'NavPathInfo', + 'NavPathStack', + 'NavRouteMode', + 'NavRouter', + 'NavRouterAttribute', + 'Navigation', + 'NavigationAnimatedTransition', + 'NavigationAttribute', + 'NavigationCommonTitle', + 'NavigationCustomTitle', + 'NavigationDividerStyle', + 'NavigationInfo', + 'NavigationInterception', + 'NavigationMenuItem', + 'NavigationMenuOptions', + 'NavigationMode', + 'NavigationOperation', + 'NavigationOptions', + 'NavigationSystemTransitionType', + 'NavigationTitleMode', + 'NavigationTitleOptions', + 'NavigationToolbarOptions', + 'NavigationTransitionProxy', + 'NavigationType', + 'Navigator', + 'NavigatorAttribute', + 'NestedScrollInfo', + 'NestedScrollMode', + 'NestedScrollOptions', + 'NestedScrollOptionsExt', + 'Node', + 'NodeContainer', + 'NodeContainerAttribute', + 'NodeController', + 'NonCurrentDayStyle', + 'Nullable', + 'ObjectLink', + 'ObscuredReasons', + 'Observed', + 'ObservedV2', + 'OffscreenCanvas', + 'OffscreenCanvasRenderingContext2D', + 'Offset', + 'OffsetOptions', + 'OffsetResult', + 'OnAdsBlockedCallback', + 'OnAlertEvent', + 'OnAlphabetIndexerPopupSelectCallback', + 'OnAlphabetIndexerRequestPopupDataCallback', + 'OnAlphabetIndexerSelectCallback', + 'OnAudioStateChangedEvent', + 'OnBeforeUnloadEvent', + 'OnCheckboxChangeCallback', + 'OnCheckboxGroupChangeCallback', + 'OnClientAuthenticationEvent', + 'OnConfirmEvent', + 'OnConsoleEvent', + 'OnContentScrollCallback', + 'OnContextMenuHideCallback', + 'OnContextMenuShowEvent', + 'OnDataResubmittedEvent', + 'OnDidChangeCallback', + 'OnDownloadStartEvent', + 'OnErrorReceiveEvent', + 'OnFaviconReceivedEvent', + 'OnFirstContentfulPaintEvent', + 'OnFirstMeaningfulPaintCallback', + 'OnFoldStatusChangeCallback', + 'OnFoldStatusChangeInfo', + 'OnFullScreenEnterCallback', + 'OnGeolocationShowEvent', + 'OnHoverStatusChangeCallback', + 'OnHttpAuthRequestEvent', + 'OnHttpErrorReceiveEvent', + 'OnIntelligentTrackingPreventionCallback', + 'OnInterceptRequestEvent', + 'OnLargestContentfulPaintCallback', + 'OnLinearIndicatorChangeCallback', + 'OnLoadInterceptEvent', + 'OnMoveHandler', + 'OnNativeEmbedVisibilityChangeCallback', + 'OnNativeLoadCallback', + 'OnNavigationEntryCommittedCallback', + 'OnOverScrollEvent', + 'OnOverrideUrlLoadingCallback', + 'OnPageBeginEvent', + 'OnPageEndEvent', + 'OnPageVisibleEvent', + 'OnPasteCallback', + 'OnPermissionRequestEvent', + 'OnProgressChangeEvent', + 'OnPromptEvent', + 'OnRefreshAccessedHistoryEvent', + 'OnRenderExitedEvent', + 'OnRenderProcessNotRespondingCallback', + 'OnRenderProcessRespondingCallback', + 'OnResourceLoadEvent', + 'OnSafeBrowsingCheckResultCallback', + 'OnScaleChangeEvent', + 'OnScreenCaptureRequestEvent', + 'OnScrollCallback', + 'OnScrollEdgeCallback', + 'OnScrollEvent', + 'OnScrollFrameBeginCallback', + 'OnScrollFrameBeginHandlerResult', + 'OnScrollVisibleContentChangeCallback', + 'OnSearchResultReceiveEvent', + 'OnShowFileSelectorEvent', + 'OnSslErrorEventCallback', + 'OnSslErrorEventReceiveEvent', + 'OnSubmitCallback', + 'OnSwiperAnimationEndCallback', + 'OnSwiperAnimationStartCallback', + 'OnSwiperGestureSwipeCallback', + 'OnTabsAnimationEndCallback', + 'OnTabsAnimationStartCallback', + 'OnTabsContentWillChangeCallback', + 'OnTabsGestureSwipeCallback', + 'OnTextSelectionChangeCallback', + 'OnTitleReceiveEvent', + 'OnTouchIconUrlReceivedEvent', + 'OnViewportFitChangedCallback', + 'OnWillScrollCallback', + 'OnWindowNewEvent', + 'Once', + 'OptionWidthMode', + 'Optional', + 'OutlineOptions', + 'OutlineRadiuses', + 'OutlineStyle', + 'OverScrollMode', + 'OverlayOffset', + 'OverlayOptions', + 'PX', + 'Padding', + 'PageFlipMode', + 'PageTransitionCallback', + 'PageTransitionEnter', + 'PageTransitionExit', + 'PageTransitionOptions', + 'PanDirection', + 'PanGesture', + 'PanGestureEvent', + 'PanGestureHandler', + 'PanGestureHandlerOptions', + 'PanGestureOptions', + 'PanGestureParams', + 'PanRecognizer', + 'Panel', + 'PanelAttribute', + 'PanelHeight', + 'PanelMode', + 'PanelType', + 'ParagraphStyle', + 'ParagraphStyleInterface', + 'Param', + 'Particle', + 'ParticleAnnulusRegion', + 'ParticleAttribute', + 'ParticleColorOptions', + 'ParticleColorPropertyOptions', + 'ParticleColorPropertyUpdaterConfigs', + 'ParticleColorUpdaterOptions', + 'ParticleConfigs', + 'ParticleEmitterShape', + 'ParticleOptions', + 'ParticlePropertyAnimation', + 'ParticlePropertyOptions', + 'ParticlePropertyUpdaterConfigs', + 'ParticleTuple', + 'ParticleType', + 'ParticleUpdater', + 'ParticleUpdaterOptions', + 'Particles', + 'PasswordIcon', + 'PasteButton', + 'PasteButtonAttribute', + 'PasteButtonOnClickResult', + 'PasteButtonOptions', + 'PasteDescription', + 'PasteEvent', + 'PasteEventCallback', + 'PasteIconStyle', + 'Path', + 'Path2D', + 'PathAttribute', + 'PathOptions', + 'PathShape', + 'PathShapeOptions', + 'PatternLock', + 'PatternLockAttribute', + 'PatternLockChallengeResult', + 'PatternLockController', + 'Percentage', + 'PerfMonitorActionType', + 'PerfMonitorSourceType', + 'PermissionRequest', + 'PersistPropsOptions', + 'PersistentStorage', + 'PickerBackgroundStyle', + 'PickerDialogButtonStyle', + 'PickerTextStyle', + 'PinchGesture', + 'PinchGestureEvent', + 'PinchGestureHandler', + 'PinchGestureHandlerOptions', + 'PinchGestureParams', + 'PinchRecognizer', + 'PixelMap', + 'PixelMapMock', + 'PixelRoundCalcPolicy', + 'PixelRoundMode', + 'PixelRoundPolicy', + 'PixelStretchEffectOptions', + 'PlaceholderStyle', + 'Placement', + 'PlayMode', + 'PlaybackInfo', + 'PlaybackSpeed', + 'PluginComponent', + 'PluginComponentAttribute', + 'PluginComponentOptions', + 'PluginComponentTemplate', + 'PluginErrorCallback', + 'PluginErrorData', + 'Point', + 'PointLightStyle', + 'PointParticleParameters', + 'PointerStyle', + 'Polygon', + 'PolygonAttribute', + 'PolygonOptions', + 'Polyline', + 'PolylineAttribute', + 'PolylineOptions', + 'PopInfo', + 'PopupBorderLinearGradient', + 'PopupCommonOptions', + 'PopupMaskType', + 'PopupMessageOptions', + 'PopupOptions', + 'PopupStateChangeParam', + 'Position', + 'PositionT', + 'PositionWithAffinity', + 'PosterOptions', + 'PreDragStatus', + 'PreparedInfo', + 'Preview', + 'PreviewConfiguration', + 'PreviewMenuOptions', + 'PreviewParams', + 'PreviewText', + 'Profiler', + 'Progress', + 'ProgressAttribute', + 'ProgressConfiguration', + 'ProgressMask', + 'ProgressOptions', + 'ProgressStatus', + 'ProgressStyle', + 'ProgressStyleMap', + 'ProgressStyleOptions', + 'ProgressType', + 'Prop', + 'ProtectedResourceType', + 'Provide', + 'ProvideOptions', + 'Provider', + 'PulseSymbolEffect', + 'QRCode', + 'QRCodeAttribute', + 'QuickReplaceSymbolEffect', + 'RRect', + 'RadialGradientOptions', + 'Radio', + 'RadioAttribute', + 'RadioConfiguration', + 'RadioIndicatorType', + 'RadioOptions', + 'RadioStyle', + 'Rating', + 'RatingAttribute', + 'RatingConfiguration', + 'RatingOptions', + 'RawFileDescriptor', + 'ReceiveCallback', + 'Rect', + 'RectAttribute', + 'RectHeightStyle', + 'RectOptions', + 'RectResult', + 'RectShape', + 'RectShapeOptions', + 'RectWidthStyle', + 'Rectangle', + 'Refresh', + 'RefreshAttribute', + 'RefreshOptions', + 'RefreshStatus', + 'RelateType', + 'RelativeContainer', + 'RelativeContainerAttribute', + 'RemoteWindow', + 'RemoteWindowAttribute', + 'RenderExitReason', + 'RenderFit', + 'RenderMode', + 'RenderProcessNotRespondingData', + 'RenderProcessNotRespondingReason', + 'RenderingContextSettings', + 'RepeatAttribute', + 'RepeatItem', + 'RepeatMode', + 'ReplaceSymbolEffect', + 'Require', + 'ResizableOptions', + 'ResolutionQuality', + 'Resource', + 'ResourceColor', + 'ResourceImageAttachmentOptions', + 'ResourceStr', + 'ResponseType', + 'RestrictedWorker', + 'Reusable', + 'ReusableV2', + 'ReuseOptions', + 'RichEditor', + 'RichEditorAttribute', + 'RichEditorBaseController', + 'RichEditorBuilderSpanOptions', + 'RichEditorChangeValue', + 'RichEditorController', + 'RichEditorDeleteDirection', + 'RichEditorDeleteValue', + 'RichEditorGesture', + 'RichEditorImageSpan', + 'RichEditorImageSpanOptions', + 'RichEditorImageSpanResult', + 'RichEditorImageSpanStyle', + 'RichEditorImageSpanStyleResult', + 'RichEditorInsertValue', + 'RichEditorLayoutStyle', + 'RichEditorOptions', + 'RichEditorParagraphResult', + 'RichEditorParagraphStyle', + 'RichEditorParagraphStyleOptions', + 'RichEditorRange', + 'RichEditorResponseType', + 'RichEditorSelection', + 'RichEditorSpan', + 'RichEditorSpanPosition', + 'RichEditorSpanStyleOptions', + 'RichEditorSpanType', + 'RichEditorStyledStringController', + 'RichEditorStyledStringOptions', + 'RichEditorSymbolSpanOptions', + 'RichEditorSymbolSpanStyle', + 'RichEditorSymbolSpanStyleResult', + 'RichEditorTextSpan', + 'RichEditorTextSpanOptions', + 'RichEditorTextSpanResult', + 'RichEditorTextStyle', + 'RichEditorTextStyleResult', + 'RichEditorUpdateImageSpanStyleOptions', + 'RichEditorUpdateSymbolSpanStyleOptions', + 'RichEditorUpdateTextSpanStyleOptions', + 'RichEditorUrlStyle', + 'RichText', + 'RichTextAttribute', + 'RingStyleOptions', + 'Root', + 'RootScene', + 'RootSceneAttribute', + 'RootSceneSession', + 'RotateOptions', + 'RotationGesture', + 'RotationGestureEvent', + 'RotationGestureHandler', + 'RotationGestureHandlerOptions', + 'RotationGestureParams', + 'RotationRecognizer', + 'RoundRectShapeOptions', + 'RoundedRectOptions', + 'RouteInfo', + 'RouteMapConfig', + 'RouteType', + 'RouterPageInfo', + 'Row', + 'RowAttribute', + 'RowOptions', + 'RowOptionsV2', + 'RowSplit', + 'RowSplitAttribute', + 'RuntimeType', + 'SafeAreaEdge', + 'SafeAreaType', + 'SaveButton', + 'SaveButtonAttribute', + 'SaveButtonOnClickResult', + 'SaveButtonOptions', + 'SaveDescription', + 'SaveIconStyle', + 'ScaleOptions', + 'ScaleRingStyleOptions', + 'ScaleSymbolEffect', + 'ScanEffectOptions', + 'Scene', + 'SceneOptions', + 'Screen', + 'ScreenAttribute', + 'ScreenCaptureConfig', + 'ScreenCaptureHandler', + 'ScriptItem', + 'Scroll', + 'ScrollAlign', + 'ScrollAnimationOptions', + 'ScrollAttribute', + 'ScrollBar', + 'ScrollBarAttribute', + 'ScrollBarDirection', + 'ScrollBarMargin', + 'ScrollBarOptions', + 'ScrollDirection', + 'ScrollEdgeOptions', + 'ScrollMotion', + 'ScrollOnScrollCallback', + 'ScrollOnWillScrollCallback', + 'ScrollOptions', + 'ScrollPageOptions', + 'ScrollResult', + 'ScrollSizeMode', + 'ScrollSnapAlign', + 'ScrollSnapOptions', + 'ScrollSource', + 'ScrollState', + 'ScrollToIndexOptions', + 'ScrollableBarModeOptions', + 'ScrollableCommonMethod', + 'ScrollableTargetInfo', + 'Scroller', + 'Search', + 'SearchAttribute', + 'SearchButtonOptions', + 'SearchController', + 'SearchOptions', + 'SearchSubmitCallback', + 'SearchType', + 'SectionOptions', + 'SecurityComponentLayoutDirection', + 'SecurityComponentMethod', + 'SeekMode', + 'Select', + 'SelectAttribute', + 'SelectOption', + 'SelectStatus', + 'SelectedMode', + 'SelectionMenuOptions', + 'SelectionMenuOptionsExt', + 'SelectionOptions', + 'Sendable', + 'Serializer', + 'ShadowOptions', + 'ShadowStyle', + 'ShadowType', + 'Shape', + 'ShapeAttribute', + 'ShapeSize', + 'SharedTransitionEffectType', + 'SheetDismiss', + 'SheetInfo', + 'SheetKeyboardAvoidMode', + 'SheetMode', + 'SheetOptions', + 'SheetSize', + 'SheetTitleOptions', + 'SheetType', + 'ShouldBuiltInRecognizerParallelWithCallback', + 'SideBarContainer', + 'SideBarContainerAttribute', + 'SideBarContainerType', + 'SideBarPosition', + 'Size', + 'SizeChangeCallback', + 'SizeOptions', + 'SizeResult', + 'SizeT', + 'SizeType', + 'SlideEffect', + 'SlideRange', + 'Slider', + 'SliderAttribute', + 'SliderBlockStyle', + 'SliderBlockType', + 'SliderChangeMode', + 'SliderConfiguration', + 'SliderCustomContentOptions', + 'SliderInteraction', + 'SliderOptions', + 'SliderPrefixOptions', + 'SliderShowStepOptions', + 'SliderStepItemAccessibility', + 'SliderStyle', + 'SliderSuffixOptions', + 'SliderTriggerChangeCallback', + 'SnapshotOptions', + 'SourceTool', + 'SourceType', + 'Span', + 'SpanAttribute', + 'SpanStyle', + 'SpringBackAction', + 'SpringMotion', + 'SpringProp', + 'SslError', + 'SslErrorEvent', + 'SslErrorHandler', + 'Stack', + 'StackAttribute', + 'StackOptions', + 'StarStyleOptions', + 'State', + 'StateStyles', + 'Stepper', + 'StepperAttribute', + 'StepperItem', + 'StepperItemAttribute', + 'Sticky', + 'StickyStyle', + 'Storage', + 'StorageLink', + 'StorageProp', + 'StyleOptions', + 'StyledString', + 'StyledStringChangeValue', + 'StyledStringChangedListener', + 'StyledStringController', + 'StyledStringKey', + 'StyledStringValue', + 'Styles', + 'SubMenuExpandingMode', + 'SubTabBarStyle', + 'SubmitCallback', + 'SubmitEvent', + 'SubscribaleAbstract', + 'SubscribedAbstractProperty', + 'Summary', + 'SuperscriptStyle', + 'SurfaceRect', + 'SurfaceRotationOptions', + 'SweepGradientOptions', + 'SwipeActionItem', + 'SwipeActionOptions', + 'SwipeActionState', + 'SwipeDirection', + 'SwipeEdgeEffect', + 'SwipeGesture', + 'SwipeGestureEvent', + 'SwipeGestureHandler', + 'SwipeGestureHandlerOptions', + 'SwipeGestureParams', + 'SwipeRecognizer', + 'Swiper', + 'SwiperAnimationEvent', + 'SwiperAnimationMode', + 'SwiperAttribute', + 'SwiperAutoFill', + 'SwiperContentAnimatedTransition', + 'SwiperContentTransitionProxy', + 'SwiperContentWillScrollResult', + 'SwiperController', + 'SwiperDisplayMode', + 'SwiperNestedScrollMode', + 'SwitchStyle', + 'SymbolEffect', + 'SymbolEffectStrategy', + 'SymbolGlyph', + 'SymbolGlyphAttribute', + 'SymbolGlyphModifier', + 'SymbolRenderingStrategy', + 'SymbolSpan', + 'SymbolSpanAttribute', + 'SyncedPropertyOneWay', + 'SyncedPropertyTwoWay', + 'SystemAdaptiveOptions', + 'SystemBarStyle', + 'SystemOps', + 'TabBarIconStyle', + 'TabBarOptions', + 'TabBarSymbol', + 'TabContent', + 'TabContentAnimatedTransition', + 'TabContentAttribute', + 'TabContentTransitionProxy', + 'Tabs', + 'TabsAnimationEvent', + 'TabsAttribute', + 'TabsCacheMode', + 'TabsController', + 'TabsCustomContentTransitionCallback', + 'TabsOptions', + 'Tag', + 'TapGesture', + 'TapGestureEvent', + 'TapGestureHandler', + 'TapGestureHandlerOptions', + 'TapGestureParameters', + 'TapGestureParams', + 'TapRecognizer', + 'TemplateOptions', + 'TerminationInfo', + 'Test', + 'Text', + 'TextAlign', + 'TextArea', + 'TextAreaAttribute', + 'TextAreaController', + 'TextAreaOptions', + 'TextAreaSubmitCallback', + 'TextAreaType', + 'TextAttribute', + 'TextBackgroundStyle', + 'TextBaseController', + 'TextBox', + 'TextCascadePickerRangeContent', + 'TextCase', + 'TextChangeOptions', + 'TextChangeReason', + 'TextClock', + 'TextClockAttribute', + 'TextClockConfiguration', + 'TextClockController', + 'TextClockOptions', + 'TextContentControllerBase', + 'TextContentControllerOptions', + 'TextContentStyle', + 'TextController', + 'TextDataDetectorConfig', + 'TextDataDetectorType', + 'TextDecorationOptions', + 'TextDecorationStyle', + 'TextDecorationType', + 'TextDeleteDirection', + 'TextEditControllerEx', + 'TextHeightAdaptivePolicy', + 'TextInput', + 'TextInputAttribute', + 'TextInputController', + 'TextInputOptions', + 'TextInputStyle', + 'TextMarqueeOptions', + 'TextMenuItem', + 'TextMenuItemId', + 'TextMenuOptions', + 'TextMenuShowMode', + 'TextMetrics', + 'TextModifier', + 'TextOptions', + 'TextOverflow', + 'TextOverflowOptions', + 'TextPicker', + 'TextPickerAttribute', + 'TextPickerDialog', + 'TextPickerDialogOptions', + 'TextPickerOptions', + 'TextPickerRangeContent', + 'TextPickerResult', + 'TextPickerTextStyle', + 'TextRange', + 'TextResponseType', + 'TextSelectableMode', + 'TextShadowStyle', + 'TextSpanType', + 'TextStyle', + 'TextTimer', + 'TextTimerAttribute', + 'TextTimerConfiguration', + 'TextTimerController', + 'TextTimerOptions', + 'Theme', + 'ThemeColorMode', + 'ThreatType', + 'TimePicker', + 'TimePickerAttribute', + 'TimePickerDialog', + 'TimePickerDialogOptions', + 'TimePickerFormat', + 'TimePickerOptions', + 'TimePickerResult', + 'TipsOptions', + 'TitleHeight', + 'TodayStyle', + 'Toggle', + 'ToggleAttribute', + 'ToggleConfiguration', + 'ToggleOptions', + 'ToggleType', + 'ToolBarItemAttribute', + 'ToolBarItemInterface', + 'ToolBarItemOptions', + 'ToolBarItemPlacement', + 'ToolbarItem', + 'ToolbarItemStatus', + 'TouchEvent', + 'TouchObject', + 'TouchPoint', + 'TouchResult', + 'TouchTestInfo', + 'TouchTestStrategy', + 'TouchType', + 'Trace', + 'Track', + 'TransitionEdge', + 'TransitionEffect', + 'TransitionEffects', + 'TransitionFinishCallback', + 'TransitionHierarchyStrategy', + 'TransitionOptions', + 'TransitionType', + 'TranslateOptions', + 'UICommonEvent', + 'UIContext', + 'UIExtensionComponent', + 'UIExtensionComponentAttribute', + 'UIExtensionOptions', + 'UIExtensionProxy', + 'UIGestureEvent', + 'UnderlineColor', + 'UnifiedData', + 'UniformDataType', + 'UrlStyle', + 'UserDataSpan', + 'VMContext', + 'VP', + 'VelocityOptions', + 'VerticalAlign', + 'Video', + 'VideoAttribute', + 'VideoController', + 'VideoOptions', + 'View', + 'ViewportFit', + 'ViewportRect', + 'VirtualScrollOptions', + 'Visibility', + 'VisibleAreaChangeCallback', + 'VisibleAreaEventOptions', + 'VisibleListContentInfo', + 'VisualEffect', + 'VoiceButtonOptions', + 'VoidCallback', + 'Want', + 'Watch', + 'WaterFlow', + 'WaterFlowAttribute', + 'WaterFlowLayoutMode', + 'WaterFlowOptions', + 'WaterFlowSections', + 'Web', + 'WebAttribute', + 'WebCaptureMode', + 'WebContextMenuParam', + 'WebContextMenuResult', + 'WebController', + 'WebCookie', + 'WebDarkMode', + 'WebElementType', + 'WebHeader', + 'WebKeyboardAvoidMode', + 'WebKeyboardCallback', + 'WebKeyboardCallbackInfo', + 'WebKeyboardController', + 'WebKeyboardOptions', + 'WebLayoutMode', + 'WebMediaOptions', + 'WebNavigationType', + 'WebOptions', + 'WebResourceError', + 'WebResourceRequest', + 'WebResourceResponse', + 'WebResponseType', + 'WebviewController', + 'Week', + 'WeekStyle', + 'WidthBreakpoint', + 'WindowAnimationTarget', + 'WindowModeFollowStrategy', + 'WindowScene', + 'WindowSceneAttribute', + 'WindowStatusType', + 'WithTheme', + 'WithThemeAttribute', + 'WithThemeOptions', + 'WordBreak', + 'WorkStateStyle', + 'WrappedBuilder', + 'XComponent', + 'XComponentAttribute', + 'XComponentController', + 'XComponentOptions', + 'XComponentType', + 'animateTo', + 'animateToImmediately', + 'cursorControl', + 'focusControl', + 'fp2px', + 'getContext', + 'getInspectorNodeById', + 'getInspectorNodes', + 'lpx2px', + 'postCardAction', + 'px2fp', + 'px2lpx', + 'px2vp', + 'setAppBgColor', + 'sharedTransitionOptions', + 'vp2px', +]); + +export const decoratorsWhiteList: string[] = [ + 'State', + 'Prop', + 'Link', + 'Observed', + 'Track', + 'ObjectLink', + 'StorageProp', + 'StorageLink', + 'LocalStorageProp', + 'LocalStorageLink', + 'Provide', + 'Consume', + 'Watch', + 'Require', +]; diff --git a/compiler/src/process_interop_ui.ts b/compiler/src/process_interop_ui.ts new file mode 100644 index 000000000..355ddd1be --- /dev/null +++ b/compiler/src/process_interop_ui.ts @@ -0,0 +1,325 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import ts from 'typescript'; + +import { EXTNAME_D_ETS } from './pre_define'; + +import { + whiteList, + decoratorsWhiteList, +} from './import_whiteList'; + +const fs = require('fs'); +const path = require('path'); + +function getDeclgenFiles(dir: string, filePaths: string[] = []) { + const files = fs.readdirSync(dir); + + files.forEach(file => { + const filePath = path.join(dir, file); + const stat = fs.statSync(filePath); + + if (stat.isDirectory()) { + getDeclgenFiles(filePath, filePaths); + } else if (stat.isFile() && file.endsWith(EXTNAME_D_ETS)) { + filePaths.push(filePath); + } + }); + + return filePaths; +} + +export function isStructDeclaration(node: ts.Node): boolean { + return ts.isStructDeclaration(node); +} + +function defaultCompilerOptions(): ts.CompilerOptions { + return { + target: ts.ScriptTarget.Latest, + module: ts.ModuleKind.CommonJS, + allowJs: true, + checkJs: true, + declaration: true, + emitDeclarationOnly: true, + noEmit: false + }; +} + +function getSourceFiles(program: ts.Program, filePaths: string[]): ts.SourceFile[] { + const sourceFiles: ts.SourceFile[] = []; + + filePaths.forEach(filePath => { + sourceFiles.push(program.getSourceFile(filePath)); + }); + + return sourceFiles; +} + +class HandleUIImports { + private context: ts.TransformationContext; + private typeChecker: ts.TypeChecker; + + private readonly outPath: string; + + private importedInterfaces: Set = new Set(); + private interfacesNeedToImport: Set = new Set(); + private printer = ts.createPrinter(); + + private readonly trueSymbolAtLocationCache = new Map(); + + constructor(program: ts.Program, context: ts.TransformationContext, outPath: string) { + this.context = context; + this.typeChecker = program.getTypeChecker(); + this.outPath = outPath; + } + + public createCustomTransformer(sourceFile: ts.SourceFile) { + this.extractImportedNames(sourceFile); + + return ts.visitNode(sourceFile, this.visitNode.bind(this)) + } + + private visitNode(node: ts.Node): ts.Node | undefined { + // TODO, declare struct => struct + if (node.parent && isStructDeclaration(node.parent) && ts.isModifier(node) && + node.kind === ts.SyntaxKind.DeclareKeyword) { + return; + } + + // TODO, build() => build() {} + if (node.parent && isStructDeclaration(node.parent) && ts.isMethodDeclaration(node) && + node.name && ts.isIdentifier(node.name) && node.name.escapedText.toString() === "build") { + return ts.factory.updateMethodDeclaration(node, + undefined, + undefined, + undefined, + node.name, + undefined, + undefined, + undefined, + undefined, + ts.factory.createBlock([], false) + ); + } + + // delete constructor + if (node.parent && isStructDeclaration(node.parent) && ts.isConstructorDeclaration(node)) { + return; + } + + // skip to collect origin import from 1.2 + if (ts.isImportDeclaration(node)) { + const moduleSpecifier = node.moduleSpecifier; + if (ts.isStringLiteral(moduleSpecifier)) { + const modulePath = moduleSpecifier.text; + if (['@ohos.arkui.stateManagement', '@ohos.arkui.component'].includes(modulePath)) { + return node; + } + } + } + + const result = ts.visitEachChild(node, this.visitNode.bind(this), this.context); + + if (ts.isIdentifier(result) && !this.shouldSkipIdentifier(result)) { + this.interfacesNeedToImport.add(result.text); + } else if (ts.isSourceFile(result)) { + this.AddUIImports(result); + } + + return result; + } + + private AddUIImports(node: ts.SourceFile): void { + const compImportSpecifiers: ts.ImportSpecifier[] = []; + const stateImportSpecifiers: ts.ImportSpecifier[] = []; + + this.interfacesNeedToImport.forEach((interfaceName) => { + if (this.importedInterfaces.has(interfaceName)) { + return; + } + const identifier = ts.factory.createIdentifier(interfaceName); + if (decoratorsWhiteList.includes(interfaceName)) { + stateImportSpecifiers.push(ts.factory.createImportSpecifier(false, undefined, identifier)); + } else { + compImportSpecifiers.push(ts.factory.createImportSpecifier(false, undefined, identifier)); + } + }); + + if (compImportSpecifiers.length + stateImportSpecifiers.length > 0) { + const newStatements = [...node.statements]; + + if (compImportSpecifiers.length) { + const moduleName = '@ohos.arkui.component'; + const compImportDeclaration = ts.factory.createImportDeclaration( + undefined, + ts.factory.createImportClause(false, + undefined, + ts.factory.createNamedImports( + compImportSpecifiers + ) + ), + ts.factory.createStringLiteral(moduleName, true), + undefined + ); + newStatements.splice(0, 0, compImportDeclaration); + } + + if (stateImportSpecifiers.length) { + const moduleName = '@ohos.arkui.stateManagement'; + const stateImportDeclaration = ts.factory.createImportDeclaration( + undefined, + ts.factory.createImportClause(false, + undefined, + ts.factory.createNamedImports( + stateImportSpecifiers + ) + ), + ts.factory.createStringLiteral(moduleName, true), + undefined + ); + newStatements.splice(0, 0, stateImportDeclaration); + } + + const updatedStatements = ts.factory.createNodeArray(newStatements); + const updatedSourceFile = ts.factory.updateSourceFile(node, + updatedStatements, + node.isDeclarationFile, + node.referencedFiles, + node.typeReferenceDirectives, + node.hasNoDefaultLib, + node.libReferenceDirectives + ); + + const updatedCode = this.printer.printFile(updatedSourceFile); + if (this.outPath) { + fs.writeFileSync(this.outPath, updatedCode); + } else { + fs.writeFileSync(updatedSourceFile.fileName, updatedCode); + } + } + } + + private getDeclarationNode(node: ts.Node): ts.Declaration | undefined { + const symbol = this.trueSymbolAtLocation(node); + return HandleUIImports.getDeclaration(symbol); + } + + static getDeclaration(tsSymbol: ts.Symbol | undefined): ts.Declaration | undefined { + if (tsSymbol?.declarations && tsSymbol.declarations.length > 0) { + return tsSymbol.declarations[0]; + } + + return undefined; + } + + private followIfAliased(symbol: ts.Symbol): ts.Symbol { + if ((symbol.getFlags() & ts.SymbolFlags.Alias) !== 0) { + return this.typeChecker.getAliasedSymbol(symbol); + } + + return symbol; + } + + private trueSymbolAtLocation(node: ts.Node): ts.Symbol | undefined { + const cache = this.trueSymbolAtLocationCache; + const val = cache.get(node); + + if (val !== undefined) { + return val !== null ? val : undefined; + } + + let symbol = this.typeChecker.getSymbolAtLocation(node); + + if (symbol === undefined) { + cache.set(node, null); + return undefined; + } + + symbol = this.followIfAliased(symbol); + cache.set(node, symbol); + + return symbol; + } + + private shouldSkipIdentifier(identifier: ts.Identifier): boolean { + const name = identifier.text; + const skippedList = new Set(['Extend', 'Styles']); + + if (skippedList.has(name)) { + return true; + } + + if (!whiteList.has(name)) { + return true; + } + + const symbol = this.typeChecker.getSymbolAtLocation(identifier); + if (symbol) { + const decl = this.getDeclarationNode(identifier); + if (decl?.getSourceFile() === identifier.getSourceFile()) { + return true; + } + } + + if (this.interfacesNeedToImport.has(name)) { + return true; + } + + return false; + } + + private extractImportedNames(sourceFile: ts.SourceFile): void { + for (const statement of sourceFile.statements) { + if (!ts.isImportDeclaration(statement)) { + continue; + } + + const importClause = statement.importClause; + if (!importClause) { + continue; + } + + const namedBindings = importClause.namedBindings; + if (!namedBindings || !ts.isNamedImports(namedBindings)) { + continue; + } + + for (const specifier of namedBindings.elements) { + const importedName = specifier.name.getText(sourceFile); + this.importedInterfaces.add(importedName); + } + } + } +} + +/** + * process interop ui + * + * @param path - declgenV2OutPath + */ +export function processInteropUI(path: string, outPath = ''): void { + const filePaths = getDeclgenFiles(path); + const program = ts.createProgram(filePaths, defaultCompilerOptions()); + const sourceFiles = getSourceFiles(program, filePaths); + + const createTransformer = (ctx: ts.TransformationContext): ts.Transformer => { + return (sourceFile: ts.SourceFile) => { + const handleUIImports = new HandleUIImports(program, ctx, outPath); + return handleUIImports.createCustomTransformer(sourceFile); + } + } + ts.transform(sourceFiles, [createTransformer]); +} diff --git a/compiler/test/interop_ui/demo/index.d.ets b/compiler/test/interop_ui/demo/index.d.ets new file mode 100644 index 000000000..12f8bb5ef --- /dev/null +++ b/compiler/test/interop_ui/demo/index.d.ets @@ -0,0 +1,24 @@ +/* + * 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. + */ +export declare const dynamicVar: Color; + +@Component +export declare struct DynamicComp { + @State + dynamicState: Color; + @Prop + dynamicProp: Color; + build(): void; +} diff --git a/compiler/test/interop_ui/package.json b/compiler/test/interop_ui/package.json new file mode 100644 index 000000000..f7a96f37c --- /dev/null +++ b/compiler/test/interop_ui/package.json @@ -0,0 +1,11 @@ +{ + "name": "interop_ui_test", + "version": "0.0.1", + "description": "test interop ui", + "private": true, + "scripts": { + "build": "npm run generateDeclarations && ./node_modules/.bin/babel ./src --out-dir lib --extensions .ts", + "build:test": "npm run build --prefix ../../../compiler && node ./test.js", + "test": "npm run build:test --prefix ./" + } +} diff --git a/compiler/test/interop_ui/test.js b/compiler/test/interop_ui/test.js new file mode 100644 index 000000000..228e45f53 --- /dev/null +++ b/compiler/test/interop_ui/test.js @@ -0,0 +1,23 @@ +/* + * 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. + */ + +const path = require('path'); + +const { processInteropUI } = require('../../lib/process_interop_ui'); + +const declgenV2OutPath = process.cwd() + '/demo'; +const outPath = path.join(declgenV2OutPath, '..' ,'transfromed_index.d.ets'); + +processInteropUI(declgenV2OutPath, outPath); -- Gitee From cc4552dd571c9702dbd0fb98f67ccc09bab1cdfc Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Mon, 7 Apr 2025 16:09:32 +0800 Subject: [PATCH 023/123] working on remove as __Options_xxx Signed-off-by: fengyuxin Change-Id: I2b5273d9250a2d247d5a224369e9d3f86f6ca36b --- .../ui-plugins/builder-lambda-transformer.ts | 127 +++++++++--------- .../ui-plugins/preprocessor-transform.ts | 28 +--- 2 files changed, 63 insertions(+), 92 deletions(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts index 16052ac2a..64184cbee 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts @@ -318,80 +318,77 @@ function createOrUpdateArgInBuilderLambda( isExternal?: boolean, typeName?: string, fallback?: arkts.AstNode -) { +): arkts.AstNode { if (!arg) { return fallback ?? arkts.factory.createUndefinedLiteral(); } if (arkts.isArrowFunctionExpression(arg)) { - const func: arkts.ScriptFunction = arg.scriptFunction; - const updateFunc = arkts.factory.updateScriptFunction( - func, - !!func.body && arkts.isBlockStatement(func.body) ? arkts.factory.updateBlock( - func.body, - func.body.statements.map( - (st) => updateContentBodyInBuilderLambda(st, isExternal) - ) - ) : undefined, - arkts.FunctionSignature.createFunctionSignature( - func.typeParams, - func.params, - func.returnTypeAnnotation, - false - ), - func.flags, - func.modifiers - ) - - return arkts.factory.updateArrowFunction( - arg, - updateFunc - ); + return processArgArrowFunction(arg, isExternal); } - - const isReusable: boolean = typeName - ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable - : false; - - if (arkts.isTSAsExpression(arg) && arg.expr && arkts.isObjectExpression(arg.expr)) { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); - const properties = arg.expr.properties as arkts.Property[]; - properties.forEach((prop, index) => { - if ( - prop.key && - prop.value && - arkts.isIdentifier(prop.key) && - arkts.isMemberExpression(prop.value) && - arkts.isThisExpression(prop.value.object) && - arkts.isIdentifier(prop.value.property) - ) { - const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; - if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { - properties[index] = arkts.Property.updateProperty( - prop, - arkts.factory.createIdentifier(backingField(prop.key.name)), - arkts.factory.updateMemberExpression( - prop.value, - prop.value.object, - arkts.factory.createIdentifier(backingField(prop.value.property.name)), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false, - ), - ); - } - } - }); - const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( - arg.expr, - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - properties, - false, - ); - return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); + if (arkts.isObjectExpression(arg)) { + return processArgObjectExpression(arg, typeName!); } return arg; } +function processArgArrowFunction( + arg: arkts.ArrowFunctionExpression, + isExternal?: boolean +): arkts.ArrowFunctionExpression { + const func: arkts.ScriptFunction = arg.scriptFunction; + const updateFunc = arkts.factory.updateScriptFunction( + func, + !!func.body && arkts.isBlockStatement(func.body) + ? arkts.factory.updateBlock( + func.body, + func.body.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) + ) + : undefined, + arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), + func.flags, + func.modifiers + ); + + return arkts.factory.updateArrowFunction(arg, updateFunc); +} + +function processArgObjectExpression(arg: arkts.ObjectExpression, typeName: string): arkts.ObjectExpression { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName); + const properties = arg.properties as arkts.Property[]; + properties.forEach((prop, index) => { + if ( + prop.key && + prop.value && + arkts.isIdentifier(prop.key) && + arkts.isMemberExpression(prop.value) && + arkts.isThisExpression(prop.value.object) && + arkts.isIdentifier(prop.value.property) + ) { + const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; + if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { + properties[index] = arkts.Property.updateProperty( + prop, + arkts.factory.createIdentifier(backingField(prop.key.name)), + arkts.factory.updateMemberExpression( + prop.value, + prop.value.object, + arkts.factory.createIdentifier(backingField(prop.value.property.name)), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + ); + } + } + }); + return arkts.ObjectExpression.updateObjectExpression( + arg, + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + properties, + false + ); +} + function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { let instanceCalls: arkts.CallExpression[] = []; let leaf: arkts.CallExpression = node; diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 627502e52..8c1ba3057 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -79,30 +79,6 @@ export class PreprocessorTransformer extends AbstractVisitor { return this.localComponentNames.includes(node.expression.name); } - transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { - if (arkts.isObjectExpression(node.arguments[0])) { - const componentName: string = - `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${node.expression.dumpSrc()}`; - const newArg = arkts.factory.createTSAsExpression( - node.arguments[0].clone(), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(componentName) - ) - ), - true - ); - return arkts.factory.updateCallExpression( - node, - node.expression, - node.typeArguments, - [newArg, ...node.arguments.slice(1)] - ).setTralingBlock(node.trailingBlock); - } else { - return node; - } - } - transformComponentFunctionCall(node: arkts.CallExpression) { if (!node || !arkts.isIdentifier(node.expression)) return node; @@ -271,9 +247,7 @@ export class PreprocessorTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); const newNode = this.visitEachChild(node) - if (arkts.isCallExpression(newNode) && this.isCustomConponentDecl(newNode)) { - return this.transformComponentCall(newNode); - } else if (arkts.isCallExpression(newNode) && this.isComponentFunctionCall(newNode)) { + if (arkts.isCallExpression(newNode) && this.isComponentFunctionCall(newNode)) { return this.transformComponentFunctionCall(newNode); } if (arkts.isETSImportDeclaration(node)) { this.addDependencesImport(node); -- Gitee From 466256d3a6c7a33ac40343063bd1ee2b049116fc Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Mon, 7 Apr 2025 22:43:08 +0800 Subject: [PATCH 024/123] update debugdump output dir w/ filename Signed-off-by: fengyuxin Change-Id: I3771a97773338183b4447ef0c3ff440f89b504b9 --- arkui-plugins/common/debug.ts | 7 +- arkui-plugins/common/program-visitor.ts | 9 +- arkui-plugins/memo-plugins/index.ts | 4 +- arkui-plugins/ui-plugins/index.ts | 8 +- koala-wrapper/native/src/bridges.cc | 28 +- koala-wrapper/src/Es2pandaNativeModule.ts | 649 ++++++++++++------- koala-wrapper/src/arkts-api/peers/Program.ts | 13 +- 7 files changed, 455 insertions(+), 263 deletions(-) diff --git a/arkui-plugins/common/debug.ts b/arkui-plugins/common/debug.ts index d01119195..3008ff789 100644 --- a/arkui-plugins/common/debug.ts +++ b/arkui-plugins/common/debug.ts @@ -33,12 +33,13 @@ function mkDir(filePath: string): void { fs.mkdirSync(filePath); } -export function debugDump(content: string, fileName: string, isInit: boolean, cachePath: string | undefined): void { +export function debugDump(content: string, fileName: string, isInit: boolean, cachePath: string | undefined, programFileName: string): void { if (!isDebugDump) return; const currentDirectory = process.cwd(); + const modifiedFileName = programFileName.replaceAll('.', '_'); const outputDir: string = cachePath - ? path.resolve(currentDirectory, cachePath) - : path.resolve(currentDirectory, 'dist', 'cache'); + ? path.resolve(currentDirectory, cachePath, modifiedFileName) + : path.resolve(currentDirectory, 'dist', 'cache', modifiedFileName); const filePath: string = path.resolve(outputDir, fileName); if (!fs.existsSync(outputDir)) { mkDir(outputDir); diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 937c503b6..4dcfc724f 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -120,7 +120,8 @@ export class ProgramVisitor extends AbstractVisitor { currProgram.astNode.dumpSrc(), getDumpFileName(this.state, "ORI", undefined, name), true, - cachePath + cachePath, + program.programFileNameWithExtension ); const script = this.visitor(currProgram.astNode, currProgram, name); if (script) { @@ -128,7 +129,8 @@ export class ProgramVisitor extends AbstractVisitor { script.dumpSrc(), getDumpFileName(this.state, this.pluginName, undefined, name), true, - cachePath + cachePath, + program.programFileNameWithExtension ); } } @@ -194,7 +196,8 @@ export class ProgramVisitor extends AbstractVisitor { script.dumpSrc(), getDumpFileName(this.state, this.pluginName, count, transformer.constructor.name), true, - this.pluginContext?.getProjectConfig()?.cachePath + this.pluginContext?.getProjectConfig()?.cachePath, + program!.programFileNameWithExtension ); count += 1; } diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index 4e0043833..369d12990 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -36,7 +36,7 @@ export function unmemoizeTransform(): Plugins { debugLog("[BEFORE MEMO SCRIPT] script: ", script.dumpSrc()); const cachePath: string | undefined = this.getProjectConfig()?.cachePath; - debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 5, "MEMO_AfterCheck_Begin"), true, cachePath); + debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 5, "MEMO_AfterCheck_Begin"), true, cachePath, program.programFileNameWithExtension); arkts.Performance.getInstance().createEvent("memo-checked"); @@ -65,7 +65,7 @@ export function unmemoizeTransform(): Plugins { arkts.Performance.getInstance().stopEvent("memo-checked", true); debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 6, "MEMO_AfterCheck_End"), true, cachePath); + debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 6, "MEMO_AfterCheck_End"), true, cachePath, program.programFileNameWithExtension); arkts.Performance.getInstance().createEvent("memo-recheck"); arkts.recheckSubtree(script); diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index 1ea707e6b..05dec1426 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -35,7 +35,7 @@ export function uiTransform(): Plugins { const cachePath: string | undefined = this.getProjectConfig()?.cachePath; debugLog('[BEFORE PARSED SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true, cachePath); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true, cachePath, program.programFileNameWithExtension); arkts.Performance.getInstance().createEvent("ui-parsed"); @@ -55,7 +55,7 @@ export function uiTransform(): Plugins { arkts.Performance.getInstance().stopEvent("ui-parsed", true); debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), true, cachePath); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), true, cachePath, program.programFileNameWithExtension); this.setArkTSAst(script); console.log('[UI PLUGIN] AFTER PARSED EXIT'); @@ -72,7 +72,7 @@ export function uiTransform(): Plugins { const cachePath: string | undefined = this.getProjectConfig()?.cachePath; debugLog('[BEFORE STRUCT SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true, cachePath); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true, cachePath, program.programFileNameWithExtension); arkts.Performance.getInstance().createEvent("ui-checked"); @@ -92,7 +92,7 @@ export function uiTransform(): Plugins { arkts.Performance.getInstance().stopEvent("ui-checked", true); debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true, cachePath); + debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true, cachePath, program.programFileNameWithExtension); arkts.GlobalInfo.getInfoInstance().reset(); arkts.Performance.getInstance().createEvent("ui-recheck"); diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index b341d79ab..5c177990e 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -344,4 +344,30 @@ KNativePointer impl_CreateETSStringLiteralType(KNativePointer contextPtr, KStrin const auto _str = getStringCopy(str); return GetImpl()->CreateETSStringLiteralType(context, _str); } -KOALA_INTEROP_2(CreateETSStringLiteralType, KNativePointer, KNativePointer, KStringPtr) \ No newline at end of file +KOALA_INTEROP_2(CreateETSStringLiteralType, KNativePointer, KNativePointer, KStringPtr) + +KNativePointer impl_ProgramFileNameConst(KNativePointer contextPtr, KNativePointer programPtr) +{ + auto context = reinterpret_cast(contextPtr); + auto program = reinterpret_cast(programPtr); + auto result = GetImpl()->ProgramFileNameConst(context, program); + return new std::string(result); +} +KOALA_INTEROP_2(ProgramFileNameConst, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_ProgramFileNameWithExtensionConst(KNativePointer contextPtr, KNativePointer programPtr) +{ + auto context = reinterpret_cast(contextPtr); + auto program = reinterpret_cast(programPtr); + auto result = GetImpl()->ProgramFileNameWithExtensionConst(context, program); + return new std::string(result); +} +KOALA_INTEROP_2(ProgramFileNameWithExtensionConst, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_ETSParserGetGlobalProgramAbsName(KNativePointer contextPtr) +{ + auto context = reinterpret_cast(contextPtr); + auto result = GetImpl()->ETSParserGetGlobalProgramAbsName(context); + return new std::string(result); +} +KOALA_INTEROP_1(ETSParserGetGlobalProgramAbsName, KNativePointer, KNativePointer) \ No newline at end of file diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index c68a445e5..3f271657a 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -20,642 +20,793 @@ import { KNativePointer, registerNativeModuleLibraryName, loadNativeModuleLibrary, - KDouble -} from "@koalaui/interop" -import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from "./generated/Es2pandaNativeModule" -import * as path from "path" + KDouble, +} from '@koalaui/interop'; +import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generated/Es2pandaNativeModule'; +import * as path from 'path'; // TODO: this type should be in interop -export type KPtrArray = BigUint64Array +export type KPtrArray = BigUint64Array; export class Es2pandaNativeModule { _ClassDefinitionSuper(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") - } - _CreateTSInterfaceDeclaration(_context: KPtr, _extends: KPtrArray, _extendsLen: KInt, _id: KPtr, _typeParams: KPtr, _body: KPtr, _isStatic: KBoolean, _isExternal: KBoolean): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + _CreateTSInterfaceDeclaration( + _context: KPtr, + _extends: KPtrArray, + _extendsLen: KInt, + _id: KPtr, + _typeParams: KPtr, + _body: KPtr, + _isStatic: KBoolean, + _isExternal: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _CreateTSTypeParameterInstantiation(context: KPtr, params: KPtrArray, paramsLen: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassElementKey(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassElementValue(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AnnotationUsageIrExpr(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AnnotationUsageIrPropertiesConst(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AnnotationAllowedAnnotations(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AnnotationAllowedAnnotationsConst(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeRebind(context: KPtr, node: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeRecheck(context: KPtr, node: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ContextState(context: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ContextErrorMessage(context: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeChildren(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ETSParserCreateExpression(context: KPtr, sourceCode: String, flags: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeDumpModifiers(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateAstDumper(context: KPtr, node: KPtr, source: String): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstDumperModifierToString(context: KPtr, dumper: KPtr, flags: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateConfig(argc: number, argv: string[]): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _DestroyConfig(config: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateContextFromString(config: KPtr, source: String, filename: String): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateContextFromFile(config: KPtr, filename: String): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _DestroyContext(context: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ProceedToState(context: KPtr, state: number): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ContextProgram(context: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ProgramAst(context: KPtr, program: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CheckerStartChecker(context: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VarBinderIdentifierAnalysis(context: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VarBinderInitTopScope(context: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VarBinderSetGenStdLib(context: KPtr, genStdLibT: KBoolean): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _SourceFileGetChildren(node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _BlockGetStatements(node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _FunctionDeclarationIsAnonymousConst(context: KPtr, node: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ExpressionStatementGetExpression(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CallExpressionArguments(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CallExpressionCallee(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IdentifierGetText(node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IdentifierIsPrivateIdentConst(context: KPtr, node: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _PropertyAccessExpressionGetExpression(node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _PropertyAccessExpressionGetName(node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _FunctionDeclarationFunction(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionSignature(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionParams(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionId(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionBody(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionAnnotations(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionSetIdent(context: KPtr, ast: KPtr, id: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionSetSignature(context: KPtr, ast: KPtr, signature: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionSetBody(context: KPtr, ast: KPtr, body: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionSetScope(context: KPtr, ast: KPtr, scope: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionSetAnnotations(context: KPtr, ast: KPtr, annotations: KPtrArray, annotationsLen: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionDeclareConst(context: KPtr, node: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionFlagsConst(context: KPtr, node: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionTypeParams(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionReturnTypeAnnotation(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScriptFunctionAddFlag(context: KPtr, node: KPtr, flags: KInt): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassPropertyAnnotations(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassPropertySetAnnotations(context: KPtr, ast: KPtr, annotations: KPtrArray, annotationsLen: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _UpdateBlockStatement(context: KPtr, original: KPtr, statementList: KPtrArray, statementListLen: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _BlockStatementSetScope(context: KPtr, node: KPtr, scope: KPtrArray): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateIdentifier1(context: KPtr, name: String): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateIdentifier2(context: KPtr, name: String, type_annotation: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IdentifierSetName(context: KPtr, node: KPtr, name: String): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IdentifierIdentifierFlags(context: KPtr, node: KPtr): KInt { - throw new Error("Not implemented") - } - _CreateFunctionDeclaration(context: KPtr, func: KPtr, annotations: KPtrArray, annotationsLen: KInt, isAnon: KBoolean): KPtr { - throw new Error("Not implemented") - } - _UpdateFunctionDeclaration(context: KPtr, node: KPtr, annotations: KPtrArray, annotationsLen: KInt, func: KPtr, isAnon: KBoolean): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + _CreateFunctionDeclaration( + context: KPtr, + func: KPtr, + annotations: KPtrArray, + annotationsLen: KInt, + isAnon: KBoolean + ): KPtr { + throw new Error('Not implemented'); + } + _UpdateFunctionDeclaration( + context: KPtr, + node: KPtr, + annotations: KPtrArray, + annotationsLen: KInt, + func: KPtr, + isAnon: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _CreateReturnStatement1(context: KPtr, argument: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ReturnStatementArgument(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateIfStatement(context: KPtr, test: KPtr, consequent: KPtr, alternate: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateBinaryExpression(context: KPtr, left: KPtr, right: KPtr, operatorType: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateAssignmentExpression(context: KPtr, left: KPtr, right: KPtr, assignmentOperator: KInt): KPtr { - throw new Error("Not implemented") - } - _CreateMethodDefinition(context: KPtr, kind: KInt, key: KPtr, value: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr { - throw new Error("Not implemented") - } - _CreateClassProperty(context: KPtr, key: KPtr, value: KPtr, typeAnnotation: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr { - throw new Error("Not implemented") - } - _CreateETSImportDeclaration(context: KPtr, source: KPtr, specifiers: KPtrArray, specifiersLen: KInt, importKind: KInt): KNativePointer { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + _CreateMethodDefinition( + context: KPtr, + kind: KInt, + key: KPtr, + value: KPtr, + modifiers: KInt, + isComputed: KBoolean + ): KPtr { + throw new Error('Not implemented'); + } + _CreateClassProperty( + context: KPtr, + key: KPtr, + value: KPtr, + typeAnnotation: KPtr, + modifiers: KInt, + isComputed: KBoolean + ): KPtr { + throw new Error('Not implemented'); + } + _CreateETSImportDeclaration( + context: KPtr, + source: KPtr, + specifiers: KPtrArray, + specifiersLen: KInt, + importKind: KInt + ): KNativePointer { + throw new Error('Not implemented'); } _ETSImportDeclarationSourceConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ETSImportDeclarationResolvedSource(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ETSImportDeclarationHasDeclConst(context: KPtr, node: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateImportSource(context: KPtr, source: KPtr, resolvedSource: KPtr, hasDecl: KBoolean): KNativePointer { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateImportSpecifier(context: KPtr, imported: KPtr, local: KPtr): KNativePointer { - throw new Error("Not implemented") - } - - _CreateFunctionSignature(context: KPtr, typeParams: KPtr, params: KPtrArray, paramsLen: KInt, returnTypeAnnotation: KPtr, hasReceiver: KBoolean): KPtr { - throw new Error("Not implemented") - } - _CreateScriptFunction(context: KPtr, databody: KPtr, datasignature: KPtr, datafuncFlags: KInt, dataflags: KInt): KPtr { - throw new Error("Not implemented") - } - _UpdateScriptFunction(context: KPtr, original: KPtr, databody: KPtr, datasignature: KPtr, datafuncFlags: KInt, dataflags: KInt, datadeclare: KBoolean): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + + _CreateFunctionSignature( + context: KPtr, + typeParams: KPtr, + params: KPtrArray, + paramsLen: KInt, + returnTypeAnnotation: KPtr, + hasReceiver: KBoolean + ): KPtr { + throw new Error('Not implemented'); + } + _CreateScriptFunction( + context: KPtr, + databody: KPtr, + datasignature: KPtr, + datafuncFlags: KInt, + dataflags: KInt + ): KPtr { + throw new Error('Not implemented'); + } + _UpdateScriptFunction( + context: KPtr, + original: KPtr, + databody: KPtr, + datasignature: KPtr, + datafuncFlags: KInt, + dataflags: KInt, + datadeclare: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _CreateBlockStatement(context: KPtr, statementList: KPtrArray, statementListLen: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeScopeConst(context: KPtr, ast: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeParent(context: KPtr, ast: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeSetParent(context: KPtr, ast: KPtr, parent: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeClone(context: KPtr, ast: KPtr, parent: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeModifiers(context: KPtr, ast: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeAddModifier(context: KPtr, ast: KPtr, flags: KInt): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeClearModifier(context: KPtr, ast: KPtr, flags: KInt): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeVariableConst(context: KPtr, ast: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeTypeConst(context: KPtr, ast: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _FunctionSignatureTypeParams(context: KPtr, ast: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _FunctionSignatureReturnType(context: KPtr, ast: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _FunctionSignatureParamsConst(context: KPtr, ast: KPtr, returnTypeLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _UpdateIdentifier1(context: KPtr, ast: KPtr, name: string): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _UpdateIdentifier2(context: KPtr, ast: KPtr, name: string, typeAnnotation: KPtr): KPtr { - throw new Error("Not implemented") - } - _UpdateMethodDefinition(context: KPtr, node: KPtr, kind: KInt, key: KPtr, value: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + _UpdateMethodDefinition( + context: KPtr, + node: KPtr, + kind: KInt, + key: KPtr, + value: KPtr, + modifiers: KInt, + isComputed: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _MethodDefinitionFunction(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _MethodDefinitionKindConst(context: KPtr, node: KPtr): KInt { - throw new Error("Not implemented") - } - - _CreateMemberExpression(context: KPtr, object: KPtr, property: KPtr, kind: KInt, computed: KBoolean, optional: KBoolean): KPtr { - throw new Error("Not implemented") - } - _UpdateMemberExpression(context: KPtr, node: KPtr, object: KPtr, property: KPtr, kind: KInt, computed: KBoolean, optional: KBoolean): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + + _CreateMemberExpression( + context: KPtr, + object: KPtr, + property: KPtr, + kind: KInt, + computed: KBoolean, + optional: KBoolean + ): KPtr { + throw new Error('Not implemented'); + } + _UpdateMemberExpression( + context: KPtr, + node: KPtr, + object: KPtr, + property: KPtr, + kind: KInt, + computed: KBoolean, + optional: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _MemberExpressionObject(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _MemberExpressionProperty(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _MemberExpressionKindConst(context: KPtr, node: KPtr): KInt { - throw new Error("Not implemented") - } - _CreateCallExpression(context: KPtr, callee: KPtr, args: KPtrArray, argsLen: KInt, typeParams: KPtr, optional: KBoolean, trailingComma: KBoolean): KPtr { - throw new Error("Not implemented") - } - _UpdateCallExpression(context: KPtr, node: KPtr, callee: KPtr, args: KPtrArray, argsLen: KInt, typeParams: KPtr, optional: KBoolean, trailingComma: KBoolean): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + _CreateCallExpression( + context: KPtr, + callee: KPtr, + args: KPtrArray, + argsLen: KInt, + typeParams: KPtr, + optional: KBoolean, + trailingComma: KBoolean + ): KPtr { + throw new Error('Not implemented'); + } + _UpdateCallExpression( + context: KPtr, + node: KPtr, + callee: KPtr, + args: KPtrArray, + argsLen: KInt, + typeParams: KPtr, + optional: KBoolean, + trailingComma: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _CreateArrowFunctionExpression(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _FunctionExpressionFunction(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ArrowFunctionExpressionFunction(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ArrowFunctionExpressionCreateTypeAnnotation(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateFunctionExpression(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _UpdateFunctionExpression(context: KPtr, original: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateExpressionStatement(context: KPtr, expr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _UpdateExpressionStatement(context: KPtr, node: KPtr, expr: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateETSParameterExpression(context: KPtr, identifier: KPtr, initializer: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateETSPrimitiveType(context: KPtr, type: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ETSPrimitiveTypeGetPrimitiveTypeConst(context: KPtr, node: KNativePointer): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateETSTypeReference(context: KPtr, part: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateETSTypeReferencePart(context: KPtr, name: KPtr, typeParams: KPtr, prev: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateETSTypeReferencePart1(context: KPtr, name: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsIdentifier(node: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IdentifierName(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ETSParameterExpressionIdent(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ETSParameterExpressionAnnotations(context: KPtr, node: KPtr, returnLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } - _ETSParameterExpressionSetAnnotations(context: KPtr, ast: KPtr, annotations: KPtrArray, annotationsLen: KInt): KPtr { - throw new Error("Not implemented") + _ETSParameterExpressionSetAnnotations( + context: KPtr, + ast: KPtr, + annotations: KPtrArray, + annotationsLen: KInt + ): KPtr { + throw new Error('Not implemented'); } _CreateTSTypeParameterDeclaration(context: KPtr, params: KPtrArray, paramsLen: KInt, requiredParams: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _TSTypeParameterDeclarationParamsConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateTSTypeParameter(context: KPtr, name: KPtr, constraint: KPtr, defaultType: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _TSTypeParameterName(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateTSUnionType(context: KPtr, types: KPtrArray, typesLen: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _TSUnionTypeTypesConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateETSUnionTypeIr(context: KPtr, types: KPtrArray, typesLen: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ETSUnionTypeIrTypesConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateVariableDeclaration(context: KPtr, kind: KInt, declarators: KPtrArray, declaratorsLen: KInt): KPtr { - throw new Error("Not implemented") - } - _UpdateVariableDeclaration(context: KPtr, original: KPtr, kind: KInt, declarators: KPtrArray, declaratorsLen: KInt, declare: KBoolean): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + _UpdateVariableDeclaration( + context: KPtr, + original: KPtr, + kind: KInt, + declarators: KPtrArray, + declaratorsLen: KInt, + declare: KBoolean + ): KPtr { + throw new Error('Not implemented'); } _CreateVariableDeclarator(context: KPtr, flag: KInt, ident: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VariableDeclarationDeclaratorsConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VariableDeclarationKindConst(context: KPtr, node: KPtr): KInt { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VariableDeclaratorId(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VariableDeclaratorSetInit(context: KPtr, node: KPtr, init: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateStringLiteral(context: KPtr, string: string): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateNumberLiteral(context: KPtr, value: KDouble): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _NumberLiteralStrConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _StringLiteralStrConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _BlockStatementStatements(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _BlockStatementSetStatements(context: KPtr, node: KPtr, statements: KPtrArray, statementsLen: KInt): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassDeclarationDefinition(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassDefinitionBody(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassDefinitionIdent(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassDefinitionTypeParamsConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateETSStructDeclaration(context: KPtr, def: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateClassDeclaration(context: KPtr, def: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _UpdateClassDeclaration(context: KPtr, original: KPtr, def: KPtr): KPtr { - throw new Error("Not implemented") - } - _CreateClassDefinition1(context: KPtr, ident: KPtr, body: KPtrArray, bodyLen: KInt, modifiers: KInt, flags: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + _CreateClassDefinition1( + context: KPtr, + ident: KPtr, + body: KPtrArray, + bodyLen: KInt, + modifiers: KInt, + flags: KInt + ): KPtr { + throw new Error('Not implemented'); } _ClassDefinitionSetTypeParams(context: KPtr, ast: KPtr, typeParams: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ClassDefinitionSetSuper(context: KPtr, ast: KPtr, superClass: KPtr): void { - throw new Error("Not implemented") - } - _UpdateClassDefinition1(context: KPtr, original: KPtr, ident: KPtr, body: KPtrArray, bodyLen: KInt, modifiers: KInt, flags: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); + } + _UpdateClassDefinition1( + context: KPtr, + original: KPtr, + ident: KPtr, + body: KPtrArray, + bodyLen: KInt, + modifiers: KInt, + flags: KInt + ): KPtr { + throw new Error('Not implemented'); } _CreateETSFunctionTypeIr(context: KPtr, signature: KPtr, funcFlags: KInt): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateSuperExpression(context: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _UpdateSuperExpression(context: KPtr, original: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsProgram(context: KPtr, node: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeDumpJSONConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeDumpEtsSrcConst(context: KPtr, node: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeUpdateChildren(context: KPtr, node: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeUpdateAll(context: KPtr, node: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeSetOriginalNode(context: KPtr, ast: KPtr, originalNode: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _AstNodeOriginalNodeConst(context: KPtr, ast: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VarBinderSetProgram(context: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VarBinderSetContext(context: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _VariableDeclaration(context: KPtr, variable: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _DeclNode(context: KPtr, decl: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ScopeSetParent(context: KPtr, ast: KPtr, scope: KPtr): void { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CallExpressionSignature(context: KPtr, classInstance: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _SignatureFunction(context: KPtr, classInstance: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _DeclarationFromIdentifier(context: KPtr, identifier: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsTSInterfaceDeclaration(ast: KNativePointer): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsAnnotationDeclaration(ast: KNativePointer): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsAnnotationUsage(ast: KNativePointer): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsClassProperty(ast: KNativePointer): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _CreateAnnotationUsageIr(context: KPtr, ast: KPtr): KPtr { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsETSUnionType(ast: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _IsETSFunctionType(ast: KPtr): KBoolean { - throw new Error("Not implemented") + throw new Error('Not implemented'); } _ProgramExternalSources(context: KNativePointer, instance: KNativePointer): KNativePointer { - throw new Error("Not implemented"); + throw new Error('Not implemented'); } _ExternalSourceName(instance: KNativePointer): KNativePointer { - throw new Error("Not implemented"); + throw new Error('Not implemented'); } _ExternalSourcePrograms(instance: KNativePointer): KNativePointer { - throw new Error("Not implemented"); + throw new Error('Not implemented'); } - _GenerateTsDeclarationsFromContext(config: KPtr, outputDeclEts: String, outputEts: String, exportAll: KBoolean): KPtr { - throw new Error("Not implemented"); + _GenerateTsDeclarationsFromContext( + config: KPtr, + outputDeclEts: String, + outputEts: String, + exportAll: KBoolean + ): KPtr { + throw new Error('Not implemented'); } - _InsertETSImportDeclarationAndParse(context: KNativePointer, program: KNativePointer, importDeclaration: KNativePointer): void { - throw new Error("Not implemented"); + _InsertETSImportDeclarationAndParse( + context: KNativePointer, + program: KNativePointer, + importDeclaration: KNativePointer + ): void { + throw new Error('Not implemented'); } _ETSParserGetImportPathManager(context: KNativePointer): KPtr { - throw new Error("Not implemented"); + throw new Error('Not implemented'); } _CreateSourcePosition(context: KNativePointer, index: KInt, line: KInt): KNativePointer { - throw new Error("Not implemented"); + throw new Error('Not implemented'); } _SourcePositionIndex(context: KNativePointer, instance: KNativePointer): KInt { - throw new Error("Not implemented"); + throw new Error('Not implemented'); } _SourcePositionLine(context: KNativePointer, instance: KNativePointer): KInt { - throw new Error("Not implemented"); + throw new Error('Not implemented'); } _CreateETSStringLiteralType(context: KNativePointer, str: String): KNativePointer { - throw new Error("Not implemented") - } + throw new Error('Not implemented'); + } _ClassDefinitionIsFromStructConst(context: KNativePointer, instance: KNativePointer): KBoolean { - throw new Error("Not implemented"); + throw new Error('Not implemented'); } _ClassDefinitionSetFromStructModifier(context: KNativePointer, instance: KNativePointer): void { - throw new Error("Not implemented"); + throw new Error('Not implemented'); + } + + _ProgramFileNameConst(context: KPtr, program: KPtr): KNativePointer { + throw new Error('Not implemented'); + } + + _ProgramFileNameWithExtensionConst(context: KPtr, program: KPtr): KNativePointer { + throw new Error('Not implemented'); + } + + _ETSParserGetGlobalProgramAbsName(context: KNativePointer): KNativePointer { + throw new Error('Not implemented'); } } export function initEs2panda(): Es2pandaNativeModule { - registerNativeModuleLibraryName("NativeModule", path.resolve(__dirname, "../native/es2panda.node")) - const instance = new Es2pandaNativeModule() - loadNativeModuleLibrary("NativeModule", instance) - return instance + registerNativeModuleLibraryName('NativeModule', path.resolve(__dirname, '../native/es2panda.node')); + const instance = new Es2pandaNativeModule(); + loadNativeModuleLibrary('NativeModule', instance); + return instance; } export function initGeneratedEs2panda(): GeneratedEs2pandaNativeModule { - registerNativeModuleLibraryName("NativeModule", path.resolve(__dirname, "../native/es2panda.node")) - const instance = new GeneratedEs2pandaNativeModule() + registerNativeModuleLibraryName('NativeModule', path.resolve(__dirname, '../native/es2panda.node')); + const instance = new GeneratedEs2pandaNativeModule(); // registerNativeModule("InteropNativeModule", NativeModule) - loadNativeModuleLibrary("NativeModule", instance) - return instance -} \ No newline at end of file + loadNativeModuleLibrary('NativeModule', instance); + return instance; +} diff --git a/koala-wrapper/src/arkts-api/peers/Program.ts b/koala-wrapper/src/arkts-api/peers/Program.ts index 6671cc8bb..5f3afbed2 100644 --- a/koala-wrapper/src/arkts-api/peers/Program.ts +++ b/koala-wrapper/src/arkts-api/peers/Program.ts @@ -21,7 +21,7 @@ import { EtsScript } from "../types" export class Program extends ArktsObject { constructor(peer: KNativePointer) { - super(peer) + super(peer); } get astNode(): EtsScript { @@ -35,6 +35,17 @@ export class Program extends ArktsObject { ); } + get programFileName(): string { + return unpackString(global.es2panda._ProgramFileNameConst(global.context, this.peer)); + } + + get programFileNameWithExtension(): string { + return unpackString(global.es2panda._ProgramFileNameWithExtensionConst(global.context, this.peer)); + } + + get programGlobalAbsName(): string { + return unpackString(global.es2panda._ETSParserGetGlobalProgramAbsName(global.context)); + } } export class ExternalSource extends ArktsObject { -- Gitee From 604e9f231b7160c887efa99df8e72466a87f69bf Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Tue, 8 Apr 2025 11:01:03 +0800 Subject: [PATCH 025/123] Revert "working on remove as __Options_xxx" This reverts commit cc4552dd571c9702dbd0fb98f67ccc09bab1cdfc. Signed-off-by: fengyuxin Change-Id: I5e88a980391c401304bb65ea6fa2bda990b76e6a --- .../ui-plugins/builder-lambda-transformer.ts | 19 +++++++------ .../ui-plugins/preprocessor-transform.ts | 28 ++++++++++++++++++- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts index 64184cbee..49207f00f 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-transformer.ts @@ -325,8 +325,8 @@ function createOrUpdateArgInBuilderLambda( if (arkts.isArrowFunctionExpression(arg)) { return processArgArrowFunction(arg, isExternal); } - if (arkts.isObjectExpression(arg)) { - return processArgObjectExpression(arg, typeName!); + if (arkts.isTSAsExpression(arg)) { + return processArgTSAsExpression(arg, typeName!); } return arg; } @@ -348,13 +348,15 @@ function processArgArrowFunction( func.flags, func.modifiers ); - return arkts.factory.updateArrowFunction(arg, updateFunc); } -function processArgObjectExpression(arg: arkts.ObjectExpression, typeName: string): arkts.ObjectExpression { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName); - const properties = arg.properties as arkts.Property[]; +function processArgTSAsExpression(arg: arkts.TSAsExpression, typeName: string): arkts.TSAsExpression { + if (!arg.expr || !arkts.isObjectExpression(arg.expr)) { + return arg; + } + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); + const properties = arg.expr.properties as arkts.Property[]; properties.forEach((prop, index) => { if ( prop.key && @@ -381,12 +383,13 @@ function processArgObjectExpression(arg: arkts.ObjectExpression, typeName: strin } } }); - return arkts.ObjectExpression.updateObjectExpression( - arg, + const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( + arg.expr, arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, properties, false ); + return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); } function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 8c1ba3057..627502e52 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -79,6 +79,30 @@ export class PreprocessorTransformer extends AbstractVisitor { return this.localComponentNames.includes(node.expression.name); } + transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { + if (arkts.isObjectExpression(node.arguments[0])) { + const componentName: string = + `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${node.expression.dumpSrc()}`; + const newArg = arkts.factory.createTSAsExpression( + node.arguments[0].clone(), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(componentName) + ) + ), + true + ); + return arkts.factory.updateCallExpression( + node, + node.expression, + node.typeArguments, + [newArg, ...node.arguments.slice(1)] + ).setTralingBlock(node.trailingBlock); + } else { + return node; + } + } + transformComponentFunctionCall(node: arkts.CallExpression) { if (!node || !arkts.isIdentifier(node.expression)) return node; @@ -247,7 +271,9 @@ export class PreprocessorTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); const newNode = this.visitEachChild(node) - if (arkts.isCallExpression(newNode) && this.isComponentFunctionCall(newNode)) { + if (arkts.isCallExpression(newNode) && this.isCustomConponentDecl(newNode)) { + return this.transformComponentCall(newNode); + } else if (arkts.isCallExpression(newNode) && this.isComponentFunctionCall(newNode)) { return this.transformComponentFunctionCall(newNode); } if (arkts.isETSImportDeclaration(node)) { this.addDependencesImport(node); -- Gitee From e375d6c6b08d2896f7d267c23768ccef8181ffdb Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Tue, 8 Apr 2025 15:55:01 +0800 Subject: [PATCH 026/123] update @reusable transform Signed-off-by: fengyuxin Change-Id: Ibc4472207c45a26f8d425ab886dbcb2c6cb5156b --- arkui-plugins/common/predefines.ts | 3 +- .../ui-plugins/component-transformer.ts | 193 ++++++++---------- 2 files changed, 82 insertions(+), 114 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 6b52253f7..22e3b03e7 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -28,7 +28,7 @@ export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ ]; export const IMPORT_SOURCE_MAP: Map> = new Map>([ - ["@ohos.arkui.component", new Set(["$r", "$rawfile", "ArkReusableStructBase", "Reusable", "_r", "_rawfile"])], + ["@ohos.arkui.component", new Set(["$r", "$rawfile", "_r", "_rawfile"])], ["@ohos.arkui.stateManagement", new Set([ "State", "Prop", @@ -71,7 +71,6 @@ export const OUTPUT_DEPENDENCY_MAP: Map = new Map, - reusableComps: Map } export class ComponentTransformer extends AbstractVisitor { @@ -73,7 +72,7 @@ export class ComponentTransformer extends AbstractVisitor { private entryNames: string[] = []; private reusableNames: string[] = []; private readonly arkui?: string; - private context: ComponentContext = { structMembers: new Map(), reusableComps: new Map()}; + private context: ComponentContext = { structMembers: new Map() }; private isCustomComponentImported: boolean = false; private isEntryPointImported: boolean = false; @@ -89,7 +88,7 @@ export class ComponentTransformer extends AbstractVisitor { this.componentInterfaceCollection = []; this.entryNames = []; this.reusableNames = []; - this.context = { structMembers: new Map(), reusableComps: new Map() }; + this.context = { structMembers: new Map() }; this.isCustomComponentImported = false; this.isEntryPointImported = false; } @@ -139,12 +138,10 @@ export class ComponentTransformer extends AbstractVisitor { const source: arkts.StringLiteral = arkts.factory.create1StringLiteral( this.arkui ?? CustomComponentNames.COMPONENT_DEFAULT_IMPORT ); - const imported: arkts.Identifier = arkts.factory.createIdentifier( - CustomComponentNames.COMPONENT_CLASS_NAME - ); + const imported: arkts.Identifier = arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_CLASS_NAME); // Insert this import at the top of the script's statements. if (!this.program) { - throw Error("Failed to insert import: Transformer has no program"); + throw Error('Failed to insert import: Transformer has no program'); } factory.createAndInsertImportDeclaration( source, @@ -156,11 +153,7 @@ export class ComponentTransformer extends AbstractVisitor { } processEtsScript(node: arkts.EtsScript): arkts.EtsScript { - if ( - this.isExternal - && this.componentInterfaceCollection.length === 0 - && this.entryNames.length === 0 - ) { + if (this.isExternal && this.componentInterfaceCollection.length === 0 && this.entryNames.length === 0) { return node; } let updateStatements: arkts.AstNode[] = []; @@ -173,56 +166,23 @@ export class ComponentTransformer extends AbstractVisitor { if (!this.isEntryPointImported) entryFactory.createAndInsertEntryPointImport(this.program); // TODO: normally, we should only have at most one @Entry component in a single file. // probably need to handle error message here. - updateStatements.push( - ...this.entryNames.map(entryFactory.generateEntryWrapper) - ); + updateStatements.push(...this.entryNames.map(entryFactory.generateEntryWrapper)); } if (updateStatements.length > 0) { - return arkts.factory.updateEtsScript( - node, - [ - ...node.statements, - ...updateStatements, - ] - ) + return arkts.factory.updateEtsScript(node, [...node.statements, ...updateStatements]); } return node; } - processReusableComponent(className: string) { - const first = arkts.factory.createClassProperty( - arkts.factory.createIdentifier("__class_name"), - undefined, - arkts.factory.createETSStringLiteralType(className), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - false - ) - const second = arkts.factory.createClassProperty( - arkts.factory.createIdentifier("__reuseId"), - undefined, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier("string") - ) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - false - ) - this.context.reusableComps.set(className, [first, second]) - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); - currentStructInfo.isReusable = true; - arkts.GlobalInfo.getInfoInstance().setStructInfo(className, currentStructInfo); - } - - createStaticMethod(definition: arkts.ClassDefinition):arkts.MethodDefinition { + createStaticMethod(definition: arkts.ClassDefinition): arkts.MethodDefinition { const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier( CustomComponentNames.OPTIONS, arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(getCustomComponentOptionsName(definition.ident!.name)) - ) + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(getCustomComponentOptionsName(definition.ident!.name)) ) + ) ), undefined ); @@ -236,8 +196,8 @@ export class ComponentTransformer extends AbstractVisitor { false ), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, - ) + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC + ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, @@ -245,10 +205,12 @@ export class ComponentTransformer extends AbstractVisitor { arkts.factory.createFunctionExpression(script), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, false - ) + ); } - processComponent(node: arkts.ClassDeclaration | arkts.StructDeclaration): arkts.ClassDeclaration | arkts.StructDeclaration { + processComponent( + node: arkts.ClassDeclaration | arkts.StructDeclaration + ): arkts.ClassDeclaration | arkts.StructDeclaration { const scopeInfo = this.scopeInfos[this.scopeInfos.length - 1]; const className = node.definition?.ident?.name; if (!className || scopeInfo?.name !== className) { @@ -261,33 +223,57 @@ export class ComponentTransformer extends AbstractVisitor { this.collectComponentMembers(node, className); } - if(scopeInfo.isReusable){ - this.processReusableComponent(className); + if (scopeInfo.isReusable) { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); + currentStructInfo.isReusable = true; + arkts.GlobalInfo.getInfoInstance().setStructInfo(className, currentStructInfo); } this.componentInterfaceCollection.push(this.generateComponentInterface(className, node.modifiers)); - const definition: arkts.ClassDefinition = node.definition; + const definition: arkts.ClassDefinition = node.definition!; const newDefinitionBody: arkts.AstNode[] = []; if (scopeInfo.isEntry) { this.entryNames.push(className); - const entryWithStorage: arkts.ClassProperty | undefined = + const entryWithStorage: arkts.ClassProperty | undefined = findEntryWithStorageInClassAnnotations(definition); if (!!entryWithStorage) { newDefinitionBody.push(entryFactory.createEntryLocalStorageInClass(entryWithStorage)); } } + const newDefinition: arkts.ClassDefinition = this.createNewDefinition( + node, + className, + definition, + newDefinitionBody + ); + + if (arkts.isStructDeclaration(node)) { + const _node = arkts.factory.createClassDeclaration(newDefinition); + _node.modifiers = node.modifiers; + return _node; + } else { + return arkts.factory.updateClassDeclaration(node, newDefinition); + } + } + createNewDefinition( + node: arkts.ClassDeclaration | arkts.StructDeclaration, + className: string, + definition: arkts.ClassDefinition, + newDefinitionBody: arkts.AstNode[] + ): arkts.ClassDefinition { const staticMethonBody: arkts.AstNode[] = []; - const hasExportFlag = (node.modifiers & arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT) === arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; + const hasExportFlag = + (node.modifiers & arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT) === + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; if (hasExportFlag) { - const buildCompatibleNode:arkts.MethodDefinition = this.createStaticMethod(definition); - if(!!buildCompatibleNode) { + const buildCompatibleNode: arkts.MethodDefinition = this.createStaticMethod(definition); + if (!!buildCompatibleNode) { staticMethonBody.push(buildCompatibleNode); } } - - const newDefinition = arkts.factory.updateClassDefinition( + return arkts.factory.updateClassDefinition( definition, definition.ident, undefined, @@ -296,56 +282,33 @@ export class ComponentTransformer extends AbstractVisitor { undefined, arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - scopeInfo.isReusable ? arkts.factory.createIdentifier('ArkReusableStructBase'): arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_CLASS_NAME), - arkts.factory.createTSTypeParameterInstantiation( - [ - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(className) + arkts.factory.createTSTypeParameterInstantiation([ + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(className)) + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier( + `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${className}` ) - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier( - `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${className}` - ) - ) - ), - ] - ) + ) + ), + ]) ) ), [...newDefinitionBody, ...definition.body, ...staticMethonBody], definition.modifiers, arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL - ) - - if (arkts.isStructDeclaration(node)) { - const _node = arkts.factory.createClassDeclaration(newDefinition); - _node.modifiers = node.modifiers; - return _node; - } else { - return arkts.factory.updateClassDeclaration( - node, - newDefinition - ) - } + ); } generateComponentInterface(name: string, modifiers: number): arkts.TSInterfaceDeclaration { const interfaceNode = arkts.factory.createInterfaceDeclaration( [], - arkts.factory.createIdentifier( - getCustomComponentOptionsName(name) - ), + arkts.factory.createIdentifier(getCustomComponentOptionsName(name)), nullptr, // TODO: wtf - arkts.factory.createInterfaceBody( - [ - ...(this.context.reusableComps.get(name) || []), - ...(this.context.structMembers.get(name) || []) - ] - ), + arkts.factory.createInterfaceBody([...(this.context.structMembers.get(name) || [])]), false, false ); @@ -358,11 +321,9 @@ export class ComponentTransformer extends AbstractVisitor { if (!this.context.structMembers.has(className)) { this.context.structMembers.set(className, []); } - node.definition.body.map(it => { + node.definition.body.map((it) => { if (arkts.isClassProperty(it)) { - this.context.structMembers.get(className)!.push( - ...this.createInterfaceInnerMember(it, structInfo) - ); + this.context.structMembers.get(className)!.push(...this.createInterfaceInnerMember(it, structInfo)); } }); arkts.GlobalInfo.getInfoInstance().setStructInfo(className, structInfo); @@ -376,22 +337,30 @@ export class ComponentTransformer extends AbstractVisitor { const hasStateManagementType = properties.length > 0; updateStructMetadata(structInfo, originalName, properties, member.modifiers, hasStateManagementType); - const originMember: arkts.ClassProperty = createOptionalClassProperty(originalName, member, - '', arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC); + const originMember: arkts.ClassProperty = createOptionalClassProperty( + originalName, + member, + '', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ); if (member.annotations.length > 0 && !hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { - const newMember: arkts.ClassProperty = createOptionalClassProperty(newName, member, - getStateManagementType(member), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC); + const newMember: arkts.ClassProperty = createOptionalClassProperty( + newName, + member, + getStateManagementType(member), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ); return [originMember, newMember]; } if (hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { - originMember.setAnnotations([annotation("memo")]); + originMember.setAnnotations([annotation('memo')]); } return [originMember]; } visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); - const newNode = this.visitEachChild(node) + const newNode = this.visitEachChild(node); if (arkts.isEtsScript(newNode)) { return this.processEtsScript(newNode); } @@ -400,6 +369,6 @@ export class ComponentTransformer extends AbstractVisitor { this.exit(newNode); return updateNode; } - return newNode + return newNode; } } -- Gitee From bcf636e426186f64bd2d0b23536e0172ed3bae93 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Fri, 4 Apr 2025 22:40:18 +0800 Subject: [PATCH 027/123] modify state variable transformation Signed-off-by: y00896775 Change-Id: I339366bdd5a21b68a35726107f48f5a43a1ec93c --- arkui-plugins/common/predefines.ts | 4 +- .../property-translators/factory.ts | 69 ++++++++++++ .../ui-plugins/property-translators/link.ts | 105 ++---------------- .../ui-plugins/property-translators/prop.ts | 2 +- .../ui-plugins/property-translators/state.ts | 2 +- .../ui-plugins/property-translators/utils.ts | 2 +- 6 files changed, 85 insertions(+), 99 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 6b52253f7..27ca51812 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -50,7 +50,7 @@ export const IMPORT_SOURCE_MAP: Map> = new Map = new Map): => { }`. + */ + static createArrowFunctionWithParamsAndBody( + typeParams: arkts.TSTypeParameterDeclaration | undefined, + params: arkts.Expression[] | undefined, + returnType: arkts.TypeNode | undefined, + hasReceiver: boolean, + bodyStatementsList: arkts.Statement[] + ): arkts.ArrowFunctionExpression { + return arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + arkts.BlockStatement.createBlockStatement(bodyStatementsList), + arkts.factory.createFunctionSignature( + typeParams, + params ? params : [], + returnType, + hasReceiver, + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ); + } + + /* + * create `initializers!.!.()`. + */ + static createBackingGetOrSetCall( + newName: string, + getOrSet: string, + args: arkts.AstNode[] | undefined + ): arkts.CallExpression { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true), + ), + arkts.factory.createIdentifier(getOrSet), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false, + ), + undefined, + args, + ); + } + + /* + * create `new ()`. + */ + static createNewDecoratedInstantiate( + className: string, + typeAnnotation: arkts.TypeNode | undefined, + args: arkts.Expression[] | undefined + ): arkts.ETSNewClassInstanceExpression { + return arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(className), + arkts.factory.createTSTypeParameterInstantiation( + typeAnnotation ? [typeAnnotation.clone()] : [], + ), + ), + ), + args?.length ? args : [], + ); + } } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/link.ts b/arkui-plugins/ui-plugins/property-translators/link.ts index c9e9ddbdd..cd63da7bd 100644 --- a/arkui-plugins/ui-plugins/property-translators/link.ts +++ b/arkui-plugins/ui-plugins/property-translators/link.ts @@ -48,104 +48,21 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon newName, ); - const first = arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - arkts.BlockStatement.createBlockStatement([ - arkts.factory.createReturnStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createIdentifier('initializers'), - ), - arkts.factory.createIdentifier(newName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false, - ), - ), - arkts.factory.createIdentifier('get'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false, - ), - undefined, - undefined, - ), - ), - ]), - arkts.factory.createFunctionSignature(undefined, [], undefined, false), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ), - ); - - const second = arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - arkts.BlockStatement.createBlockStatement([ - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createIdentifier('initializers'), - ), - arkts.factory.createIdentifier(newName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false, - ), - ), - arkts.factory.createIdentifier('set'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false, - ), - undefined, - [arkts.factory.createIdentifier('newValue')], - ), - ), - ]), - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.ETSParameterExpression.create( - arkts.factory.createIdentifier('newValue', this.property.typeAnnotation), - undefined, - ), - ], - undefined, - false, - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ), - ); - const consequent = arkts.BlockStatement.createBlockStatement([ arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(newName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false, - ), + generateThisBacking(newName, false, false), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('LinkDecoratedVariable'), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [], - ), - ), - ), - [first, second], - ), + factory.createNewDecoratedInstantiate( + 'LinkDecoratedVariable', + this.property.typeAnnotation, + [ + arkts.factory.create1StringLiteral(originalName), + arkts.factory.createTSNonNullExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true) + ) + ] + ) ), ), ]); diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts index 21942313f..d6b8f6173 100644 --- a/arkui-plugins/ui-plugins/property-translators/prop.ts +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -104,7 +104,7 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon ) ) ), - [this.property.value ? binaryItem : nonNullItem] + [arkts.factory.create1StringLiteral(originalName), this.property.value ? binaryItem : nonNullItem] ); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts index 718c22fab..40f4249f0 100644 --- a/arkui-plugins/ui-plugins/property-translators/state.ts +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -100,7 +100,7 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo ) ) ), - [binaryItem] + [arkts.factory.create1StringLiteral(originalName), binaryItem] ); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 1550eb3d0..393e0e4e3 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -64,7 +64,7 @@ export function getStateManagementType(node: arkts.ClassProperty): string { if (hasDecorator(node, DecoratorNames.STATE)) { return 'StateDecoratedVariable'; } else if (hasDecorator(node, DecoratorNames.LINK)) { - return 'DecoratedMutableVariable'; + return 'DecoratedV1VariableBase'; } else if (hasDecorator(node, DecoratorNames.PROP)) { return "PropDecoratedVariable"; } else if (hasDecorator(node, DecoratorNames.STORAGE_LINK)) { -- Gitee From 2c310aa9ae3a806377eb0e8aab8ea552e52f6d32 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Mon, 7 Apr 2025 21:14:37 +0800 Subject: [PATCH 028/123] develop Watch Signed-off-by: y00896775 Change-Id: I8909a7a16e2206cca54eceb00734408314a915c9 --- arkui-plugins/common/predefines.ts | 4 +- .../property-translators/factory.ts | 47 +++++++ .../ui-plugins/property-translators/index.ts | 36 ++--- .../ui-plugins/property-translators/link.ts | 23 +++- .../ui-plugins/property-translators/prop.ts | 12 +- .../ui-plugins/property-translators/state.ts | 7 +- .../property-translators/storageProp.ts | 14 +- .../property-translators/storagelink.ts | 14 +- .../ui-plugins/property-translators/utils.ts | 40 ++++++ .../ui-plugins/property-translators/watch.ts | 130 ------------------ 10 files changed, 149 insertions(+), 178 deletions(-) delete mode 100644 arkui-plugins/ui-plugins/property-translators/watch.ts diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 27ca51812..ccb36bac1 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -58,8 +58,7 @@ export const IMPORT_SOURCE_MAP: Map> = new Map = new Map([ @@ -75,6 +74,5 @@ export const OUTPUT_DEPENDENCY_MAP: Map = new Map {this.(propertyName)}. + */ + static createWatchCallback( + callbackName: string, + ): arkts.ArrowFunctionExpression { + return factory.createArrowFunctionWithParamsAndBody( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('_', UIFactory.createTypeReferenceFromString('string')), + undefined + ) + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, + [ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + factory.generateThisCall(callbackName), + undefined, + [arkts.factory.createIdentifier('_')] + ) + ) + ] + ); + } + + /* + * create this. with optional or nonNullable. + */ + static generateThisCall( + name: string, + optional: boolean = false, + nonNull: boolean = false, + ): arkts.Expression { + const member: arkts.Expression = arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(`${name}`), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + optional, + ); + return nonNull ? arkts.factory.createTSNonNullExpression(member) : member; + } + /* * create `initializers!.!.()`. */ diff --git a/arkui-plugins/ui-plugins/property-translators/index.ts b/arkui-plugins/ui-plugins/property-translators/index.ts index 7062476af..697ff38e3 100644 --- a/arkui-plugins/ui-plugins/property-translators/index.ts +++ b/arkui-plugins/ui-plugins/property-translators/index.ts @@ -21,7 +21,6 @@ import { StateTranslator } from './state'; import { PropTranslator } from './prop'; import { StorageLinkTranslator } from './storagelink'; import { LocalStorageLinkTranslator } from './localstoragelink'; -import { WatchTranslator } from './watch'; import { LinkTranslator } from './link'; import { ObjectLinkTranslator } from './objectlink'; import { LocalStoragePropTranslator } from './localstorageprop'; @@ -37,53 +36,42 @@ export { PropertyTranslator }; export function classifyProperty( member: arkts.AstNode, - structName: string, - skipDecorator?: DecoratorNames[], + structName: string ): PropertyTranslator | undefined { if (!arkts.isClassProperty(member)) return undefined; if (isStatic(member)) return new staticPropertyTranslator(member, structName); - if (!skipDecorator?.includes(DecoratorNames.WATCH) && hasDecorator(member, DecoratorNames.WATCH)) { - return new WatchTranslator(member, structName, classifyProperty(member, structName, [DecoratorNames.WATCH])); - } - - if (!skipDecorator?.includes(DecoratorNames.STATE) && hasDecorator(member, DecoratorNames.STATE)) { + if (hasDecorator(member, DecoratorNames.STATE)) { return new StateTranslator(member, structName); } - if (!skipDecorator?.includes(DecoratorNames.STORAGE_LINK) && hasDecorator(member, DecoratorNames.STORAGE_LINK)) { + if (hasDecorator(member, DecoratorNames.STORAGE_LINK)) { return new StorageLinkTranslator(member, structName); } - if ( - !skipDecorator?.includes(DecoratorNames.LOCAL_STORAGE_LINK) && - hasDecorator(member, DecoratorNames.LOCAL_STORAGE_LINK) - ) { + if (hasDecorator(member, DecoratorNames.LOCAL_STORAGE_LINK)) { return new LocalStorageLinkTranslator(member, structName); } - if (!skipDecorator?.includes(DecoratorNames.LINK) && hasDecorator(member, DecoratorNames.LINK)) { + if (hasDecorator(member, DecoratorNames.LINK)) { return new LinkTranslator(member, structName); } - if (!skipDecorator?.includes(DecoratorNames.OBJECT_LINK) && hasDecorator(member, DecoratorNames.OBJECT_LINK)) { + if (hasDecorator(member, DecoratorNames.OBJECT_LINK)) { return new ObjectLinkTranslator(member, structName); } - if ( - !skipDecorator?.includes(DecoratorNames.LOCAL_STORAGE_PROP) && - hasDecorator(member, DecoratorNames.LOCAL_STORAGE_PROP) - ) { + if (hasDecorator(member, DecoratorNames.LOCAL_STORAGE_PROP)) { return new LocalStoragePropTranslator(member, structName); } - if (!skipDecorator?.includes(DecoratorNames.STORAGE_PROP) && hasDecorator(member, DecoratorNames.STORAGE_PROP)) { + if (hasDecorator(member, DecoratorNames.STORAGE_PROP)) { return new StoragePropTranslator(member, structName); } - if (!skipDecorator?.includes(DecoratorNames.PROP) && hasDecorator(member, DecoratorNames.PROP)) { + if (hasDecorator(member, DecoratorNames.PROP)) { return new PropTranslator(member, structName); } - if (!skipDecorator?.includes(DecoratorNames.PROVIDE) && hasDecorator(member, DecoratorNames.PROVIDE)) { + if (hasDecorator(member, DecoratorNames.PROVIDE)) { return new ProvideTranslator(member, structName); } - if (!skipDecorator?.includes(DecoratorNames.CONSUME) && hasDecorator(member, DecoratorNames.CONSUME)) { + if (hasDecorator(member, DecoratorNames.CONSUME)) { return new ConsumeTranslator(member, structName); } - if (!skipDecorator?.includes(DecoratorNames.BUILDER_PARAM) && hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { + if (hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { return new BuilderParamTranslator(member, structName); } diff --git a/arkui-plugins/ui-plugins/property-translators/link.ts b/arkui-plugins/ui-plugins/property-translators/link.ts index cd63da7bd..fb3740f74 100644 --- a/arkui-plugins/ui-plugins/property-translators/link.ts +++ b/arkui-plugins/ui-plugins/property-translators/link.ts @@ -15,7 +15,14 @@ import * as arkts from '@koalaui/libarkts'; -import { generateToRecord, createGetter, createSetter2, generateThisBacking, generateGetOrSetCall } from './utils'; +import { + generateToRecord, + createGetter, + createSetter2, + generateThisBacking, + generateGetOrSetCall, + judgeIfAddWatchFunc +} from './utils'; import { PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; @@ -48,6 +55,13 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon newName, ); + const args: arkts.Expression[] = [ + arkts.factory.create1StringLiteral(originalName), + arkts.factory.createTSNonNullExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true) + ) + ]; + judgeIfAddWatchFunc(args, this.property); const consequent = arkts.BlockStatement.createBlockStatement([ arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( @@ -56,12 +70,7 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon factory.createNewDecoratedInstantiate( 'LinkDecoratedVariable', this.property.typeAnnotation, - [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true) - ) - ] + args ) ), ), diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts index d6b8f6173..356863eda 100644 --- a/arkui-plugins/ui-plugins/property-translators/prop.ts +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -16,10 +16,12 @@ import * as arkts from "@koalaui/libarkts" import { + generateToRecord, createGetter, createSetter2, generateGetOrSetCall, - generateThisBacking + generateThisBacking, + judgeIfAddWatchFunc } from "./utils"; import { PropertyTranslator } from "./base"; import { @@ -49,6 +51,10 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon const updateStruct: arkts.AstNode = this.generateUpdateStruct(mutableThis, originalName); currentStructInfo.initializeBody.push(initializeStruct); currentStructInfo.updateBody.push(updateStruct); + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } @@ -95,6 +101,8 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon ); const nonNullItem =arkts.factory.createTSNonNullExpression( factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true)); + const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), this.property.value ? binaryItem : nonNullItem]; + judgeIfAddWatchFunc(args, this.property); const right = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( @@ -104,7 +112,7 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon ) ) ), - [arkts.factory.create1StringLiteral(originalName), this.property.value ? binaryItem : nonNullItem] + args ); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts index 40f4249f0..d612a128f 100644 --- a/arkui-plugins/ui-plugins/property-translators/state.ts +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -20,7 +20,8 @@ import { createGetter, createSetter2, generateThisBacking, - generateGetOrSetCall + generateGetOrSetCall, + judgeIfAddWatchFunc } from "./utils"; import { PropertyTranslator } from "./base"; import { @@ -91,6 +92,8 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo this.property.value ?? arkts.factory.createIdentifier('undefined'), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ); + const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), binaryItem]; + judgeIfAddWatchFunc(args, this.property); const right = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( @@ -100,7 +103,7 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo ) ) ), - [arkts.factory.create1StringLiteral(originalName), binaryItem] + args ); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), diff --git a/arkui-plugins/ui-plugins/property-translators/storageProp.ts b/arkui-plugins/ui-plugins/property-translators/storageProp.ts index 797e9acb8..c3f17c276 100644 --- a/arkui-plugins/ui-plugins/property-translators/storageProp.ts +++ b/arkui-plugins/ui-plugins/property-translators/storageProp.ts @@ -25,6 +25,7 @@ import { createSetter2, generateThisBacking, generateGetOrSetCall, + judgeIfAddWatchFunc } from './utils'; import { createOptionalClassProperty } from '../utils'; @@ -85,6 +86,13 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial throw new Error('StorageProp required only one value!!'); // TODO: replace this with proper error message. } + const args: arkts.Expression[] = [ + arkts.factory.createStringLiteral(storagePropValueStr), + arkts.factory.create1StringLiteral(originalName), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + ]; + judgeIfAddWatchFunc(args, this.property); + const newClass = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( @@ -94,11 +102,7 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial ), ), ), - [ - arkts.factory.createStringLiteral(storagePropValueStr), - arkts.factory.create1StringLiteral(originalName), - this.property.value ?? arkts.factory.createIdentifier('undefined'), - ], + args ); return arkts.factory.createAssignmentExpression( diff --git a/arkui-plugins/ui-plugins/property-translators/storagelink.ts b/arkui-plugins/ui-plugins/property-translators/storagelink.ts index 25720833d..a2f69a239 100644 --- a/arkui-plugins/ui-plugins/property-translators/storagelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/storagelink.ts @@ -25,6 +25,7 @@ import { createSetter2, generateThisBacking, generateGetOrSetCall, + judgeIfAddWatchFunc } from './utils'; import { createOptionalClassProperty } from '../utils'; @@ -85,6 +86,13 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial throw new Error('StorageLink required only one value!!'); // TODO: replace this with proper error message. } + const args: arkts.Expression[] = [ + arkts.factory.createStringLiteral(storageLinkValueStr), + arkts.factory.create1StringLiteral(originalName), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + ]; + judgeIfAddWatchFunc(args, this.property); + const newClass = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( @@ -94,11 +102,7 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial ), ), ), - [ - arkts.factory.createStringLiteral(storageLinkValueStr), - arkts.factory.create1StringLiteral(originalName), - this.property.value ?? arkts.factory.createIdentifier('undefined'), - ], + args ); return arkts.factory.createAssignmentExpression( diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 393e0e4e3..df3f93414 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -220,6 +220,46 @@ export function getValueInAnnotation(node: arkts.ClassProperty, decoratorName: D return undefined; } +function getWatchValueStr(node: arkts.AstNode): string | undefined { + if (!arkts.isClassProperty(node) || !node.value) { + return undefined; + } + return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +} + +function getWatchAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { + const isWatchAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.WATCH; + + if (isWatchAnnotation && anno.properties.length === 1) { + return getWatchValueStr(anno.properties.at(0)!); + } + return undefined; +} + +function getWatchValueInAnnotation(node: arkts.ClassProperty): string | undefined { + const annotations: readonly arkts.AnnotationUsage[] = node.annotations; + + for (let i = 0; i < annotations.length; i++) { + const anno: arkts.AnnotationUsage = annotations[i]; + const str: string | undefined = getWatchAnnotationValue(anno); + if (!!str) { + return str; + } + } + + return undefined; +} + +export function judgeIfAddWatchFunc(args: arkts.Expression[], property: arkts.ClassProperty): void { + if (hasDecorator(property, DecoratorNames.WATCH)) { + const watchStr: string | undefined = getWatchValueInAnnotation(property); + if (watchStr) { + args.push(factory.createWatchCallback(watchStr)); + } + } +} + export function generateGetOrSetCall(beforCall: arkts.AstNode, type: string) { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( diff --git a/arkui-plugins/ui-plugins/property-translators/watch.ts b/arkui-plugins/ui-plugins/property-translators/watch.ts deleted file mode 100644 index cd097b3a7..000000000 --- a/arkui-plugins/ui-plugins/property-translators/watch.ts +++ /dev/null @@ -1,130 +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. - */ - -import * as arkts from '@koalaui/libarkts'; - -import { backingField, expectName } from '../../common/arkts-utils'; -import { PropertyTranslator } from './base'; -import { InitializerConstructor } from './types'; -import { DecoratorNames } from './utils'; - -export class WatchTranslator extends PropertyTranslator implements InitializerConstructor { - constructor( - protected property: arkts.ClassProperty, - protected structName: string, - protected translator?: PropertyTranslator, - ) { - super(property, structName); - } - - translateMember(): arkts.AstNode[] { - const allNodes = this.translator?.translateMember(); - - if (!allNodes) { - // ONLY @WATCH, THROW ERROR - throw new Error('@Watch decorator must be used with other statemanagement decorators'); - } - - const originalName: string = expectName(this.property.key); - const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); - - return allNodes; - } - - cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); - const updateStruct: arkts.AstNode = this.generateUpdateStruct(newName, originalName); - currentStructInfo.updateBody.push(updateStruct); - } - - translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - throw new Error('Method not implemented.'); - } - - generateUpdateStruct(newName: string, originalName: string): arkts.AstNode { - const first = arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - this.property.key!, - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false, - ); - const body = arkts.factory.createBlock([ - arkts.factory.createReturnStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(getWatchValueInAnnotation(this.property)!), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false, - ), - undefined, - [arkts.factory.createStringLiteral(originalName)], - ), - ), - ]); - - const params = [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('_', this.property.typeAnnotation), - undefined, - ), - ]; - - const second = arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - body, - arkts.FunctionSignature.createFunctionSignature(undefined, params, undefined, false), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - ), - ); - - return arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(arkts.factory.createIdentifier('OnChange'), undefined, [first, second]), - ); - } -} - -function getWatchValueStr(node: arkts.AstNode): string | undefined { - if (!arkts.isClassProperty(node) || !node.value) return undefined; - return arkts.isStringLiteral(node.value) ? node.value.str : undefined; -} - -function getWatchAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { - const isWatchAnnotation: boolean = - !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.WATCH; - - if (isWatchAnnotation && anno.properties.length === 1) { - return getWatchValueStr(anno.properties.at(0)!); - } - return undefined; -} - -function getWatchValueInAnnotation(node: arkts.ClassProperty): string | undefined { - const annotations: readonly arkts.AnnotationUsage[] = node.annotations; - - for (let i = 0; i < annotations.length; i++) { - const anno: arkts.AnnotationUsage = annotations[i]; - const str: string | undefined = getWatchAnnotationValue(anno); - if (!!str) { - return str; - } - } - - return undefined; -} -- Gitee From 8e66d35e6de8ec63ec95a579af553c08e60f6516 Mon Sep 17 00:00:00 2001 From: Nazarov Konstantin Date: Wed, 19 Mar 2025 17:52:26 +0800 Subject: [PATCH 029/123] Remove removed APIs from frontend Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/IBQD77 Change-Id: I721e26f13fe81677a1d86773cadd16d462e7a451 Signed-off-by: Nazarov Konstantin --- koala-wrapper/native/src/generated/bridges.cc | 37 -- koala-wrapper/src/Es2pandaEnums.ts | 1 - koala-wrapper/src/generated/Es2pandaEnums.ts | 367 +++++++++--------- .../src/generated/Es2pandaNativeModule.ts | 14 +- koala-wrapper/src/generated/index.ts | 3 +- koala-wrapper/src/generated/node-map.ts | 305 ++++++++------- .../src/generated/peers/AnnotationUsage.ts | 8 +- .../peers/ArrowFunctionExpression.ts | 8 +- .../src/generated/peers/AssertStatement.ts | 8 +- .../src/generated/peers/AwaitExpression.ts | 8 +- .../src/generated/peers/BigIntLiteral.ts | 8 +- .../src/generated/peers/BinaryExpression.ts | 8 +- .../src/generated/peers/BlockExpression.ts | 8 +- .../src/generated/peers/BlockStatement.ts | 8 +- .../src/generated/peers/BooleanLiteral.ts | 8 +- .../src/generated/peers/BreakStatement.ts | 8 +- .../src/generated/peers/CallExpression.ts | 8 +- .../src/generated/peers/CatchClause.ts | 8 +- .../src/generated/peers/ChainExpression.ts | 8 +- .../src/generated/peers/CharLiteral.ts | 8 +- .../src/generated/peers/ClassDeclaration.ts | 8 +- .../src/generated/peers/ClassDefinition.ts | 8 +- .../src/generated/peers/ClassExpression.ts | 8 +- .../src/generated/peers/ClassProperty.ts | 8 +- .../src/generated/peers/ClassStaticBlock.ts | 8 +- .../generated/peers/ConditionalExpression.ts | 8 +- .../src/generated/peers/ContinueStatement.ts | 8 +- .../src/generated/peers/DebuggerStatement.ts | 8 +- .../src/generated/peers/Decorator.ts | 8 +- .../generated/peers/DirectEvalExpression.ts | 8 +- .../src/generated/peers/DoWhileStatement.ts | 8 +- .../src/generated/peers/ETSClassLiteral.ts | 8 +- .../src/generated/peers/ETSFunctionType.ts | 8 +- .../generated/peers/ETSImportDeclaration.ts | 8 +- .../generated/peers/ETSLaunchExpression.ts | 55 --- .../src/generated/peers/ETSModule.ts | 8 +- .../peers/ETSNewArrayInstanceExpression.ts | 8 +- .../peers/ETSNewClassInstanceExpression.ts | 8 +- .../ETSNewMultiDimArrayInstanceExpression.ts | 8 +- .../src/generated/peers/ETSNullType.ts | 8 +- .../generated/peers/ETSPackageDeclaration.ts | 8 +- .../generated/peers/ETSParameterExpression.ts | 8 +- .../src/generated/peers/ETSPrimitiveType.ts | 8 +- .../generated/peers/ETSReExportDeclaration.ts | 8 +- .../generated/peers/ETSStructDeclaration.ts | 8 +- koala-wrapper/src/generated/peers/ETSTuple.ts | 8 +- .../src/generated/peers/ETSTypeReference.ts | 8 +- .../generated/peers/ETSTypeReferencePart.ts | 8 +- .../src/generated/peers/ETSUndefinedType.ts | 8 +- .../src/generated/peers/ETSUnionType.ts | 8 +- .../src/generated/peers/ETSWildcardType.ts | 8 +- .../src/generated/peers/EmptyStatement.ts | 8 +- .../generated/peers/ExportAllDeclaration.ts | 8 +- .../peers/ExportDefaultDeclaration.ts | 8 +- .../generated/peers/ExportNamedDeclaration.ts | 8 +- .../src/generated/peers/ExportSpecifier.ts | 8 +- .../generated/peers/ExpressionStatement.ts | 8 +- .../src/generated/peers/ForInStatement.ts | 8 +- .../src/generated/peers/ForOfStatement.ts | 8 +- .../src/generated/peers/ForUpdateStatement.ts | 8 +- .../generated/peers/FunctionDeclaration.ts | 8 +- .../src/generated/peers/FunctionExpression.ts | 8 +- .../src/generated/peers/Identifier.ts | 8 +- .../src/generated/peers/IfStatement.ts | 8 +- .../src/generated/peers/ImportDeclaration.ts | 6 +- .../generated/peers/ImportDefaultSpecifier.ts | 8 +- .../src/generated/peers/ImportExpression.ts | 8 +- .../peers/ImportNamespaceSpecifier.ts | 8 +- .../src/generated/peers/ImportSpecifier.ts | 8 +- .../src/generated/peers/LabelledStatement.ts | 8 +- .../src/generated/peers/MemberExpression.ts | 8 +- .../src/generated/peers/MetaProperty.ts | 8 +- .../src/generated/peers/MethodDefinition.ts | 8 +- .../src/generated/peers/NamedType.ts | 8 +- .../src/generated/peers/NewExpression.ts | 8 +- .../src/generated/peers/NullLiteral.ts | 8 +- .../src/generated/peers/NumberLiteral.ts | 8 +- .../src/generated/peers/OmittedExpression.ts | 8 +- .../src/generated/peers/OpaqueTypeNode.ts | 8 +- .../peers/PrefixAssertionExpression.ts | 8 +- koala-wrapper/src/generated/peers/Property.ts | 8 +- .../src/generated/peers/RegExpLiteral.ts | 8 +- .../src/generated/peers/ReturnStatement.ts | 8 +- .../src/generated/peers/ScriptFunction.ts | 8 +- .../src/generated/peers/SequenceExpression.ts | 8 +- .../src/generated/peers/StringLiteral.ts | 8 +- .../src/generated/peers/SuperExpression.ts | 8 +- .../generated/peers/SwitchCaseStatement.ts | 8 +- .../src/generated/peers/SwitchStatement.ts | 8 +- .../src/generated/peers/TSAnyKeyword.ts | 8 +- .../src/generated/peers/TSArrayType.ts | 8 +- .../src/generated/peers/TSAsExpression.ts | 8 +- .../src/generated/peers/TSBigintKeyword.ts | 8 +- .../src/generated/peers/TSBooleanKeyword.ts | 8 +- .../src/generated/peers/TSClassImplements.ts | 8 +- .../src/generated/peers/TSConditionalType.ts | 8 +- .../src/generated/peers/TSConstructorType.ts | 8 +- .../src/generated/peers/TSEnumDeclaration.ts | 8 +- .../src/generated/peers/TSEnumMember.ts | 8 +- .../peers/TSExternalModuleReference.ts | 8 +- .../src/generated/peers/TSFunctionType.ts | 8 +- .../peers/TSImportEqualsDeclaration.ts | 8 +- .../src/generated/peers/TSImportType.ts | 8 +- .../src/generated/peers/TSIndexSignature.ts | 8 +- .../generated/peers/TSIndexedAccessType.ts | 8 +- .../src/generated/peers/TSInferType.ts | 8 +- .../src/generated/peers/TSInterfaceBody.ts | 8 +- .../generated/peers/TSInterfaceDeclaration.ts | 8 +- .../generated/peers/TSInterfaceHeritage.ts | 8 +- .../src/generated/peers/TSIntersectionType.ts | 8 +- .../src/generated/peers/TSLiteralType.ts | 8 +- .../src/generated/peers/TSMappedType.ts | 8 +- .../src/generated/peers/TSMethodSignature.ts | 8 +- .../src/generated/peers/TSModuleBlock.ts | 8 +- .../generated/peers/TSModuleDeclaration.ts | 8 +- .../src/generated/peers/TSNamedTupleMember.ts | 8 +- .../src/generated/peers/TSNeverKeyword.ts | 8 +- .../generated/peers/TSNonNullExpression.ts | 8 +- .../src/generated/peers/TSNullKeyword.ts | 8 +- .../src/generated/peers/TSNumberKeyword.ts | 8 +- .../src/generated/peers/TSObjectKeyword.ts | 8 +- .../generated/peers/TSParameterProperty.ts | 8 +- .../generated/peers/TSParenthesizedType.ts | 8 +- .../generated/peers/TSPropertySignature.ts | 8 +- .../src/generated/peers/TSQualifiedName.ts | 8 +- .../generated/peers/TSSignatureDeclaration.ts | 8 +- .../src/generated/peers/TSStringKeyword.ts | 8 +- .../src/generated/peers/TSThisType.ts | 8 +- .../src/generated/peers/TSTupleType.ts | 8 +- .../generated/peers/TSTypeAliasDeclaration.ts | 8 +- .../src/generated/peers/TSTypeAssertion.ts | 8 +- .../src/generated/peers/TSTypeLiteral.ts | 8 +- .../src/generated/peers/TSTypeOperator.ts | 6 +- .../src/generated/peers/TSTypeParameter.ts | 6 +- .../peers/TSTypeParameterDeclaration.ts | 6 +- .../peers/TSTypeParameterInstantiation.ts | 6 +- .../src/generated/peers/TSTypePredicate.ts | 6 +- .../src/generated/peers/TSTypeQuery.ts | 6 +- .../src/generated/peers/TSTypeReference.ts | 6 +- .../src/generated/peers/TSUndefinedKeyword.ts | 6 +- .../src/generated/peers/TSUnionType.ts | 6 +- .../src/generated/peers/TSUnknownKeyword.ts | 6 +- .../src/generated/peers/TSVoidKeyword.ts | 6 +- .../peers/TaggedTemplateExpression.ts | 8 +- .../src/generated/peers/TemplateElement.ts | 8 +- .../src/generated/peers/TemplateLiteral.ts | 8 +- .../src/generated/peers/ThisExpression.ts | 8 +- .../src/generated/peers/ThrowStatement.ts | 8 +- .../src/generated/peers/TryStatement.ts | 8 +- .../src/generated/peers/TypeofExpression.ts | 6 +- .../src/generated/peers/UnaryExpression.ts | 6 +- .../src/generated/peers/UndefinedLiteral.ts | 6 +- .../src/generated/peers/UpdateExpression.ts | 6 +- .../generated/peers/VariableDeclaration.ts | 6 +- .../src/generated/peers/VariableDeclarator.ts | 6 +- .../src/generated/peers/WhileStatement.ts | 6 +- .../src/generated/peers/YieldExpression.ts | 6 +- 157 files changed, 917 insertions(+), 1025 deletions(-) delete mode 100644 koala-wrapper/src/generated/peers/ETSLaunchExpression.ts diff --git a/koala-wrapper/native/src/generated/bridges.cc b/koala-wrapper/native/src/generated/bridges.cc index f1ca609eb..9f9601e16 100644 --- a/koala-wrapper/native/src/generated/bridges.cc +++ b/koala-wrapper/native/src/generated/bridges.cc @@ -7242,43 +7242,6 @@ KNativePointer impl_UpdateEmptyStatement(KNativePointer context, KNativePointer } KOALA_INTEROP_2(UpdateEmptyStatement, KNativePointer, KNativePointer, KNativePointer); -KNativePointer impl_CreateETSLaunchExpression(KNativePointer context, KNativePointer expr) -{ - const auto _context = reinterpret_cast(context); - const auto _expr = reinterpret_cast(expr); - auto result = GetImpl()->CreateETSLaunchExpression(_context, _expr); - return result; -} -KOALA_INTEROP_2(CreateETSLaunchExpression, KNativePointer, KNativePointer, KNativePointer); - -KNativePointer impl_UpdateETSLaunchExpression(KNativePointer context, KNativePointer original, KNativePointer expr) -{ - const auto _context = reinterpret_cast(context); - const auto _original = reinterpret_cast(original); - const auto _expr = reinterpret_cast(expr); - auto result = GetImpl()->UpdateETSLaunchExpression(_context, _original, _expr); - return result; -} -KOALA_INTEROP_3(UpdateETSLaunchExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); - -KBoolean impl_ETSLaunchExpressionIsStaticCallConst(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - auto result = GetImpl()->ETSLaunchExpressionIsStaticCallConst(_context, _receiver); - return result; -} -KOALA_INTEROP_2(ETSLaunchExpressionIsStaticCallConst, KBoolean, KNativePointer, KNativePointer); - -KNativePointer impl_ETSLaunchExpressionCallConst(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - auto result = GetImpl()->ETSLaunchExpressionCallConst(_context, _receiver); - return (void*)result; -} -KOALA_INTEROP_2(ETSLaunchExpressionCallConst, KNativePointer, KNativePointer, KNativePointer); - KNativePointer impl_CreateWhileStatement(KNativePointer context, KNativePointer test, KNativePointer body) { const auto _context = reinterpret_cast(context); diff --git a/koala-wrapper/src/Es2pandaEnums.ts b/koala-wrapper/src/Es2pandaEnums.ts index bf820a759..e0c455afc 100644 --- a/koala-wrapper/src/Es2pandaEnums.ts +++ b/koala-wrapper/src/Es2pandaEnums.ts @@ -91,7 +91,6 @@ export enum Es2pandaAstNodeType { AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, AST_NODE_TYPE_ETS_UNION_TYPE, AST_NODE_TYPE_ETS_KEYOF_TYPE, - AST_NODE_TYPE_ETS_LAUNCH_EXPRESSION, AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION, AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION, AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION, diff --git a/koala-wrapper/src/generated/Es2pandaEnums.ts b/koala-wrapper/src/generated/Es2pandaEnums.ts index cc682d5a3..bde4ac8d9 100644 --- a/koala-wrapper/src/generated/Es2pandaEnums.ts +++ b/koala-wrapper/src/generated/Es2pandaEnums.ts @@ -332,190 +332,189 @@ export enum Es2pandaId { ID_COUNT = 4 } export enum Es2pandaTokenType { - TOKEN_TYPE_EOS = 0, - TOKEN_TYPE_LITERAL_IDENT = 1, - TOKEN_TYPE_LITERAL_STRING = 2, - TOKEN_TYPE_LITERAL_CHAR = 3, - TOKEN_TYPE_LITERAL_NUMBER = 4, - TOKEN_TYPE_LITERAL_REGEXP = 5, - TOKEN_TYPE_PUNCTUATOR_BITWISE_AND = 6, - TOKEN_TYPE_PUNCTUATOR_BITWISE_OR = 7, - TOKEN_TYPE_PUNCTUATOR_MULTIPLY = 8, - TOKEN_TYPE_PUNCTUATOR_DIVIDE = 9, - TOKEN_TYPE_PUNCTUATOR_MINUS = 10, - TOKEN_TYPE_PUNCTUATOR_EXCLAMATION_MARK = 11, - TOKEN_TYPE_PUNCTUATOR_TILDE = 12, - TOKEN_TYPE_PUNCTUATOR_MINUS_MINUS = 13, - TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT = 14, - TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT = 15, - TOKEN_TYPE_PUNCTUATOR_LESS_THAN_EQUAL = 16, - TOKEN_TYPE_PUNCTUATOR_GREATER_THAN_EQUAL = 17, - TOKEN_TYPE_PUNCTUATOR_MOD = 18, - TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR = 19, - TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION = 20, - TOKEN_TYPE_PUNCTUATOR_MULTIPLY_EQUAL = 21, - TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION_EQUAL = 22, - TOKEN_TYPE_PUNCTUATOR_ARROW = 23, - TOKEN_TYPE_PUNCTUATOR_BACK_TICK = 24, - TOKEN_TYPE_PUNCTUATOR_HASH_MARK = 25, - TOKEN_TYPE_PUNCTUATOR_DIVIDE_EQUAL = 26, - TOKEN_TYPE_PUNCTUATOR_MOD_EQUAL = 27, - TOKEN_TYPE_PUNCTUATOR_MINUS_EQUAL = 28, - TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT_EQUAL = 29, - TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT_EQUAL = 30, - TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT = 31, - TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT_EQUAL = 32, - TOKEN_TYPE_PUNCTUATOR_BITWISE_AND_EQUAL = 33, - TOKEN_TYPE_PUNCTUATOR_BITWISE_OR_EQUAL = 34, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND_EQUAL = 35, - TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING = 36, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR_EQUAL = 37, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_NULLISH_EQUAL = 38, - TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR_EQUAL = 39, - TOKEN_TYPE_PUNCTUATOR_PLUS = 40, - TOKEN_TYPE_PUNCTUATOR_PLUS_PLUS = 41, - TOKEN_TYPE_PUNCTUATOR_PLUS_EQUAL = 42, - TOKEN_TYPE_PUNCTUATOR_LESS_THAN = 43, - TOKEN_TYPE_PUNCTUATOR_GREATER_THAN = 44, - TOKEN_TYPE_PUNCTUATOR_EQUAL = 45, - TOKEN_TYPE_PUNCTUATOR_NOT_EQUAL = 46, - TOKEN_TYPE_PUNCTUATOR_STRICT_EQUAL = 47, - TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL = 48, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND = 49, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR = 50, - TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION = 51, - TOKEN_TYPE_PUNCTUATOR_QUESTION_MARK = 52, - TOKEN_TYPE_PUNCTUATOR_QUESTION_DOT = 53, - TOKEN_TYPE_PUNCTUATOR_AT = 54, - TOKEN_TYPE_PUNCTUATOR_FORMAT = 55, - TOKEN_TYPE_PUNCTUATOR_RIGHT_PARENTHESIS = 56, - TOKEN_TYPE_PUNCTUATOR_LEFT_PARENTHESIS = 57, - TOKEN_TYPE_PUNCTUATOR_RIGHT_SQUARE_BRACKET = 58, - TOKEN_TYPE_PUNCTUATOR_LEFT_SQUARE_BRACKET = 59, - TOKEN_TYPE_PUNCTUATOR_RIGHT_BRACE = 60, - TOKEN_TYPE_PUNCTUATOR_PERIOD = 61, - TOKEN_TYPE_PUNCTUATOR_PERIOD_PERIOD_PERIOD = 62, - TOKEN_TYPE_PUNCTUATOR_PERIOD_QUESTION = 63, - TOKEN_TYPE_PUNCTUATOR_LEFT_BRACE = 64, - TOKEN_TYPE_PUNCTUATOR_SEMI_COLON = 65, - TOKEN_TYPE_PUNCTUATOR_COLON = 66, - TOKEN_TYPE_PUNCTUATOR_COMMA = 67, - TOKEN_TYPE_KEYW_ABSTRACT = 68, - TOKEN_TYPE_KEYW_ANY = 69, - TOKEN_TYPE_KEYW_ANYREF = 70, - TOKEN_TYPE_KEYW_ARGUMENTS = 71, - TOKEN_TYPE_KEYW_AS = 72, - TOKEN_TYPE_KEYW_ASSERT = 73, - TOKEN_TYPE_KEYW_ASSERTS = 74, - TOKEN_TYPE_KEYW_ASYNC = 75, - TOKEN_TYPE_KEYW_AWAIT = 76, - TOKEN_TYPE_KEYW_BIGINT = 77, - TOKEN_TYPE_KEYW_BOOLEAN = 78, - TOKEN_TYPE_KEYW_BREAK = 79, - TOKEN_TYPE_KEYW_BYTE = 80, - TOKEN_TYPE_KEYW_CASE = 81, - TOKEN_TYPE_KEYW_CATCH = 82, - TOKEN_TYPE_KEYW_CHAR = 83, - TOKEN_TYPE_KEYW_CLASS = 84, - TOKEN_TYPE_KEYW_CONST = 85, - TOKEN_TYPE_KEYW_CONSTRUCTOR = 86, - TOKEN_TYPE_KEYW_CONTINUE = 87, - TOKEN_TYPE_KEYW_DATAREF = 88, - TOKEN_TYPE_KEYW_DEBUGGER = 89, - TOKEN_TYPE_KEYW_DECLARE = 90, - TOKEN_TYPE_KEYW_DEFAULT = 91, - TOKEN_TYPE_KEYW_DELETE = 92, - TOKEN_TYPE_KEYW_DO = 93, - TOKEN_TYPE_KEYW_DOUBLE = 94, - TOKEN_TYPE_KEYW_ELSE = 95, - TOKEN_TYPE_KEYW_ENUM = 96, - TOKEN_TYPE_KEYW_EQREF = 97, - TOKEN_TYPE_KEYW_EVAL = 98, - TOKEN_TYPE_KEYW_EXPORT = 99, - TOKEN_TYPE_KEYW_EXTENDS = 100, - TOKEN_TYPE_KEYW_EXTERNREF = 101, - TOKEN_TYPE_KEYW_F32 = 102, - TOKEN_TYPE_KEYW_F64 = 103, - TOKEN_TYPE_LITERAL_FALSE = 104, - TOKEN_TYPE_KEYW_FINALLY = 105, - TOKEN_TYPE_KEYW_FLOAT = 106, - TOKEN_TYPE_KEYW_FOR = 107, - TOKEN_TYPE_KEYW_FROM = 108, - TOKEN_TYPE_KEYW_FUNCREF = 109, - TOKEN_TYPE_KEYW_FUNCTION = 110, - TOKEN_TYPE_KEYW_GET = 111, - TOKEN_TYPE_KEYW_GLOBAL = 112, - TOKEN_TYPE_KEYW_I8 = 113, - TOKEN_TYPE_KEYW_I16 = 114, - TOKEN_TYPE_KEYW_I31REF = 115, - TOKEN_TYPE_KEYW_I32 = 116, - TOKEN_TYPE_KEYW_I64 = 117, - TOKEN_TYPE_KEYW_IF = 118, - TOKEN_TYPE_KEYW_IMPLEMENTS = 119, - TOKEN_TYPE_KEYW_IMPORT = 120, - TOKEN_TYPE_KEYW_IN = 121, - TOKEN_TYPE_KEYW_INFER = 122, - TOKEN_TYPE_KEYW_INSTANCEOF = 123, - TOKEN_TYPE_KEYW_INT = 124, - TOKEN_TYPE_KEYW_INTERFACE = 125, - TOKEN_TYPE_KEYW_IS = 126, - TOKEN_TYPE_KEYW_ISIZE = 127, - TOKEN_TYPE_KEYW_KEYOF = 128, - TOKEN_TYPE_KEYW_LET = 129, - TOKEN_TYPE_KEYW_LAUNCH = 130, - TOKEN_TYPE_KEYW_LONG = 131, - TOKEN_TYPE_KEYW_META = 132, - TOKEN_TYPE_KEYW_MODULE = 133, - TOKEN_TYPE_KEYW_NAMESPACE = 134, - TOKEN_TYPE_KEYW_NATIVE = 135, - TOKEN_TYPE_KEYW_NEVER = 136, - TOKEN_TYPE_KEYW_NEW = 137, - TOKEN_TYPE_LITERAL_NULL = 138, - TOKEN_TYPE_KEYW_NUMBER = 139, - TOKEN_TYPE_KEYW_OBJECT = 140, - TOKEN_TYPE_KEYW_OF = 141, - TOKEN_TYPE_KEYW_FINAL = 142, - TOKEN_TYPE_KEYW_OUT = 143, - TOKEN_TYPE_KEYW_OVERRIDE = 144, - TOKEN_TYPE_KEYW_PACKAGE = 145, - TOKEN_TYPE_KEYW_INTERNAL = 146, - TOKEN_TYPE_KEYW_PRIVATE = 147, - TOKEN_TYPE_KEYW_PROTECTED = 148, - TOKEN_TYPE_KEYW_PUBLIC = 149, - TOKEN_TYPE_KEYW_READONLY = 150, - TOKEN_TYPE_KEYW_RETHROWS = 151, - TOKEN_TYPE_KEYW_RETURN = 152, - TOKEN_TYPE_KEYW_REQUIRE = 153, - TOKEN_TYPE_KEYW_SET = 154, - TOKEN_TYPE_KEYW_SHORT = 155, - TOKEN_TYPE_KEYW_STATIC = 156, - TOKEN_TYPE_KEYW_STRING = 157, - TOKEN_TYPE_KEYW_STRUCT = 158, - TOKEN_TYPE_KEYW_SUPER = 159, - TOKEN_TYPE_KEYW_SWITCH = 160, - TOKEN_TYPE_KEYW_TARGET = 161, - TOKEN_TYPE_KEYW_THIS = 162, - TOKEN_TYPE_KEYW_THROW = 163, - TOKEN_TYPE_KEYW_THROWS = 164, - TOKEN_TYPE_LITERAL_TRUE = 165, - TOKEN_TYPE_KEYW_TRY = 166, - TOKEN_TYPE_KEYW_TYPE = 167, - TOKEN_TYPE_KEYW_TYPEOF = 168, - TOKEN_TYPE_KEYW_U8 = 169, - TOKEN_TYPE_KEYW_U16 = 170, - TOKEN_TYPE_KEYW_U32 = 171, - TOKEN_TYPE_KEYW_U64 = 172, - TOKEN_TYPE_KEYW_UNDEFINED = 173, - TOKEN_TYPE_KEYW_UNKNOWN = 174, - TOKEN_TYPE_KEYW_USIZE = 175, - TOKEN_TYPE_KEYW_V128 = 176, - TOKEN_TYPE_KEYW_VAR = 177, - TOKEN_TYPE_KEYW_VOID = 178, - TOKEN_TYPE_KEYW_WHILE = 179, - TOKEN_TYPE_KEYW_WITH = 180, - TOKEN_TYPE_KEYW_YIELD = 181, - TOKEN_TYPE_FIRST_PUNCTUATOR = 6, - TOKEN_TYPE_FIRST_KEYW = 68 + TOKEN_TYPE_EOS, + TOKEN_TYPE_LITERAL_IDENT, + TOKEN_TYPE_LITERAL_STRING, + TOKEN_TYPE_LITERAL_CHAR, + TOKEN_TYPE_LITERAL_NUMBER, + TOKEN_TYPE_LITERAL_REGEXP, + TOKEN_TYPE_PUNCTUATOR_BITWISE_AND, + TOKEN_TYPE_PUNCTUATOR_BITWISE_OR, + TOKEN_TYPE_PUNCTUATOR_MULTIPLY, + TOKEN_TYPE_PUNCTUATOR_DIVIDE, + TOKEN_TYPE_PUNCTUATOR_MINUS, + TOKEN_TYPE_PUNCTUATOR_EXCLAMATION_MARK, + TOKEN_TYPE_PUNCTUATOR_TILDE, + TOKEN_TYPE_PUNCTUATOR_MINUS_MINUS, + TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT, + TOKEN_TYPE_PUNCTUATOR_LESS_THAN_EQUAL, + TOKEN_TYPE_PUNCTUATOR_GREATER_THAN_EQUAL, + TOKEN_TYPE_PUNCTUATOR_MOD, + TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR, + TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION, + TOKEN_TYPE_PUNCTUATOR_MULTIPLY_EQUAL, + TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION_EQUAL, + TOKEN_TYPE_PUNCTUATOR_ARROW, + TOKEN_TYPE_PUNCTUATOR_BACK_TICK, + TOKEN_TYPE_PUNCTUATOR_HASH_MARK, + TOKEN_TYPE_PUNCTUATOR_DIVIDE_EQUAL, + TOKEN_TYPE_PUNCTUATOR_MOD_EQUAL, + TOKEN_TYPE_PUNCTUATOR_MINUS_EQUAL, + TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT_EQUAL, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT_EQUAL, + TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT, + TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT_EQUAL, + TOKEN_TYPE_PUNCTUATOR_BITWISE_AND_EQUAL, + TOKEN_TYPE_PUNCTUATOR_BITWISE_OR_EQUAL, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND_EQUAL, + TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR_EQUAL, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_NULLISH_EQUAL, + TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR_EQUAL, + TOKEN_TYPE_PUNCTUATOR_PLUS, + TOKEN_TYPE_PUNCTUATOR_PLUS_PLUS, + TOKEN_TYPE_PUNCTUATOR_PLUS_EQUAL, + TOKEN_TYPE_PUNCTUATOR_LESS_THAN, + TOKEN_TYPE_PUNCTUATOR_GREATER_THAN, + TOKEN_TYPE_PUNCTUATOR_EQUAL, + TOKEN_TYPE_PUNCTUATOR_NOT_EQUAL, + TOKEN_TYPE_PUNCTUATOR_STRICT_EQUAL, + TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR, + TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + TOKEN_TYPE_PUNCTUATOR_QUESTION_MARK, + TOKEN_TYPE_PUNCTUATOR_QUESTION_DOT, + TOKEN_TYPE_PUNCTUATOR_AT, + TOKEN_TYPE_PUNCTUATOR_FORMAT, + TOKEN_TYPE_PUNCTUATOR_RIGHT_PARENTHESIS, + TOKEN_TYPE_PUNCTUATOR_LEFT_PARENTHESIS, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SQUARE_BRACKET, + TOKEN_TYPE_PUNCTUATOR_LEFT_SQUARE_BRACKET, + TOKEN_TYPE_PUNCTUATOR_RIGHT_BRACE, + TOKEN_TYPE_PUNCTUATOR_PERIOD, + TOKEN_TYPE_PUNCTUATOR_PERIOD_PERIOD_PERIOD, + TOKEN_TYPE_PUNCTUATOR_PERIOD_QUESTION, + TOKEN_TYPE_PUNCTUATOR_LEFT_BRACE, + TOKEN_TYPE_PUNCTUATOR_SEMI_COLON, + TOKEN_TYPE_PUNCTUATOR_COLON, + TOKEN_TYPE_PUNCTUATOR_COMMA, + TOKEN_TYPE_KEYW_ABSTRACT, + TOKEN_TYPE_KEYW_ANY, + TOKEN_TYPE_KEYW_ANYREF, + TOKEN_TYPE_KEYW_ARGUMENTS, + TOKEN_TYPE_KEYW_AS, + TOKEN_TYPE_KEYW_ASSERT, + TOKEN_TYPE_KEYW_ASSERTS, + TOKEN_TYPE_KEYW_ASYNC, + TOKEN_TYPE_KEYW_AWAIT, + TOKEN_TYPE_KEYW_BIGINT, + TOKEN_TYPE_KEYW_BOOLEAN, + TOKEN_TYPE_KEYW_BREAK, + TOKEN_TYPE_KEYW_BYTE, + TOKEN_TYPE_KEYW_CASE, + TOKEN_TYPE_KEYW_CATCH, + TOKEN_TYPE_KEYW_CHAR, + TOKEN_TYPE_KEYW_CLASS, + TOKEN_TYPE_KEYW_CONST, + TOKEN_TYPE_KEYW_CONSTRUCTOR, + TOKEN_TYPE_KEYW_CONTINUE, + TOKEN_TYPE_KEYW_DATAREF, + TOKEN_TYPE_KEYW_DEBUGGER, + TOKEN_TYPE_KEYW_DECLARE, + TOKEN_TYPE_KEYW_DEFAULT, + TOKEN_TYPE_KEYW_DELETE, + TOKEN_TYPE_KEYW_DO, + TOKEN_TYPE_KEYW_DOUBLE, + TOKEN_TYPE_KEYW_ELSE, + TOKEN_TYPE_KEYW_ENUM, + TOKEN_TYPE_KEYW_EQREF, + TOKEN_TYPE_KEYW_EVAL, + TOKEN_TYPE_KEYW_EXPORT, + TOKEN_TYPE_KEYW_EXTENDS, + TOKEN_TYPE_KEYW_EXTERNREF, + TOKEN_TYPE_KEYW_F32, + TOKEN_TYPE_KEYW_F64, + TOKEN_TYPE_LITERAL_FALSE, + TOKEN_TYPE_KEYW_FINALLY, + TOKEN_TYPE_KEYW_FLOAT, + TOKEN_TYPE_KEYW_FOR, + TOKEN_TYPE_KEYW_FROM, + TOKEN_TYPE_KEYW_FUNCREF, + TOKEN_TYPE_KEYW_FUNCTION, + TOKEN_TYPE_KEYW_GET, + TOKEN_TYPE_KEYW_GLOBAL, + TOKEN_TYPE_KEYW_I8, + TOKEN_TYPE_KEYW_I16, + TOKEN_TYPE_KEYW_I31REF, + TOKEN_TYPE_KEYW_I32, + TOKEN_TYPE_KEYW_I64, + TOKEN_TYPE_KEYW_IF, + TOKEN_TYPE_KEYW_IMPLEMENTS, + TOKEN_TYPE_KEYW_IMPORT, + TOKEN_TYPE_KEYW_IN, + TOKEN_TYPE_KEYW_INFER, + TOKEN_TYPE_KEYW_INSTANCEOF, + TOKEN_TYPE_KEYW_INT, + TOKEN_TYPE_KEYW_INTERFACE, + TOKEN_TYPE_KEYW_IS, + TOKEN_TYPE_KEYW_ISIZE, + TOKEN_TYPE_KEYW_KEYOF, + TOKEN_TYPE_KEYW_LET, + TOKEN_TYPE_KEYW_LONG, + TOKEN_TYPE_KEYW_META, + TOKEN_TYPE_KEYW_MODULE, + TOKEN_TYPE_KEYW_NAMESPACE, + TOKEN_TYPE_KEYW_NATIVE, + TOKEN_TYPE_KEYW_NEVER, + TOKEN_TYPE_KEYW_NEW, + TOKEN_TYPE_LITERAL_NULL, + TOKEN_TYPE_KEYW_NUMBER, + TOKEN_TYPE_KEYW_OBJECT, + TOKEN_TYPE_KEYW_OF, + TOKEN_TYPE_KEYW_FINAL, + TOKEN_TYPE_KEYW_OUT, + TOKEN_TYPE_KEYW_OVERRIDE, + TOKEN_TYPE_KEYW_PACKAGE, + TOKEN_TYPE_KEYW_INTERNAL, + TOKEN_TYPE_KEYW_PRIVATE, + TOKEN_TYPE_KEYW_PROTECTED, + TOKEN_TYPE_KEYW_PUBLIC, + TOKEN_TYPE_KEYW_READONLY, + TOKEN_TYPE_KEYW_RETHROWS, + TOKEN_TYPE_KEYW_RETURN, + TOKEN_TYPE_KEYW_REQUIRE, + TOKEN_TYPE_KEYW_SET, + TOKEN_TYPE_KEYW_SHORT, + TOKEN_TYPE_KEYW_STATIC, + TOKEN_TYPE_KEYW_STRING, + TOKEN_TYPE_KEYW_STRUCT, + TOKEN_TYPE_KEYW_SUPER, + TOKEN_TYPE_KEYW_SWITCH, + TOKEN_TYPE_KEYW_TARGET, + TOKEN_TYPE_KEYW_THIS, + TOKEN_TYPE_KEYW_THROW, + TOKEN_TYPE_KEYW_THROWS, + TOKEN_TYPE_LITERAL_TRUE, + TOKEN_TYPE_KEYW_TRY, + TOKEN_TYPE_KEYW_TYPE, + TOKEN_TYPE_KEYW_TYPEOF, + TOKEN_TYPE_KEYW_U8, + TOKEN_TYPE_KEYW_U16, + TOKEN_TYPE_KEYW_U32, + TOKEN_TYPE_KEYW_U64, + TOKEN_TYPE_KEYW_UNDEFINED, + TOKEN_TYPE_KEYW_UNKNOWN, + TOKEN_TYPE_KEYW_USIZE, + TOKEN_TYPE_KEYW_V128, + TOKEN_TYPE_KEYW_VAR, + TOKEN_TYPE_KEYW_VOID, + TOKEN_TYPE_KEYW_WHILE, + TOKEN_TYPE_KEYW_WITH, + TOKEN_TYPE_KEYW_YIELD, + TOKEN_TYPE_FIRST_PUNCTUATOR = Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_BITWISE_AND, + TOKEN_TYPE_FIRST_KEYW = Es2pandaTokenType.TOKEN_TYPE_KEYW_ABSTRACT } export enum Es2pandaAstNodeFlags { AST_NODE_FLAGS_NO_OPTS = 0, diff --git a/koala-wrapper/src/generated/Es2pandaNativeModule.ts b/koala-wrapper/src/generated/Es2pandaNativeModule.ts index 51040c02b..8c115879f 100644 --- a/koala-wrapper/src/generated/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/generated/Es2pandaNativeModule.ts @@ -2311,18 +2311,6 @@ export class Es2pandaNativeModule { _UpdateEmptyStatement(context: KNativePointer, original: KNativePointer): KNativePointer { throw new Error("'UpdateEmptyStatement was not overloaded by native module initialization") } - _CreateETSLaunchExpression(context: KNativePointer, expr: KNativePointer): KNativePointer { - throw new Error("'CreateETSLaunchExpression was not overloaded by native module initialization") - } - _UpdateETSLaunchExpression(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { - throw new Error("'UpdateETSLaunchExpression was not overloaded by native module initialization") - } - _ETSLaunchExpressionIsStaticCallConst(context: KNativePointer, receiver: KNativePointer): KBoolean { - throw new Error("'ETSLaunchExpressionIsStaticCallConst was not overloaded by native module initialization") - } - _ETSLaunchExpressionCallConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { - throw new Error("'ETSLaunchExpressionCallConst was not overloaded by native module initialization") - } _CreateWhileStatement(context: KNativePointer, test: KNativePointer, body: KNativePointer): KNativePointer { throw new Error("'CreateWhileStatement was not overloaded by native module initialization") } @@ -3712,4 +3700,4 @@ export class Es2pandaNativeModule { _CreateFunctionDecl(context: KNativePointer, name: KStringPtr, node: KNativePointer): KNativePointer { throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") } -} \ No newline at end of file +} diff --git a/koala-wrapper/src/generated/index.ts b/koala-wrapper/src/generated/index.ts index 4b9ae3fc2..0416a0691 100644 --- a/koala-wrapper/src/generated/index.ts +++ b/koala-wrapper/src/generated/index.ts @@ -106,7 +106,6 @@ export * from "./peers/LoopStatement" export * from "./peers/AnnotationDeclaration" export * from "./peers/AnnotationUsage" export * from "./peers/EmptyStatement" -export * from "./peers/ETSLaunchExpression" export * from "./peers/WhileStatement" export * from "./peers/FunctionSignature" export * from "./peers/ChainExpression" @@ -189,4 +188,4 @@ export * from "./peers/TSThisType" export * from "./peers/ETSDynamicFunctionType" export * from "./peers/InterfaceDecl" export * from "./peers/FunctionDecl" -export * from "./peers/Context" \ No newline at end of file +export * from "./peers/Context" diff --git a/koala-wrapper/src/generated/node-map.ts b/koala-wrapper/src/generated/node-map.ts index c8d894039..d9de6e3b5 100644 --- a/koala-wrapper/src/generated/node-map.ts +++ b/koala-wrapper/src/generated/node-map.ts @@ -27,156 +27,155 @@ import { import * as peers from "./index" export const nodes = new Map([ - [44, peers.LabelledStatement], - [146, peers.ThrowStatement], - [17, peers.ClassProperty], - [94, peers.TSVoidKeyword], - [66, peers.ETSFunctionType], - [117, peers.TSTypeOperator], - [38, peers.IfStatement], - [126, peers.TSConstructorType], - [22, peers.Decorator], - [87, peers.TSEnumDeclaration], - [99, peers.TSNeverKeyword], - [41, peers.ImportDefaultSpecifier], - [43, peers.ImportSpecifier], - [19, peers.ConditionalExpression], - [10, peers.CallExpression], - [5, peers.BigIntLiteral], - [112, peers.TSImportType], - [141, peers.TaggedTemplateExpression], - [34, peers.FunctionDeclaration], - [71, peers.ETSTypeReference], - [128, peers.TSTypeReference], - [48, peers.NamedType], - [52, peers.NumberLiteral], - [125, peers.TSFunctionType], - [142, peers.TemplateElement], - [131, peers.TSInterfaceDeclaration], - [150, peers.VariableDeclaration], - [51, peers.UndefinedLiteral], - [45, peers.MemberExpression], - [139, peers.TSClassImplements], - [97, peers.TSObjectKeyword], - [73, peers.ETSUnionType], - [105, peers.TSPropertySignature], - [111, peers.TSConditionalType], - [109, peers.TSLiteralType], - [127, peers.TSTypeAliasDeclaration], - [21, peers.DebuggerStatement], - [58, peers.ReturnStatement], - [27, peers.ExportDefaultDeclaration], - [59, peers.ScriptFunction], - [14, peers.ClassDefinition], - [132, peers.TSInterfaceBody], - [137, peers.TSTypeQuery], - [98, peers.TSBigintKeyword], - [55, peers.Property], - [151, peers.VariableDeclarator], - [61, peers.StringLiteral], - [140, peers.TSTypeAssertion], - [89, peers.TSExternalModuleReference], - [95, peers.TSUndefinedKeyword], - [81, peers.ETSTuple], - [147, peers.TryStatement], - [148, peers.UnaryExpression], - [31, peers.ForInStatement], - [144, peers.ThisExpression], - [106, peers.TSMethodSignature], - [6, peers.BinaryExpression], - [83, peers.SuperExpression], - [3, peers.AssertStatement], - [92, peers.TSStringKeyword], - [30, peers.ExpressionStatement], - [82, peers.ETSModule], - [46, peers.MetaProperty], - [102, peers.TSArrayType], - [107, peers.TSSignatureDeclaration], - [26, peers.ExportAllDeclaration], - [29, peers.ExportSpecifier], - [134, peers.TSTupleType], - [35, peers.FunctionExpression], - [136, peers.TSIndexSignature], - [123, peers.TSModuleDeclaration], - [39, peers.ImportDeclaration], - [108, peers.TSParenthesizedType], - [13, peers.CharLiteral], - [69, peers.ETSPackageDeclaration], - [79, peers.ETSImportDeclaration], - [84, peers.ETSStructDeclaration], - [115, peers.TSModuleBlock], - [76, peers.ETSNewArrayInstanceExpression], - [1, peers.AnnotationDeclaration], - [2, peers.AnnotationUsage], - [25, peers.EmptyStatement], - [75, peers.ETSLaunchExpression], - [152, peers.WhileStatement], - [12, peers.ChainExpression], - [113, peers.TSIntersectionType], - [149, peers.UpdateExpression], - [155, peers.BlockExpression], - [104, peers.TSTypeLiteral], - [118, peers.TSTypeParameter], - [93, peers.TSBooleanKeyword], - [121, peers.TSTypePredicate], - [42, peers.ImportNamespaceSpecifier], - [28, peers.ExportNamedDeclaration], - [80, peers.ETSParameterExpression], - [120, peers.TSTypeParameterInstantiation], - [50, peers.NullLiteral], - [110, peers.TSInferType], - [85, peers.SwitchCaseStatement], - [153, peers.YieldExpression], - [124, peers.TSImportEqualsDeclaration], - [8, peers.BooleanLiteral], - [90, peers.TSNumberKeyword], - [18, peers.ClassStaticBlock], - [100, peers.TSNonNullExpression], - [54, peers.PrefixAssertionExpression], - [16, peers.ClassExpression], - [32, peers.ForOfStatement], - [143, peers.TemplateLiteral], - [103, peers.TSUnionType], - [96, peers.TSUnknownKeyword], - [36, peers.Identifier], - [154, peers.OpaqueTypeNode], - [7, peers.BlockStatement], - [23, peers.DirectEvalExpression], - [119, peers.TSTypeParameterDeclaration], - [47, peers.MethodDefinition], - [101, peers.TSNullKeyword], - [133, peers.TSInterfaceHeritage], - [70, peers.ETSClassLiteral], - [9, peers.BreakStatement], - [56, peers.RegExpLiteral], - [114, peers.TSMappedType], - [91, peers.TSAnyKeyword], - [15, peers.ClassDeclaration], - [130, peers.TSIndexedAccessType], - [129, peers.TSQualifiedName], - [4, peers.AwaitExpression], - [20, peers.ContinueStatement], - [77, peers.ETSNewMultiDimArrayInstanceExpression], - [135, peers.TSNamedTupleMember], - [40, peers.ImportExpression], - [62, peers.ETSNullType], - [63, peers.ETSUndefinedType], - [145, peers.TypeofExpression], - [88, peers.TSEnumMember], - [86, peers.SwitchStatement], - [24, peers.DoWhileStatement], - [11, peers.CatchClause], - [60, peers.SequenceExpression], - [0, peers.ArrowFunctionExpression], - [53, peers.OmittedExpression], - [78, peers.ETSNewClassInstanceExpression], - [138, peers.TSAsExpression], - [33, peers.ForUpdateStatement], - [72, peers.ETSTypeReferencePart], - [57, peers.ETSReExportDeclaration], - [68, peers.ETSPrimitiveType], - [49, peers.NewExpression], - [122, peers.TSParameterProperty], - [67, peers.ETSWildcardType], - [116, peers.TSThisType], -]) \ No newline at end of file + [Es2pandaAstNodeType.AST_NODE_TYPE_LABELLED_STATEMENT, peers.LabelledStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_THROW_STATEMENT, peers.ThrowStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY, peers.ClassProperty], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_VOID_KEYWORD, peers.TSVoidKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE, peers.ETSFunctionType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_OPERATOR, peers.TSTypeOperator], + [Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT, peers.IfStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE, peers.TSConstructorType], + [Es2pandaAstNodeType.AST_NODE_TYPE_DECORATOR, peers.Decorator], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_DECLARATION, peers.TSEnumDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NEVER_KEYWORD, peers.TSNeverKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER, peers.ImportDefaultSpecifier], + [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER, peers.ImportSpecifier], + [Es2pandaAstNodeType.AST_NODE_TYPE_CONDITIONAL_EXPRESSION, peers.ConditionalExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION, peers.CallExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_BIGINT_LITERAL, peers.BigIntLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_TYPE, peers.TSImportType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION, peers.TaggedTemplateExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION, peers.FunctionDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, peers.ETSTypeReference], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_REFERENCE, peers.TSTypeReference], + [Es2pandaAstNodeType.AST_NODE_TYPE_NAMED_TYPE, peers.NamedType], + [Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL, peers.NumberLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_FUNCTION_TYPE, peers.TSFunctionType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_ELEMENT, peers.TemplateElement], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_DECLARATION, peers.TSInterfaceDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION, peers.VariableDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL, peers.UndefinedLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION, peers.MemberExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_CLASS_IMPLEMENTS, peers.TSClassImplements], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_OBJECT_KEYWORD, peers.TSObjectKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE, peers.ETSUnionType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_PROPERTY_SIGNATURE, peers.TSPropertySignature], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONDITIONAL_TYPE, peers.TSConditionalType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE, peers.TSLiteralType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION, peers.TSTypeAliasDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_DEBUGGER_STATEMENT, peers.DebuggerStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT, peers.ReturnStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION, peers.ExportDefaultDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION, peers.ScriptFunction], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION, peers.ClassDefinition], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_BODY, peers.TSInterfaceBody], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_QUERY, peers.TSTypeQuery], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_BIGINT_KEYWORD, peers.TSBigintKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_PROPERTY, peers.Property], + [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR, peers.VariableDeclarator], + [Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL, peers.StringLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ASSERTION, peers.TSTypeAssertion], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE, peers.TSExternalModuleReference], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNDEFINED_KEYWORD, peers.TSUndefinedKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TUPLE, peers.ETSTuple], + [Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT, peers.TryStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_UNARY_EXPRESSION, peers.UnaryExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_FOR_IN_STATEMENT, peers.ForInStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_THIS_EXPRESSION, peers.ThisExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_METHOD_SIGNATURE, peers.TSMethodSignature], + [Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION, peers.BinaryExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION, peers.SuperExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ASSERT_STATEMENT, peers.AssertStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_STRING_KEYWORD, peers.TSStringKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT, peers.ExpressionStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE, peers.ETSModule], + [Es2pandaAstNodeType.AST_NODE_TYPE_META_PROPERTY_EXPRESSION, peers.MetaProperty], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_ARRAY_TYPE, peers.TSArrayType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_SIGNATURE_DECLARATION, peers.TSSignatureDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_ALL_DECLARATION, peers.ExportAllDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_SPECIFIER, peers.ExportSpecifier], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TUPLE_TYPE, peers.TSTupleType], + [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION, peers.FunctionExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEX_SIGNATURE, peers.TSIndexSignature], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_DECLARATION, peers.TSModuleDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DECLARATION, peers.ImportDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARENT_TYPE, peers.TSParenthesizedType], + [Es2pandaAstNodeType.AST_NODE_TYPE_CHAR_LITERAL, peers.CharLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PACKAGE_DECLARATION, peers.ETSPackageDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DECLARATION, peers.ETSImportDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION, peers.ETSStructDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_BLOCK, peers.TSModuleBlock], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION, peers.ETSNewArrayInstanceExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_DECLARATION, peers.AnnotationDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_USAGE, peers.AnnotationUsage], + [Es2pandaAstNodeType.AST_NODE_TYPE_EMPTY_STATEMENT, peers.EmptyStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_WHILE_STATEMENT, peers.WhileStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_CHAIN_EXPRESSION, peers.ChainExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERSECTION_TYPE, peers.TSIntersectionType], + [Es2pandaAstNodeType.AST_NODE_TYPE_UPDATE_EXPRESSION, peers.UpdateExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_EXPRESSION, peers.BlockExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_LITERAL, peers.TSTypeLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER, peers.TSTypeParameter], + [Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL, peers.TSBooleanKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PREDICATE, peers.TSTypePredicate], + [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER, peers.ImportNamespaceSpecifier], + [Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_NAMED_DECLARATION, peers.ExportNamedDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, peers.ETSParameterExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION, peers.TSTypeParameterInstantiation], + [Es2pandaAstNodeType.AST_NODE_TYPE_NULL_LITERAL, peers.NullLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INFER_TYPE, peers.TSInferType], + [Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_CASE_STATEMENT, peers.SwitchCaseStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_YIELD_EXPRESSION, peers.YieldExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION, peers.TSImportEqualsDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL, peers.BooleanLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NUMBER_KEYWORD, peers.TSNumberKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK, peers.ClassStaticBlock], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NON_NULL_EXPRESSION, peers.TSNonNullExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION, peers.PrefixAssertionExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_EXPRESSION, peers.ClassExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_FOR_OF_STATEMENT, peers.ForOfStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_LITERAL, peers.TemplateLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE, peers.TSUnionType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNKNOWN_KEYWORD, peers.TSUnknownKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER, peers.Identifier], + [Es2pandaAstNodeType.AST_NODE_TYPE_OPAQUE_TYPE_NODE, peers.OpaqueTypeNode], + [Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, peers.BlockStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_DIRECT_EVAL, peers.DirectEvalExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION, peers.TSTypeParameterDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION, peers.MethodDefinition], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NULL_KEYWORD, peers.TSNullKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_HERITAGE, peers.TSInterfaceHeritage], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_CLASS_LITERAL, peers.ETSClassLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_BREAK_STATEMENT, peers.BreakStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_REGEXP_LITERAL, peers.RegExpLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_MAPPED_TYPE, peers.TSMappedType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_ANY_KEYWORD, peers.TSAnyKeyword], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION, peers.ClassDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE, peers.TSIndexedAccessType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_QUALIFIED_NAME, peers.TSQualifiedName], + [Es2pandaAstNodeType.AST_NODE_TYPE_AWAIT_EXPRESSION, peers.AwaitExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_CONTINUE_STATEMENT, peers.ContinueStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION, peers.ETSNewMultiDimArrayInstanceExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER, peers.TSNamedTupleMember], + [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_EXPRESSION, peers.ImportExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE, peers.ETSNullType], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE, peers.ETSUndefinedType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TYPEOF_EXPRESSION, peers.TypeofExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_MEMBER, peers.TSEnumMember], + [Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_STATEMENT, peers.SwitchStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_DO_WHILE_STATEMENT, peers.DoWhileStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_CATCH_CLAUSE, peers.CatchClause], + [Es2pandaAstNodeType.AST_NODE_TYPE_SEQUENCE_EXPRESSION, peers.SequenceExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, peers.ArrowFunctionExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_OMITTED_EXPRESSION, peers.OmittedExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION, peers.ETSNewClassInstanceExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_AS_EXPRESSION, peers.TSAsExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_FOR_UPDATE_STATEMENT, peers.ForUpdateStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, peers.ETSTypeReferencePart], + [Es2pandaAstNodeType.AST_NODE_TYPE_REEXPORT_STATEMENT, peers.ETSReExportDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE, peers.ETSPrimitiveType], + [Es2pandaAstNodeType.AST_NODE_TYPE_NEW_EXPRESSION, peers.NewExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARAMETER_PROPERTY, peers.TSParameterProperty], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_WILDCARD_TYPE, peers.ETSWildcardType], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_THIS_TYPE, peers.TSThisType], +]) diff --git a/koala-wrapper/src/generated/peers/AnnotationUsage.ts b/koala-wrapper/src/generated/peers/AnnotationUsage.ts index 1ee1f98b7..e093c4617 100644 --- a/koala-wrapper/src/generated/peers/AnnotationUsage.ts +++ b/koala-wrapper/src/generated/peers/AnnotationUsage.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Identifier } from "./Identifier" export class AnnotationUsage extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 2) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_USAGE) super(pointer) } @@ -73,6 +73,6 @@ export class AnnotationUsage extends Statement { export function isAnnotationUsage(node: AstNode): node is AnnotationUsage { return node instanceof AnnotationUsage } -if (!nodeByType.has(2)) { - nodeByType.set(2, AnnotationUsage) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_USAGE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_USAGE, AnnotationUsage) +} diff --git a/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts b/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts index 7c8ca00f5..75393b037 100644 --- a/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts +++ b/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts @@ -35,7 +35,7 @@ import { TypeNode } from "./TypeNode" import { AnnotationUsage } from "./AnnotationUsage" export class ArrowFunctionExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 0) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION) super(pointer) } @@ -66,6 +66,6 @@ export class ArrowFunctionExpression extends Expression { export function isArrowFunctionExpression(node: AstNode): node is ArrowFunctionExpression { return node instanceof ArrowFunctionExpression } -if (!nodeByType.has(0)) { - nodeByType.set(0, ArrowFunctionExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, ArrowFunctionExpression) +} diff --git a/koala-wrapper/src/generated/peers/AssertStatement.ts b/koala-wrapper/src/generated/peers/AssertStatement.ts index 0d2dcfe05..07f40d7c1 100644 --- a/koala-wrapper/src/generated/peers/AssertStatement.ts +++ b/koala-wrapper/src/generated/peers/AssertStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class AssertStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 3) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ASSERT_STATEMENT) super(pointer) } @@ -53,6 +53,6 @@ export class AssertStatement extends Statement { export function isAssertStatement(node: AstNode): node is AssertStatement { return node instanceof AssertStatement } -if (!nodeByType.has(3)) { - nodeByType.set(3, AssertStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ASSERT_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ASSERT_STATEMENT, AssertStatement) +} diff --git a/koala-wrapper/src/generated/peers/AwaitExpression.ts b/koala-wrapper/src/generated/peers/AwaitExpression.ts index 1e5520228..b090abc87 100644 --- a/koala-wrapper/src/generated/peers/AwaitExpression.ts +++ b/koala-wrapper/src/generated/peers/AwaitExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class AwaitExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 4) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_AWAIT_EXPRESSION) super(pointer) } @@ -49,6 +49,6 @@ export class AwaitExpression extends Expression { export function isAwaitExpression(node: AstNode): node is AwaitExpression { return node instanceof AwaitExpression } -if (!nodeByType.has(4)) { - nodeByType.set(4, AwaitExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_AWAIT_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_AWAIT_EXPRESSION, AwaitExpression) +} diff --git a/koala-wrapper/src/generated/peers/BigIntLiteral.ts b/koala-wrapper/src/generated/peers/BigIntLiteral.ts index 9d390c0c4..e03909d85 100644 --- a/koala-wrapper/src/generated/peers/BigIntLiteral.ts +++ b/koala-wrapper/src/generated/peers/BigIntLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class BigIntLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 5) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BIGINT_LITERAL) super(pointer) } @@ -49,6 +49,6 @@ export class BigIntLiteral extends Literal { export function isBigIntLiteral(node: AstNode): node is BigIntLiteral { return node instanceof BigIntLiteral } -if (!nodeByType.has(5)) { - nodeByType.set(5, BigIntLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BIGINT_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BIGINT_LITERAL, BigIntLiteral) +} diff --git a/koala-wrapper/src/generated/peers/BinaryExpression.ts b/koala-wrapper/src/generated/peers/BinaryExpression.ts index c524075b1..b911d0c58 100644 --- a/koala-wrapper/src/generated/peers/BinaryExpression.ts +++ b/koala-wrapper/src/generated/peers/BinaryExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaTokenType } from "./../Es2pandaEnums" export class BinaryExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 6) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION) super(pointer) } @@ -91,6 +91,6 @@ export class BinaryExpression extends Expression { export function isBinaryExpression(node: AstNode): node is BinaryExpression { return node instanceof BinaryExpression } -if (!nodeByType.has(6)) { - nodeByType.set(6, BinaryExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION, BinaryExpression) +} diff --git a/koala-wrapper/src/generated/peers/BlockExpression.ts b/koala-wrapper/src/generated/peers/BlockExpression.ts index 7e22eef67..38520bcd3 100644 --- a/koala-wrapper/src/generated/peers/BlockExpression.ts +++ b/koala-wrapper/src/generated/peers/BlockExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Statement } from "./Statement" export class BlockExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 155) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_EXPRESSION) super(pointer) } @@ -60,6 +60,6 @@ export class BlockExpression extends Expression { export function isBlockExpression(node: AstNode): node is BlockExpression { return node instanceof BlockExpression } -if (!nodeByType.has(155)) { - nodeByType.set(155, BlockExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_EXPRESSION, BlockExpression) +} diff --git a/koala-wrapper/src/generated/peers/BlockStatement.ts b/koala-wrapper/src/generated/peers/BlockStatement.ts index 8d8ddf9fa..09948d77c 100644 --- a/koala-wrapper/src/generated/peers/BlockStatement.ts +++ b/koala-wrapper/src/generated/peers/BlockStatement.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class BlockStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 7) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT) super(pointer) } @@ -59,6 +59,6 @@ export class BlockStatement extends Statement { export function isBlockStatement(node: AstNode): node is BlockStatement { return node instanceof BlockStatement } -if (!nodeByType.has(7)) { - nodeByType.set(7, BlockStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, BlockStatement) +} diff --git a/koala-wrapper/src/generated/peers/BooleanLiteral.ts b/koala-wrapper/src/generated/peers/BooleanLiteral.ts index 9995a9f89..f82d3a6ed 100644 --- a/koala-wrapper/src/generated/peers/BooleanLiteral.ts +++ b/koala-wrapper/src/generated/peers/BooleanLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class BooleanLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 8) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL) super(pointer) } @@ -49,6 +49,6 @@ export class BooleanLiteral extends Literal { export function isBooleanLiteral(node: AstNode): node is BooleanLiteral { return node instanceof BooleanLiteral } -if (!nodeByType.has(8)) { - nodeByType.set(8, BooleanLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL, BooleanLiteral) +} diff --git a/koala-wrapper/src/generated/peers/BreakStatement.ts b/koala-wrapper/src/generated/peers/BreakStatement.ts index e293ddf59..77b609b0a 100644 --- a/koala-wrapper/src/generated/peers/BreakStatement.ts +++ b/koala-wrapper/src/generated/peers/BreakStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class BreakStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 9) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT) super(pointer) } @@ -64,6 +64,6 @@ export class BreakStatement extends Statement { export function isBreakStatement(node: AstNode): node is BreakStatement { return node instanceof BreakStatement } -if (!nodeByType.has(9)) { - nodeByType.set(9, BreakStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, BreakStatement) +} diff --git a/koala-wrapper/src/generated/peers/CallExpression.ts b/koala-wrapper/src/generated/peers/CallExpression.ts index 3a61208f9..2a8422665 100644 --- a/koala-wrapper/src/generated/peers/CallExpression.ts +++ b/koala-wrapper/src/generated/peers/CallExpression.ts @@ -35,7 +35,7 @@ import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" import { BlockStatement } from "./BlockStatement" export class CallExpression extends MaybeOptionalExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 10) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION) super(pointer) } @@ -93,6 +93,6 @@ export class CallExpression extends MaybeOptionalExpression { export function isCallExpression(node: AstNode): node is CallExpression { return node instanceof CallExpression } -if (!nodeByType.has(10)) { - nodeByType.set(10, CallExpression) -} \ No newline at end of file +if (!nodeByType.has( Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION)) { + nodeByType.set( Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION, CallExpression) +} diff --git a/koala-wrapper/src/generated/peers/CatchClause.ts b/koala-wrapper/src/generated/peers/CatchClause.ts index 068b1dd80..270650213 100644 --- a/koala-wrapper/src/generated/peers/CatchClause.ts +++ b/koala-wrapper/src/generated/peers/CatchClause.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { BlockStatement } from "./BlockStatement" export class CatchClause extends TypedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 11) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CATCH_CLAUSE) super(pointer) } @@ -54,6 +54,6 @@ export class CatchClause extends TypedStatement { export function isCatchClause(node: AstNode): node is CatchClause { return node instanceof CatchClause } -if (!nodeByType.has(11)) { - nodeByType.set(11, CatchClause) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CATCH_CLAUSE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CATCH_CLAUSE, CatchClause) +} diff --git a/koala-wrapper/src/generated/peers/ChainExpression.ts b/koala-wrapper/src/generated/peers/ChainExpression.ts index ae76f46e0..2c89dcd53 100644 --- a/koala-wrapper/src/generated/peers/ChainExpression.ts +++ b/koala-wrapper/src/generated/peers/ChainExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ChainExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 12) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CHAIN_EXPRESSION) super(pointer) } @@ -49,6 +49,6 @@ export class ChainExpression extends Expression { export function isChainExpression(node: AstNode): node is ChainExpression { return node instanceof ChainExpression } -if (!nodeByType.has(12)) { - nodeByType.set(12, ChainExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CHAIN_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CHAIN_EXPRESSION, ChainExpression) +} diff --git a/koala-wrapper/src/generated/peers/CharLiteral.ts b/koala-wrapper/src/generated/peers/CharLiteral.ts index 7dbceda4c..97c67d44e 100644 --- a/koala-wrapper/src/generated/peers/CharLiteral.ts +++ b/koala-wrapper/src/generated/peers/CharLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class CharLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 13) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CHAR_LITERAL) super(pointer) } @@ -46,6 +46,6 @@ export class CharLiteral extends Literal { export function isCharLiteral(node: AstNode): node is CharLiteral { return node instanceof CharLiteral } -if (!nodeByType.has(13)) { - nodeByType.set(13, CharLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CHAR_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CHAR_LITERAL, CharLiteral) +} diff --git a/koala-wrapper/src/generated/peers/ClassDeclaration.ts b/koala-wrapper/src/generated/peers/ClassDeclaration.ts index 1af101f1c..f163c2de3 100644 --- a/koala-wrapper/src/generated/peers/ClassDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ClassDeclaration.ts @@ -34,7 +34,7 @@ import { ClassDefinition } from "./ClassDefinition" import { Decorator } from "./Decorator" export class ClassDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 15) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION) super(pointer) } @@ -54,6 +54,6 @@ export class ClassDeclaration extends Statement { export function isClassDeclaration(node: AstNode): node is ClassDeclaration { return node instanceof ClassDeclaration } -if (!nodeByType.has(15)) { - nodeByType.set(15, ClassDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION, ClassDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ClassDefinition.ts b/koala-wrapper/src/generated/peers/ClassDefinition.ts index f1187001d..fe51f912b 100644 --- a/koala-wrapper/src/generated/peers/ClassDefinition.ts +++ b/koala-wrapper/src/generated/peers/ClassDefinition.ts @@ -44,7 +44,7 @@ import { FunctionExpression } from "./FunctionExpression" import { AnnotationUsage } from "./AnnotationUsage" export class ClassDefinition extends TypedAstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 14) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION) super(pointer) } @@ -217,6 +217,6 @@ export class ClassDefinition extends TypedAstNode { export function isClassDefinition(node: AstNode): node is ClassDefinition { return node instanceof ClassDefinition } -if (!nodeByType.has(14)) { - nodeByType.set(14, ClassDefinition) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION, ClassDefinition) +} diff --git a/koala-wrapper/src/generated/peers/ClassExpression.ts b/koala-wrapper/src/generated/peers/ClassExpression.ts index 9b2f05b2e..e0e0bfef8 100644 --- a/koala-wrapper/src/generated/peers/ClassExpression.ts +++ b/koala-wrapper/src/generated/peers/ClassExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { ClassDefinition } from "./ClassDefinition" export class ClassExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 16) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_EXPRESSION) super(pointer) } @@ -50,6 +50,6 @@ export class ClassExpression extends Expression { export function isClassExpression(node: AstNode): node is ClassExpression { return node instanceof ClassExpression } -if (!nodeByType.has(16)) { - nodeByType.set(16, ClassExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_EXPRESSION, ClassExpression) +} diff --git a/koala-wrapper/src/generated/peers/ClassProperty.ts b/koala-wrapper/src/generated/peers/ClassProperty.ts index cac674bfb..04648bd99 100644 --- a/koala-wrapper/src/generated/peers/ClassProperty.ts +++ b/koala-wrapper/src/generated/peers/ClassProperty.ts @@ -36,7 +36,7 @@ import { Es2pandaModifierFlags } from "./../Es2pandaEnums" import { AnnotationUsage } from "./AnnotationUsage" export class ClassProperty extends ClassElement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 17) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY) super(pointer) } @@ -66,6 +66,6 @@ export class ClassProperty extends ClassElement { export function isClassProperty(node: AstNode): node is ClassProperty { return node instanceof ClassProperty } -if (!nodeByType.has(17)) { - nodeByType.set(17, ClassProperty) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY, ClassProperty) +} diff --git a/koala-wrapper/src/generated/peers/ClassStaticBlock.ts b/koala-wrapper/src/generated/peers/ClassStaticBlock.ts index 92ff36429..5b2bef593 100644 --- a/koala-wrapper/src/generated/peers/ClassStaticBlock.ts +++ b/koala-wrapper/src/generated/peers/ClassStaticBlock.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { ScriptFunction } from "./ScriptFunction" export class ClassStaticBlock extends ClassElement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 18) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK) super(pointer) } @@ -48,6 +48,6 @@ export class ClassStaticBlock extends ClassElement { export function isClassStaticBlock(node: AstNode): node is ClassStaticBlock { return node instanceof ClassStaticBlock } -if (!nodeByType.has(18)) { - nodeByType.set(18, ClassStaticBlock) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK, ClassStaticBlock) +} diff --git a/koala-wrapper/src/generated/peers/ConditionalExpression.ts b/koala-wrapper/src/generated/peers/ConditionalExpression.ts index 20ab3b028..998aa934d 100644 --- a/koala-wrapper/src/generated/peers/ConditionalExpression.ts +++ b/koala-wrapper/src/generated/peers/ConditionalExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ConditionalExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 19) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CONDITIONAL_EXPRESSION) super(pointer) } @@ -70,6 +70,6 @@ export class ConditionalExpression extends Expression { export function isConditionalExpression(node: AstNode): node is ConditionalExpression { return node instanceof ConditionalExpression } -if (!nodeByType.has(19)) { - nodeByType.set(19, ConditionalExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CONDITIONAL_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CONDITIONAL_EXPRESSION, ConditionalExpression) +} diff --git a/koala-wrapper/src/generated/peers/ContinueStatement.ts b/koala-wrapper/src/generated/peers/ContinueStatement.ts index 6d9f8a42e..52cd73c0d 100644 --- a/koala-wrapper/src/generated/peers/ContinueStatement.ts +++ b/koala-wrapper/src/generated/peers/ContinueStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ContinueStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 20) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CONTINUE_STATEMENT) super(pointer) } @@ -64,6 +64,6 @@ export class ContinueStatement extends Statement { export function isContinueStatement(node: AstNode): node is ContinueStatement { return node instanceof ContinueStatement } -if (!nodeByType.has(20)) { - nodeByType.set(20, ContinueStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CONTINUE_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CONTINUE_STATEMENT, ContinueStatement) +} diff --git a/koala-wrapper/src/generated/peers/DebuggerStatement.ts b/koala-wrapper/src/generated/peers/DebuggerStatement.ts index e74c35108..7bebfba19 100644 --- a/koala-wrapper/src/generated/peers/DebuggerStatement.ts +++ b/koala-wrapper/src/generated/peers/DebuggerStatement.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class DebuggerStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 21) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_DEBUGGER_STATEMENT) super(pointer) } @@ -46,6 +46,6 @@ export class DebuggerStatement extends Statement { export function isDebuggerStatement(node: AstNode): node is DebuggerStatement { return node instanceof DebuggerStatement } -if (!nodeByType.has(21)) { - nodeByType.set(21, DebuggerStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_DEBUGGER_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_DEBUGGER_STATEMENT, DebuggerStatement) +} diff --git a/koala-wrapper/src/generated/peers/Decorator.ts b/koala-wrapper/src/generated/peers/Decorator.ts index de635c11e..4f3366551 100644 --- a/koala-wrapper/src/generated/peers/Decorator.ts +++ b/koala-wrapper/src/generated/peers/Decorator.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class Decorator extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 22) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_DECORATOR) super(pointer) } @@ -50,6 +50,6 @@ export class Decorator extends Statement { export function isDecorator(node: AstNode): node is Decorator { return node instanceof Decorator } -if (!nodeByType.has(22)) { - nodeByType.set(22, Decorator) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_DECORATOR)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_DECORATOR, Decorator) +} diff --git a/koala-wrapper/src/generated/peers/DirectEvalExpression.ts b/koala-wrapper/src/generated/peers/DirectEvalExpression.ts index d432f9f0d..0accb0b24 100644 --- a/koala-wrapper/src/generated/peers/DirectEvalExpression.ts +++ b/koala-wrapper/src/generated/peers/DirectEvalExpression.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class DirectEvalExpression extends CallExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 23) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_DIRECT_EVAL) super(pointer) } @@ -48,6 +48,6 @@ export class DirectEvalExpression extends CallExpression { export function isDirectEvalExpression(node: AstNode): node is DirectEvalExpression { return node instanceof DirectEvalExpression } -if (!nodeByType.has(23)) { - nodeByType.set(23, DirectEvalExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_DIRECT_EVAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_DIRECT_EVAL, DirectEvalExpression) +} diff --git a/koala-wrapper/src/generated/peers/DoWhileStatement.ts b/koala-wrapper/src/generated/peers/DoWhileStatement.ts index c6ce8c8cd..569c03d1f 100644 --- a/koala-wrapper/src/generated/peers/DoWhileStatement.ts +++ b/koala-wrapper/src/generated/peers/DoWhileStatement.ts @@ -34,7 +34,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class DoWhileStatement extends LoopStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 24) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_DO_WHILE_STATEMENT) super(pointer) } @@ -54,6 +54,6 @@ export class DoWhileStatement extends LoopStatement { export function isDoWhileStatement(node: AstNode): node is DoWhileStatement { return node instanceof DoWhileStatement } -if (!nodeByType.has(24)) { - nodeByType.set(24, DoWhileStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_DO_WHILE_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_DO_WHILE_STATEMENT, DoWhileStatement) +} diff --git a/koala-wrapper/src/generated/peers/ETSClassLiteral.ts b/koala-wrapper/src/generated/peers/ETSClassLiteral.ts index d78af3b90..80d2e86a7 100644 --- a/koala-wrapper/src/generated/peers/ETSClassLiteral.ts +++ b/koala-wrapper/src/generated/peers/ETSClassLiteral.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class ETSClassLiteral extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 70) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_CLASS_LITERAL) super(pointer) } @@ -50,6 +50,6 @@ export class ETSClassLiteral extends Expression { export function isETSClassLiteral(node: AstNode): node is ETSClassLiteral { return node instanceof ETSClassLiteral } -if (!nodeByType.has(70)) { - nodeByType.set(70, ETSClassLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_CLASS_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_CLASS_LITERAL, ETSClassLiteral) +} diff --git a/koala-wrapper/src/generated/peers/ETSFunctionType.ts b/koala-wrapper/src/generated/peers/ETSFunctionType.ts index 5354546f8..5a630295c 100644 --- a/koala-wrapper/src/generated/peers/ETSFunctionType.ts +++ b/koala-wrapper/src/generated/peers/ETSFunctionType.ts @@ -37,7 +37,7 @@ import { Expression } from "./Expression" import { TSInterfaceDeclaration } from "./TSInterfaceDeclaration" export class ETSFunctionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 66) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE) super(pointer) } @@ -80,6 +80,6 @@ export class ETSFunctionType extends TypeNode { export function isETSFunctionType(node: AstNode): node is ETSFunctionType { return node instanceof ETSFunctionType } -if (!nodeByType.has(66)) { - nodeByType.set(66, ETSFunctionType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE, ETSFunctionType) +} diff --git a/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts b/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts index 9261c82c6..56da81c59 100644 --- a/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts @@ -35,7 +35,7 @@ import { Es2pandaImportKinds } from "./../Es2pandaEnums" import { StringLiteral } from "./StringLiteral" export class ETSImportDeclaration extends ImportDeclaration { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 79) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION) super(pointer) } @@ -64,6 +64,6 @@ export class ETSImportDeclaration extends ImportDeclaration { export function isETSImportDeclaration(node: AstNode): node is ETSImportDeclaration { return node instanceof ETSImportDeclaration } -if (!nodeByType.has(79)) { - nodeByType.set(79, ETSImportDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION, ETSImportDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ETSLaunchExpression.ts b/koala-wrapper/src/generated/peers/ETSLaunchExpression.ts deleted file mode 100644 index 39a42bcc6..000000000 --- a/koala-wrapper/src/generated/peers/ETSLaunchExpression.ts +++ /dev/null @@ -1,55 +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. - */ - -import { - global, - passNode, - passNodeArray, - unpackNonNullableNode, - unpackNode, - unpackNodeArray, - assertValidPeer, - AstNode, - Es2pandaAstNodeType, - KNativePointer, - nodeByType, - ArktsObject, - unpackString -} from "../../reexport-for-generated" - -import { Expression } from "./Expression" -import { CallExpression } from "./CallExpression" -export class ETSLaunchExpression extends Expression { - constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 75) - super(pointer) - - } - static createETSLaunchExpression(expr?: CallExpression): ETSLaunchExpression { - return new ETSLaunchExpression(global.generatedEs2panda._CreateETSLaunchExpression(global.context, passNode(expr))) - } - static updateETSLaunchExpression(original?: ETSLaunchExpression, expr?: CallExpression): ETSLaunchExpression { - return new ETSLaunchExpression(global.generatedEs2panda._UpdateETSLaunchExpression(global.context, passNode(original), passNode(expr))) - } - get call(): CallExpression | undefined { - return unpackNode(global.generatedEs2panda._ETSLaunchExpressionCallConst(global.context, this.peer)) - } -} -export function isETSLaunchExpression(node: AstNode): node is ETSLaunchExpression { - return node instanceof ETSLaunchExpression -} -if (!nodeByType.has(75)) { - nodeByType.set(75, ETSLaunchExpression) -} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSModule.ts b/koala-wrapper/src/generated/peers/ETSModule.ts index df693d3b1..396edaac7 100644 --- a/koala-wrapper/src/generated/peers/ETSModule.ts +++ b/koala-wrapper/src/generated/peers/ETSModule.ts @@ -34,7 +34,7 @@ import { Identifier } from "./Identifier" import { AnnotationUsage } from "./AnnotationUsage" export class ETSModule extends BlockStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 82) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) super(pointer) } @@ -67,6 +67,6 @@ export class ETSModule extends BlockStatement { export function isETSModule(node: AstNode): node is ETSModule { return node instanceof ETSModule } -if (!nodeByType.has(82)) { - nodeByType.set(82, ETSModule) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE, ETSModule) +} diff --git a/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts index 05135647e..63d66f230 100644 --- a/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts +++ b/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class ETSNewArrayInstanceExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 76) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION) super(pointer) } @@ -58,6 +58,6 @@ export class ETSNewArrayInstanceExpression extends Expression { export function isETSNewArrayInstanceExpression(node: AstNode): node is ETSNewArrayInstanceExpression { return node instanceof ETSNewArrayInstanceExpression } -if (!nodeByType.has(76)) { - nodeByType.set(76, ETSNewArrayInstanceExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION, ETSNewArrayInstanceExpression) +} diff --git a/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts index 7e0bb389b..a79deafb3 100644 --- a/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts +++ b/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ETSNewClassInstanceExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 78) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION) super(pointer) } @@ -68,6 +68,6 @@ export class ETSNewClassInstanceExpression extends Expression { export function isETSNewClassInstanceExpression(node: AstNode): node is ETSNewClassInstanceExpression { return node instanceof ETSNewClassInstanceExpression } -if (!nodeByType.has(78)) { - nodeByType.set(78, ETSNewClassInstanceExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION, ETSNewClassInstanceExpression) +} diff --git a/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts index e99e3ed42..5b599dce6 100644 --- a/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts +++ b/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class ETSNewMultiDimArrayInstanceExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 77) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION) super(pointer) } @@ -59,6 +59,6 @@ export class ETSNewMultiDimArrayInstanceExpression extends Expression { export function isETSNewMultiDimArrayInstanceExpression(node: AstNode): node is ETSNewMultiDimArrayInstanceExpression { return node instanceof ETSNewMultiDimArrayInstanceExpression } -if (!nodeByType.has(77)) { - nodeByType.set(77, ETSNewMultiDimArrayInstanceExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION, ETSNewMultiDimArrayInstanceExpression) +} diff --git a/koala-wrapper/src/generated/peers/ETSNullType.ts b/koala-wrapper/src/generated/peers/ETSNullType.ts index edf561cf1..6619bf72a 100644 --- a/koala-wrapper/src/generated/peers/ETSNullType.ts +++ b/koala-wrapper/src/generated/peers/ETSNullType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class ETSNullType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 62) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE) super(pointer) } @@ -46,6 +46,6 @@ export class ETSNullType extends TypeNode { export function isETSNullType(node: AstNode): node is ETSNullType { return node instanceof ETSNullType } -if (!nodeByType.has(62)) { - nodeByType.set(62, ETSNullType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE, ETSNullType) +} diff --git a/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts b/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts index 1148df88e..dce8c6261 100644 --- a/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class ETSPackageDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 69) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PACKAGE_DECLARATION) super(pointer) } @@ -47,6 +47,6 @@ export class ETSPackageDeclaration extends Statement { export function isETSPackageDeclaration(node: AstNode): node is ETSPackageDeclaration { return node instanceof ETSPackageDeclaration } -if (!nodeByType.has(69)) { - nodeByType.set(69, ETSPackageDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PACKAGE_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PACKAGE_DECLARATION, ETSPackageDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ETSParameterExpression.ts b/koala-wrapper/src/generated/peers/ETSParameterExpression.ts index 3b8c76a41..7a16dc8e1 100644 --- a/koala-wrapper/src/generated/peers/ETSParameterExpression.ts +++ b/koala-wrapper/src/generated/peers/ETSParameterExpression.ts @@ -37,7 +37,7 @@ import { TypeNode } from "./TypeNode" import { AnnotationUsage } from "./AnnotationUsage" export class ETSParameterExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 80) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION) super(pointer) } @@ -104,6 +104,6 @@ export class ETSParameterExpression extends Expression { export function isETSParameterExpression(node: AstNode): node is ETSParameterExpression { return node instanceof ETSParameterExpression } -if (!nodeByType.has(80)) { - nodeByType.set(80, ETSParameterExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, ETSParameterExpression) +} diff --git a/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts b/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts index 82713f44b..6d433dff4 100644 --- a/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts +++ b/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Es2pandaPrimitiveType } from "./../Es2pandaEnums" export class ETSPrimitiveType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 68) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE) super(pointer) } @@ -50,6 +50,6 @@ export class ETSPrimitiveType extends TypeNode { export function isETSPrimitiveType(node: AstNode): node is ETSPrimitiveType { return node instanceof ETSPrimitiveType } -if (!nodeByType.has(68)) { - nodeByType.set(68, ETSPrimitiveType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE, ETSPrimitiveType) +} diff --git a/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts b/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts index 6e33931db..669a54af1 100644 --- a/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { ETSImportDeclaration } from "./ETSImportDeclaration" export class ETSReExportDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 57) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_REEXPORT_STATEMENT) super(pointer) } @@ -47,6 +47,6 @@ export class ETSReExportDeclaration extends Statement { export function isETSReExportDeclaration(node: AstNode): node is ETSReExportDeclaration { return node instanceof ETSReExportDeclaration } -if (!nodeByType.has(57)) { - nodeByType.set(57, ETSReExportDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_REEXPORT_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_REEXPORT_STATEMENT, ETSReExportDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts b/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts index 9a060fdce..dfa10cf4c 100644 --- a/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts @@ -33,7 +33,7 @@ import { ClassDeclaration } from "./ClassDeclaration" import { ClassDefinition } from "./ClassDefinition" export class ETSStructDeclaration extends ClassDeclaration { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 84) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION) super(pointer) } @@ -47,6 +47,6 @@ export class ETSStructDeclaration extends ClassDeclaration { export function isETSStructDeclaration(node: AstNode): node is ETSStructDeclaration { return node instanceof ETSStructDeclaration } -if (!nodeByType.has(84)) { - nodeByType.set(84, ETSStructDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION, ETSStructDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ETSTuple.ts b/koala-wrapper/src/generated/peers/ETSTuple.ts index 158eee3f8..8eee89765 100644 --- a/koala-wrapper/src/generated/peers/ETSTuple.ts +++ b/koala-wrapper/src/generated/peers/ETSTuple.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class ETSTuple extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 81) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TUPLE) super(pointer) } @@ -77,6 +77,6 @@ export class ETSTuple extends TypeNode { export function isETSTuple(node: AstNode): node is ETSTuple { return node instanceof ETSTuple } -if (!nodeByType.has(81)) { - nodeByType.set(81, ETSTuple) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TUPLE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TUPLE, ETSTuple) +} diff --git a/koala-wrapper/src/generated/peers/ETSTypeReference.ts b/koala-wrapper/src/generated/peers/ETSTypeReference.ts index f18f4c8b3..1089a11ab 100644 --- a/koala-wrapper/src/generated/peers/ETSTypeReference.ts +++ b/koala-wrapper/src/generated/peers/ETSTypeReference.ts @@ -34,7 +34,7 @@ import { ETSTypeReferencePart } from "./ETSTypeReferencePart" import { Identifier } from "./Identifier" export class ETSTypeReference extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 71) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE) super(pointer) } @@ -51,6 +51,6 @@ export class ETSTypeReference extends TypeNode { export function isETSTypeReference(node: AstNode): node is ETSTypeReference { return node instanceof ETSTypeReference } -if (!nodeByType.has(71)) { - nodeByType.set(71, ETSTypeReference) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, ETSTypeReference) +} diff --git a/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts b/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts index 804642d30..1a7f1968f 100644 --- a/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts +++ b/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class ETSTypeReferencePart extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 72) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART) super(pointer) } @@ -63,6 +63,6 @@ export class ETSTypeReferencePart extends TypeNode { export function isETSTypeReferencePart(node: AstNode): node is ETSTypeReferencePart { return node instanceof ETSTypeReferencePart } -if (!nodeByType.has(72)) { - nodeByType.set(72, ETSTypeReferencePart) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, ETSTypeReferencePart) +} diff --git a/koala-wrapper/src/generated/peers/ETSUndefinedType.ts b/koala-wrapper/src/generated/peers/ETSUndefinedType.ts index 6f44b6a87..c42dcf76b 100644 --- a/koala-wrapper/src/generated/peers/ETSUndefinedType.ts +++ b/koala-wrapper/src/generated/peers/ETSUndefinedType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class ETSUndefinedType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 63) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE) super(pointer) } @@ -46,6 +46,6 @@ export class ETSUndefinedType extends TypeNode { export function isETSUndefinedType(node: AstNode): node is ETSUndefinedType { return node instanceof ETSUndefinedType } -if (!nodeByType.has(63)) { - nodeByType.set(63, ETSUndefinedType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE, ETSUndefinedType) +} diff --git a/koala-wrapper/src/generated/peers/ETSUnionType.ts b/koala-wrapper/src/generated/peers/ETSUnionType.ts index 18ea1f142..59b73ebe7 100644 --- a/koala-wrapper/src/generated/peers/ETSUnionType.ts +++ b/koala-wrapper/src/generated/peers/ETSUnionType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class ETSUnionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 73) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE) super(pointer) } @@ -49,6 +49,6 @@ export class ETSUnionType extends TypeNode { export function isETSUnionType(node: AstNode): node is ETSUnionType { return node instanceof ETSUnionType } -if (!nodeByType.has(73)) { - nodeByType.set(73, ETSUnionType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE, ETSUnionType) +} diff --git a/koala-wrapper/src/generated/peers/ETSWildcardType.ts b/koala-wrapper/src/generated/peers/ETSWildcardType.ts index 7dd790f55..c34909ca7 100644 --- a/koala-wrapper/src/generated/peers/ETSWildcardType.ts +++ b/koala-wrapper/src/generated/peers/ETSWildcardType.ts @@ -34,7 +34,7 @@ import { ETSTypeReference } from "./ETSTypeReference" import { Es2pandaModifierFlags } from "./../Es2pandaEnums" export class ETSWildcardType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 67) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_WILDCARD_TYPE) super(pointer) } @@ -51,6 +51,6 @@ export class ETSWildcardType extends TypeNode { export function isETSWildcardType(node: AstNode): node is ETSWildcardType { return node instanceof ETSWildcardType } -if (!nodeByType.has(67)) { - nodeByType.set(67, ETSWildcardType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_WILDCARD_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_WILDCARD_TYPE, ETSWildcardType) +} diff --git a/koala-wrapper/src/generated/peers/EmptyStatement.ts b/koala-wrapper/src/generated/peers/EmptyStatement.ts index 9e3e61706..b0b5e74f6 100644 --- a/koala-wrapper/src/generated/peers/EmptyStatement.ts +++ b/koala-wrapper/src/generated/peers/EmptyStatement.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class EmptyStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 25) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EMPTY_STATEMENT) super(pointer) } @@ -46,6 +46,6 @@ export class EmptyStatement extends Statement { export function isEmptyStatement(node: AstNode): node is EmptyStatement { return node instanceof EmptyStatement } -if (!nodeByType.has(25)) { - nodeByType.set(25, EmptyStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EMPTY_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EMPTY_STATEMENT, EmptyStatement) +} diff --git a/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts b/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts index 631cdc354..b95b42687 100644 --- a/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts @@ -34,7 +34,7 @@ import { StringLiteral } from "./StringLiteral" import { Identifier } from "./Identifier" export class ExportAllDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 26) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_ALL_DECLARATION) super(pointer) } @@ -54,6 +54,6 @@ export class ExportAllDeclaration extends Statement { export function isExportAllDeclaration(node: AstNode): node is ExportAllDeclaration { return node instanceof ExportAllDeclaration } -if (!nodeByType.has(26)) { - nodeByType.set(26, ExportAllDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_ALL_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_ALL_DECLARATION, ExportAllDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts b/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts index d4f07bb62..0a1600886 100644 --- a/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class ExportDefaultDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 27) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION) super(pointer) } @@ -52,6 +52,6 @@ export class ExportDefaultDeclaration extends Statement { export function isExportDefaultDeclaration(node: AstNode): node is ExportDefaultDeclaration { return node instanceof ExportDefaultDeclaration } -if (!nodeByType.has(27)) { - nodeByType.set(27, ExportDefaultDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION, ExportDefaultDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts b/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts index d7f82f76a..8fe0ed593 100644 --- a/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts @@ -34,7 +34,7 @@ import { StringLiteral } from "./StringLiteral" import { ExportSpecifier } from "./ExportSpecifier" export class ExportNamedDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 28) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_NAMED_DECLARATION) super(pointer) } @@ -69,6 +69,6 @@ export class ExportNamedDeclaration extends Statement { export function isExportNamedDeclaration(node: AstNode): node is ExportNamedDeclaration { return node instanceof ExportNamedDeclaration } -if (!nodeByType.has(28)) { - nodeByType.set(28, ExportNamedDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_NAMED_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_NAMED_DECLARATION, ExportNamedDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ExportSpecifier.ts b/koala-wrapper/src/generated/peers/ExportSpecifier.ts index de59281d9..d68740c1a 100644 --- a/koala-wrapper/src/generated/peers/ExportSpecifier.ts +++ b/koala-wrapper/src/generated/peers/ExportSpecifier.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ExportSpecifier extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 29) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_SPECIFIER) super(pointer) } @@ -53,6 +53,6 @@ export class ExportSpecifier extends Statement { export function isExportSpecifier(node: AstNode): node is ExportSpecifier { return node instanceof ExportSpecifier } -if (!nodeByType.has(29)) { - nodeByType.set(29, ExportSpecifier) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_SPECIFIER)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_SPECIFIER, ExportSpecifier) +} diff --git a/koala-wrapper/src/generated/peers/ExpressionStatement.ts b/koala-wrapper/src/generated/peers/ExpressionStatement.ts index 6603e673e..d7f6ec665 100644 --- a/koala-wrapper/src/generated/peers/ExpressionStatement.ts +++ b/koala-wrapper/src/generated/peers/ExpressionStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class ExpressionStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 30) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT) super(pointer) } @@ -55,6 +55,6 @@ export class ExpressionStatement extends Statement { export function isExpressionStatement(node: AstNode): node is ExpressionStatement { return node instanceof ExpressionStatement } -if (!nodeByType.has(30)) { - nodeByType.set(30, ExpressionStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT, ExpressionStatement) +} diff --git a/koala-wrapper/src/generated/peers/ForInStatement.ts b/koala-wrapper/src/generated/peers/ForInStatement.ts index ff051e35b..adb587a5e 100644 --- a/koala-wrapper/src/generated/peers/ForInStatement.ts +++ b/koala-wrapper/src/generated/peers/ForInStatement.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Statement } from "./Statement" export class ForInStatement extends LoopStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 31) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FOR_IN_STATEMENT) super(pointer) } @@ -57,6 +57,6 @@ export class ForInStatement extends LoopStatement { export function isForInStatement(node: AstNode): node is ForInStatement { return node instanceof ForInStatement } -if (!nodeByType.has(31)) { - nodeByType.set(31, ForInStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_IN_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_IN_STATEMENT, ForInStatement) +} diff --git a/koala-wrapper/src/generated/peers/ForOfStatement.ts b/koala-wrapper/src/generated/peers/ForOfStatement.ts index 801178fd3..d958eb5a2 100644 --- a/koala-wrapper/src/generated/peers/ForOfStatement.ts +++ b/koala-wrapper/src/generated/peers/ForOfStatement.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Statement } from "./Statement" export class ForOfStatement extends LoopStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 32) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FOR_OF_STATEMENT) super(pointer) } @@ -60,6 +60,6 @@ export class ForOfStatement extends LoopStatement { export function isForOfStatement(node: AstNode): node is ForOfStatement { return node instanceof ForOfStatement } -if (!nodeByType.has(32)) { - nodeByType.set(32, ForOfStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_OF_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_OF_STATEMENT, ForOfStatement) +} diff --git a/koala-wrapper/src/generated/peers/ForUpdateStatement.ts b/koala-wrapper/src/generated/peers/ForUpdateStatement.ts index dbf5a9686..cb7985248 100644 --- a/koala-wrapper/src/generated/peers/ForUpdateStatement.ts +++ b/koala-wrapper/src/generated/peers/ForUpdateStatement.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Statement } from "./Statement" export class ForUpdateStatement extends LoopStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 33) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FOR_UPDATE_STATEMENT) super(pointer) } @@ -57,6 +57,6 @@ export class ForUpdateStatement extends LoopStatement { export function isForUpdateStatement(node: AstNode): node is ForUpdateStatement { return node instanceof ForUpdateStatement } -if (!nodeByType.has(33)) { - nodeByType.set(33, ForUpdateStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_UPDATE_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_UPDATE_STATEMENT, ForUpdateStatement) +} diff --git a/koala-wrapper/src/generated/peers/FunctionDeclaration.ts b/koala-wrapper/src/generated/peers/FunctionDeclaration.ts index 1265a281a..598654f02 100644 --- a/koala-wrapper/src/generated/peers/FunctionDeclaration.ts +++ b/koala-wrapper/src/generated/peers/FunctionDeclaration.ts @@ -34,7 +34,7 @@ import { ScriptFunction } from "./ScriptFunction" import { AnnotationUsage } from "./AnnotationUsage" export class FunctionDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 34) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION) super(pointer) } @@ -68,6 +68,6 @@ export class FunctionDeclaration extends Statement { export function isFunctionDeclaration(node: AstNode): node is FunctionDeclaration { return node instanceof FunctionDeclaration } -if (!nodeByType.has(34)) { - nodeByType.set(34, FunctionDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION, FunctionDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/FunctionExpression.ts b/koala-wrapper/src/generated/peers/FunctionExpression.ts index d9e2b3886..65c4ee87b 100644 --- a/koala-wrapper/src/generated/peers/FunctionExpression.ts +++ b/koala-wrapper/src/generated/peers/FunctionExpression.ts @@ -34,7 +34,7 @@ import { ScriptFunction } from "./ScriptFunction" import { Identifier } from "./Identifier" export class FunctionExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 35) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION) super(pointer) } @@ -63,6 +63,6 @@ export class FunctionExpression extends Expression { export function isFunctionExpression(node: AstNode): node is FunctionExpression { return node instanceof FunctionExpression } -if (!nodeByType.has(35)) { - nodeByType.set(35, FunctionExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION, FunctionExpression) +} diff --git a/koala-wrapper/src/generated/peers/Identifier.ts b/koala-wrapper/src/generated/peers/Identifier.ts index 042688c12..f6a3967f5 100644 --- a/koala-wrapper/src/generated/peers/Identifier.ts +++ b/koala-wrapper/src/generated/peers/Identifier.ts @@ -35,7 +35,7 @@ import { Decorator } from "./Decorator" import { ValidationInfo } from "./ValidationInfo" export class Identifier extends AnnotatedExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 36) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER) super(pointer) } @@ -153,6 +153,6 @@ export class Identifier extends AnnotatedExpression { export function isIdentifier(node: AstNode): node is Identifier { return node instanceof Identifier } -if (!nodeByType.has(36)) { - nodeByType.set(36, Identifier) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER, Identifier) +} diff --git a/koala-wrapper/src/generated/peers/IfStatement.ts b/koala-wrapper/src/generated/peers/IfStatement.ts index 056f095f6..2491ed7c6 100644 --- a/koala-wrapper/src/generated/peers/IfStatement.ts +++ b/koala-wrapper/src/generated/peers/IfStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class IfStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 38) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT) super(pointer) } @@ -56,6 +56,6 @@ export class IfStatement extends Statement { export function isIfStatement(node: AstNode): node is IfStatement { return node instanceof IfStatement } -if (!nodeByType.has(38)) { - nodeByType.set(38, IfStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT, IfStatement) +} diff --git a/koala-wrapper/src/generated/peers/ImportDeclaration.ts b/koala-wrapper/src/generated/peers/ImportDeclaration.ts index 3ce4b85d1..eaed6d450 100644 --- a/koala-wrapper/src/generated/peers/ImportDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ImportDeclaration.ts @@ -57,6 +57,6 @@ export class ImportDeclaration extends Statement { export function isImportDeclaration(node: AstNode): node is ImportDeclaration { return node instanceof ImportDeclaration } -if (!nodeByType.has(39)) { - nodeByType.set(39, ImportDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DECLARATION, ImportDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts b/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts index 5b4ce34e9..2ae1f64be 100644 --- a/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts +++ b/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ImportDefaultSpecifier extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 41) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER) super(pointer) } @@ -50,6 +50,6 @@ export class ImportDefaultSpecifier extends Statement { export function isImportDefaultSpecifier(node: AstNode): node is ImportDefaultSpecifier { return node instanceof ImportDefaultSpecifier } -if (!nodeByType.has(41)) { - nodeByType.set(41, ImportDefaultSpecifier) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER, ImportDefaultSpecifier) +} diff --git a/koala-wrapper/src/generated/peers/ImportExpression.ts b/koala-wrapper/src/generated/peers/ImportExpression.ts index fc70fd1cb..25ae47eef 100644 --- a/koala-wrapper/src/generated/peers/ImportExpression.ts +++ b/koala-wrapper/src/generated/peers/ImportExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ImportExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 40) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_EXPRESSION) super(pointer) } @@ -49,6 +49,6 @@ export class ImportExpression extends Expression { export function isImportExpression(node: AstNode): node is ImportExpression { return node instanceof ImportExpression } -if (!nodeByType.has(40)) { - nodeByType.set(40, ImportExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_EXPRESSION, ImportExpression) +} diff --git a/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts b/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts index 4f1e128bf..4caa2e2e8 100644 --- a/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts +++ b/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ImportNamespaceSpecifier extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 42) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER) super(pointer) } @@ -50,6 +50,6 @@ export class ImportNamespaceSpecifier extends Statement { export function isImportNamespaceSpecifier(node: AstNode): node is ImportNamespaceSpecifier { return node instanceof ImportNamespaceSpecifier } -if (!nodeByType.has(42)) { - nodeByType.set(42, ImportNamespaceSpecifier) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER, ImportNamespaceSpecifier) +} diff --git a/koala-wrapper/src/generated/peers/ImportSpecifier.ts b/koala-wrapper/src/generated/peers/ImportSpecifier.ts index e2d49f139..828f1eebf 100644 --- a/koala-wrapper/src/generated/peers/ImportSpecifier.ts +++ b/koala-wrapper/src/generated/peers/ImportSpecifier.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ImportSpecifier extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 43) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER) super(pointer) } @@ -53,6 +53,6 @@ export class ImportSpecifier extends Statement { export function isImportSpecifier(node: AstNode): node is ImportSpecifier { return node instanceof ImportSpecifier } -if (!nodeByType.has(43)) { - nodeByType.set(43, ImportSpecifier) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER, ImportSpecifier) +} diff --git a/koala-wrapper/src/generated/peers/LabelledStatement.ts b/koala-wrapper/src/generated/peers/LabelledStatement.ts index 7dec2f9ee..9b9ac14b1 100644 --- a/koala-wrapper/src/generated/peers/LabelledStatement.ts +++ b/koala-wrapper/src/generated/peers/LabelledStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class LabelledStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 44) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_LABELLED_STATEMENT) super(pointer) } @@ -53,6 +53,6 @@ export class LabelledStatement extends Statement { export function isLabelledStatement(node: AstNode): node is LabelledStatement { return node instanceof LabelledStatement } -if (!nodeByType.has(44)) { - nodeByType.set(44, LabelledStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_LABELLED_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_LABELLED_STATEMENT, LabelledStatement) +} diff --git a/koala-wrapper/src/generated/peers/MemberExpression.ts b/koala-wrapper/src/generated/peers/MemberExpression.ts index 40f74fe00..530fc754e 100644 --- a/koala-wrapper/src/generated/peers/MemberExpression.ts +++ b/koala-wrapper/src/generated/peers/MemberExpression.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Es2pandaMemberExpressionKind } from "./../Es2pandaEnums" export class MemberExpression extends MaybeOptionalExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 45) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION) super(pointer) } @@ -88,6 +88,6 @@ export class MemberExpression extends MaybeOptionalExpression { export function isMemberExpression(node: AstNode): node is MemberExpression { return node instanceof MemberExpression } -if (!nodeByType.has(45)) { - nodeByType.set(45, MemberExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION, MemberExpression) +} diff --git a/koala-wrapper/src/generated/peers/MetaProperty.ts b/koala-wrapper/src/generated/peers/MetaProperty.ts index 82c8bc8ae..fbdb77b24 100644 --- a/koala-wrapper/src/generated/peers/MetaProperty.ts +++ b/koala-wrapper/src/generated/peers/MetaProperty.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaMetaPropertyKind } from "./../Es2pandaEnums" export class MetaProperty extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 46) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_META_PROPERTY_EXPRESSION) super(pointer) } @@ -50,6 +50,6 @@ export class MetaProperty extends Expression { export function isMetaProperty(node: AstNode): node is MetaProperty { return node instanceof MetaProperty } -if (!nodeByType.has(46)) { - nodeByType.set(46, MetaProperty) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_META_PROPERTY_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_META_PROPERTY_EXPRESSION, MetaProperty) +} diff --git a/koala-wrapper/src/generated/peers/MethodDefinition.ts b/koala-wrapper/src/generated/peers/MethodDefinition.ts index 40dd13888..0cfbcff23 100644 --- a/koala-wrapper/src/generated/peers/MethodDefinition.ts +++ b/koala-wrapper/src/generated/peers/MethodDefinition.ts @@ -36,7 +36,7 @@ import { Es2pandaModifierFlags } from "./../Es2pandaEnums" import { ScriptFunction } from "./ScriptFunction" export class MethodDefinition extends ClassElement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 47) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION) super(pointer) } @@ -93,6 +93,6 @@ export class MethodDefinition extends ClassElement { export function isMethodDefinition(node: AstNode): node is MethodDefinition { return node instanceof MethodDefinition } -if (!nodeByType.has(47)) { - nodeByType.set(47, MethodDefinition) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION, MethodDefinition) +} diff --git a/koala-wrapper/src/generated/peers/NamedType.ts b/koala-wrapper/src/generated/peers/NamedType.ts index ce6ee368e..a95328543 100644 --- a/koala-wrapper/src/generated/peers/NamedType.ts +++ b/koala-wrapper/src/generated/peers/NamedType.ts @@ -34,7 +34,7 @@ import { Identifier } from "./Identifier" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class NamedType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 48) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_NAMED_TYPE) super(pointer) } @@ -72,6 +72,6 @@ export class NamedType extends TypeNode { export function isNamedType(node: AstNode): node is NamedType { return node instanceof NamedType } -if (!nodeByType.has(48)) { - nodeByType.set(48, NamedType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_NAMED_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_NAMED_TYPE, NamedType) +} diff --git a/koala-wrapper/src/generated/peers/NewExpression.ts b/koala-wrapper/src/generated/peers/NewExpression.ts index c267a581d..f09cf3d6e 100644 --- a/koala-wrapper/src/generated/peers/NewExpression.ts +++ b/koala-wrapper/src/generated/peers/NewExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class NewExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 49) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_NEW_EXPRESSION) super(pointer) } @@ -52,6 +52,6 @@ export class NewExpression extends Expression { export function isNewExpression(node: AstNode): node is NewExpression { return node instanceof NewExpression } -if (!nodeByType.has(49)) { - nodeByType.set(49, NewExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_NEW_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_NEW_EXPRESSION, NewExpression) +} diff --git a/koala-wrapper/src/generated/peers/NullLiteral.ts b/koala-wrapper/src/generated/peers/NullLiteral.ts index a8047b711..11f751021 100644 --- a/koala-wrapper/src/generated/peers/NullLiteral.ts +++ b/koala-wrapper/src/generated/peers/NullLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class NullLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 50) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_NULL_LITERAL) super(pointer) } @@ -46,6 +46,6 @@ export class NullLiteral extends Literal { export function isNullLiteral(node: AstNode): node is NullLiteral { return node instanceof NullLiteral } -if (!nodeByType.has(50)) { - nodeByType.set(50, NullLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_NULL_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_NULL_LITERAL, NullLiteral) +} diff --git a/koala-wrapper/src/generated/peers/NumberLiteral.ts b/koala-wrapper/src/generated/peers/NumberLiteral.ts index e14e174d9..419e7cb74 100644 --- a/koala-wrapper/src/generated/peers/NumberLiteral.ts +++ b/koala-wrapper/src/generated/peers/NumberLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class NumberLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 52) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL) super(pointer) } @@ -43,6 +43,6 @@ export class NumberLiteral extends Literal { export function isNumberLiteral(node: AstNode): node is NumberLiteral { return node instanceof NumberLiteral } -if (!nodeByType.has(52)) { - nodeByType.set(52, NumberLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL, NumberLiteral) +} diff --git a/koala-wrapper/src/generated/peers/OmittedExpression.ts b/koala-wrapper/src/generated/peers/OmittedExpression.ts index 339202ae3..4449960a1 100644 --- a/koala-wrapper/src/generated/peers/OmittedExpression.ts +++ b/koala-wrapper/src/generated/peers/OmittedExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class OmittedExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 53) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_OMITTED_EXPRESSION) super(pointer) } @@ -46,6 +46,6 @@ export class OmittedExpression extends Expression { export function isOmittedExpression(node: AstNode): node is OmittedExpression { return node instanceof OmittedExpression } -if (!nodeByType.has(53)) { - nodeByType.set(53, OmittedExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_OMITTED_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_OMITTED_EXPRESSION, OmittedExpression) +} diff --git a/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts b/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts index ba2d646dc..8fbc0101b 100644 --- a/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts +++ b/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class OpaqueTypeNode extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 154) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_OPAQUE_TYPE_NODE) super(pointer) } @@ -46,6 +46,6 @@ export class OpaqueTypeNode extends TypeNode { export function isOpaqueTypeNode(node: AstNode): node is OpaqueTypeNode { return node instanceof OpaqueTypeNode } -if (!nodeByType.has(154)) { - nodeByType.set(154, OpaqueTypeNode) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_OPAQUE_TYPE_NODE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_OPAQUE_TYPE_NODE, OpaqueTypeNode) +} diff --git a/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts b/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts index 03a093531..30dc3d43a 100644 --- a/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts +++ b/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class PrefixAssertionExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 54) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION) super(pointer) } @@ -53,6 +53,6 @@ export class PrefixAssertionExpression extends Expression { export function isPrefixAssertionExpression(node: AstNode): node is PrefixAssertionExpression { return node instanceof PrefixAssertionExpression } -if (!nodeByType.has(54)) { - nodeByType.set(54, PrefixAssertionExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION, PrefixAssertionExpression) +} diff --git a/koala-wrapper/src/generated/peers/Property.ts b/koala-wrapper/src/generated/peers/Property.ts index 982cb0241..6a576762b 100644 --- a/koala-wrapper/src/generated/peers/Property.ts +++ b/koala-wrapper/src/generated/peers/Property.ts @@ -34,7 +34,7 @@ import { Es2pandaPropertyKind } from "./../Es2pandaEnums" import { ValidationInfo } from "./ValidationInfo" export class Property extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 55) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_PROPERTY) super(pointer) } @@ -75,6 +75,6 @@ export class Property extends Expression { export function isProperty(node: AstNode): node is Property { return node instanceof Property } -if (!nodeByType.has(55)) { - nodeByType.set(55, Property) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_PROPERTY)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_PROPERTY, Property) +} diff --git a/koala-wrapper/src/generated/peers/RegExpLiteral.ts b/koala-wrapper/src/generated/peers/RegExpLiteral.ts index 5ae04143b..0d91a57d9 100644 --- a/koala-wrapper/src/generated/peers/RegExpLiteral.ts +++ b/koala-wrapper/src/generated/peers/RegExpLiteral.ts @@ -33,7 +33,7 @@ import { Literal } from "./Literal" import { Es2pandaRegExpFlags } from "./../Es2pandaEnums" export class RegExpLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 56) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_REGEXP_LITERAL) super(pointer) } @@ -53,6 +53,6 @@ export class RegExpLiteral extends Literal { export function isRegExpLiteral(node: AstNode): node is RegExpLiteral { return node instanceof RegExpLiteral } -if (!nodeByType.has(56)) { - nodeByType.set(56, RegExpLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_REGEXP_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_REGEXP_LITERAL, RegExpLiteral) +} diff --git a/koala-wrapper/src/generated/peers/ReturnStatement.ts b/koala-wrapper/src/generated/peers/ReturnStatement.ts index 6489e99df..4607dbe40 100644 --- a/koala-wrapper/src/generated/peers/ReturnStatement.ts +++ b/koala-wrapper/src/generated/peers/ReturnStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class ReturnStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 58) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT) super(pointer) } @@ -61,6 +61,6 @@ export class ReturnStatement extends Statement { export function isReturnStatement(node: AstNode): node is ReturnStatement { return node instanceof ReturnStatement } -if (!nodeByType.has(58)) { - nodeByType.set(58, ReturnStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT, ReturnStatement) +} diff --git a/koala-wrapper/src/generated/peers/ScriptFunction.ts b/koala-wrapper/src/generated/peers/ScriptFunction.ts index 28b262008..42c4c9343 100644 --- a/koala-wrapper/src/generated/peers/ScriptFunction.ts +++ b/koala-wrapper/src/generated/peers/ScriptFunction.ts @@ -40,7 +40,7 @@ import { Es2pandaModifierFlags } from "./../Es2pandaEnums" import { AnnotationUsage } from "./AnnotationUsage" export class ScriptFunction extends AstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 59) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION) super(pointer) } @@ -194,6 +194,6 @@ export class ScriptFunction extends AstNode { export function isScriptFunction(node: AstNode): node is ScriptFunction { return node instanceof ScriptFunction } -if (!nodeByType.has(59)) { - nodeByType.set(59, ScriptFunction) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION, ScriptFunction) +} diff --git a/koala-wrapper/src/generated/peers/SequenceExpression.ts b/koala-wrapper/src/generated/peers/SequenceExpression.ts index fb0f1a9c0..dc814dd4d 100644 --- a/koala-wrapper/src/generated/peers/SequenceExpression.ts +++ b/koala-wrapper/src/generated/peers/SequenceExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class SequenceExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 60) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SEQUENCE_EXPRESSION) super(pointer) } @@ -49,6 +49,6 @@ export class SequenceExpression extends Expression { export function isSequenceExpression(node: AstNode): node is SequenceExpression { return node instanceof SequenceExpression } -if (!nodeByType.has(60)) { - nodeByType.set(60, SequenceExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SEQUENCE_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SEQUENCE_EXPRESSION, SequenceExpression) +} diff --git a/koala-wrapper/src/generated/peers/StringLiteral.ts b/koala-wrapper/src/generated/peers/StringLiteral.ts index 6eed3c9e4..cf03dca5c 100644 --- a/koala-wrapper/src/generated/peers/StringLiteral.ts +++ b/koala-wrapper/src/generated/peers/StringLiteral.ts @@ -31,7 +31,7 @@ import { import { Literal } from "./Literal" export class StringLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 61) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL) super(pointer) } @@ -54,6 +54,6 @@ export class StringLiteral extends Literal { export function isStringLiteral(node: AstNode): node is StringLiteral { return node instanceof StringLiteral } -if (!nodeByType.has(61)) { - nodeByType.set(61, StringLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL, StringLiteral) +} diff --git a/koala-wrapper/src/generated/peers/SuperExpression.ts b/koala-wrapper/src/generated/peers/SuperExpression.ts index 57b35074d..6f7c877c0 100644 --- a/koala-wrapper/src/generated/peers/SuperExpression.ts +++ b/koala-wrapper/src/generated/peers/SuperExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class SuperExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 83) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION) super(pointer) } @@ -46,6 +46,6 @@ export class SuperExpression extends Expression { export function isSuperExpression(node: AstNode): node is SuperExpression { return node instanceof SuperExpression } -if (!nodeByType.has(83)) { - nodeByType.set(83, SuperExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION, SuperExpression) +} diff --git a/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts b/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts index 93ff25f08..27f1d7e98 100644 --- a/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts +++ b/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class SwitchCaseStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 85) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_CASE_STATEMENT) super(pointer) } @@ -53,6 +53,6 @@ export class SwitchCaseStatement extends Statement { export function isSwitchCaseStatement(node: AstNode): node is SwitchCaseStatement { return node instanceof SwitchCaseStatement } -if (!nodeByType.has(85)) { - nodeByType.set(85, SwitchCaseStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_CASE_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_CASE_STATEMENT, SwitchCaseStatement) +} diff --git a/koala-wrapper/src/generated/peers/SwitchStatement.ts b/koala-wrapper/src/generated/peers/SwitchStatement.ts index d11afaf4a..d7c9289cd 100644 --- a/koala-wrapper/src/generated/peers/SwitchStatement.ts +++ b/koala-wrapper/src/generated/peers/SwitchStatement.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { SwitchCaseStatement } from "./SwitchCaseStatement" export class SwitchStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 86) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_STATEMENT) super(pointer) } @@ -54,6 +54,6 @@ export class SwitchStatement extends Statement { export function isSwitchStatement(node: AstNode): node is SwitchStatement { return node instanceof SwitchStatement } -if (!nodeByType.has(86)) { - nodeByType.set(86, SwitchStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_STATEMENT, SwitchStatement) +} diff --git a/koala-wrapper/src/generated/peers/TSAnyKeyword.ts b/koala-wrapper/src/generated/peers/TSAnyKeyword.ts index ffb19bebf..7f0133efb 100644 --- a/koala-wrapper/src/generated/peers/TSAnyKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSAnyKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSAnyKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 91) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_ANY_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSAnyKeyword extends TypeNode { export function isTSAnyKeyword(node: AstNode): node is TSAnyKeyword { return node instanceof TSAnyKeyword } -if (!nodeByType.has(91)) { - nodeByType.set(91, TSAnyKeyword) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ANY_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ANY_KEYWORD, TSAnyKeyword) +} diff --git a/koala-wrapper/src/generated/peers/TSArrayType.ts b/koala-wrapper/src/generated/peers/TSArrayType.ts index a727d24fc..475b248cc 100644 --- a/koala-wrapper/src/generated/peers/TSArrayType.ts +++ b/koala-wrapper/src/generated/peers/TSArrayType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSArrayType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 102) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_ARRAY_TYPE) super(pointer) } @@ -49,6 +49,6 @@ export class TSArrayType extends TypeNode { export function isTSArrayType(node: AstNode): node is TSArrayType { return node instanceof TSArrayType } -if (!nodeByType.has(102)) { - nodeByType.set(102, TSArrayType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ARRAY_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ARRAY_TYPE, TSArrayType) +} diff --git a/koala-wrapper/src/generated/peers/TSAsExpression.ts b/koala-wrapper/src/generated/peers/TSAsExpression.ts index 718b9427b..99c58edd4 100644 --- a/koala-wrapper/src/generated/peers/TSAsExpression.ts +++ b/koala-wrapper/src/generated/peers/TSAsExpression.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSAsExpression extends AnnotatedExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 138) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_AS_EXPRESSION) super(pointer) } @@ -72,6 +72,6 @@ export class TSAsExpression extends AnnotatedExpression { export function isTSAsExpression(node: AstNode): node is TSAsExpression { return node instanceof TSAsExpression } -if (!nodeByType.has(138)) { - nodeByType.set(138, TSAsExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_AS_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_AS_EXPRESSION, TSAsExpression) +} diff --git a/koala-wrapper/src/generated/peers/TSBigintKeyword.ts b/koala-wrapper/src/generated/peers/TSBigintKeyword.ts index 371719a14..12da1be06 100644 --- a/koala-wrapper/src/generated/peers/TSBigintKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSBigintKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSBigintKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 98) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_BIGINT_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSBigintKeyword extends TypeNode { export function isTSBigintKeyword(node: AstNode): node is TSBigintKeyword { return node instanceof TSBigintKeyword } -if (!nodeByType.has(98)) { - nodeByType.set(98, TSBigintKeyword) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_BIGINT_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_BIGINT_KEYWORD, TSBigintKeyword) +} diff --git a/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts b/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts index cc4c077b3..6459f6fdb 100644 --- a/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSBooleanKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 93) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_BOOLEAN_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSBooleanKeyword extends TypeNode { export function isTSBooleanKeyword(node: AstNode): node is TSBooleanKeyword { return node instanceof TSBooleanKeyword } -if (!nodeByType.has(93)) { - nodeByType.set(93, TSBooleanKeyword) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_BOOLEAN_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_BOOLEAN_KEYWORD, TSBooleanKeyword) +} diff --git a/koala-wrapper/src/generated/peers/TSClassImplements.ts b/koala-wrapper/src/generated/peers/TSClassImplements.ts index b06a578a1..ed621c260 100644 --- a/koala-wrapper/src/generated/peers/TSClassImplements.ts +++ b/koala-wrapper/src/generated/peers/TSClassImplements.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class TSClassImplements extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 139) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_CLASS_IMPLEMENTS) super(pointer) } @@ -59,6 +59,6 @@ export class TSClassImplements extends Expression { export function isTSClassImplements(node: AstNode): node is TSClassImplements { return node instanceof TSClassImplements } -if (!nodeByType.has(139)) { - nodeByType.set(139, TSClassImplements) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CLASS_IMPLEMENTS)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CLASS_IMPLEMENTS, TSClassImplements) +} diff --git a/koala-wrapper/src/generated/peers/TSConditionalType.ts b/koala-wrapper/src/generated/peers/TSConditionalType.ts index f03de8600..6b6ab8f22 100644 --- a/koala-wrapper/src/generated/peers/TSConditionalType.ts +++ b/koala-wrapper/src/generated/peers/TSConditionalType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSConditionalType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 111) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONDITIONAL_TYPE) super(pointer) } @@ -59,6 +59,6 @@ export class TSConditionalType extends TypeNode { export function isTSConditionalType(node: AstNode): node is TSConditionalType { return node instanceof TSConditionalType } -if (!nodeByType.has(111)) { - nodeByType.set(111, TSConditionalType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONDITIONAL_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONDITIONAL_TYPE, TSConditionalType) +} diff --git a/koala-wrapper/src/generated/peers/TSConstructorType.ts b/koala-wrapper/src/generated/peers/TSConstructorType.ts index 896ccf390..be2be772c 100644 --- a/koala-wrapper/src/generated/peers/TSConstructorType.ts +++ b/koala-wrapper/src/generated/peers/TSConstructorType.ts @@ -35,7 +35,7 @@ import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" import { Expression } from "./Expression" export class TSConstructorType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 126) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE) super(pointer) } @@ -61,6 +61,6 @@ export class TSConstructorType extends TypeNode { export function isTSConstructorType(node: AstNode): node is TSConstructorType { return node instanceof TSConstructorType } -if (!nodeByType.has(126)) { - nodeByType.set(126, TSConstructorType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE, TSConstructorType) +} diff --git a/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts b/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts index ecebdceed..707334a8c 100644 --- a/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts @@ -35,7 +35,7 @@ import { ClassDefinition } from "./ClassDefinition" import { Decorator } from "./Decorator" export class TSEnumDeclaration extends TypedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 87) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_DECLARATION) super(pointer) } @@ -77,6 +77,6 @@ export class TSEnumDeclaration extends TypedStatement { export function isTSEnumDeclaration(node: AstNode): node is TSEnumDeclaration { return node instanceof TSEnumDeclaration } -if (!nodeByType.has(87)) { - nodeByType.set(87, TSEnumDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_DECLARATION, TSEnumDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/TSEnumMember.ts b/koala-wrapper/src/generated/peers/TSEnumMember.ts index c0332c509..862e08867 100644 --- a/koala-wrapper/src/generated/peers/TSEnumMember.ts +++ b/koala-wrapper/src/generated/peers/TSEnumMember.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class TSEnumMember extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 88) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_MEMBER) super(pointer) } @@ -62,6 +62,6 @@ export class TSEnumMember extends Statement { export function isTSEnumMember(node: AstNode): node is TSEnumMember { return node instanceof TSEnumMember } -if (!nodeByType.has(88)) { - nodeByType.set(88, TSEnumMember) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_MEMBER)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_MEMBER, TSEnumMember) +} diff --git a/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts b/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts index eae8cfabc..44303a741 100644 --- a/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts +++ b/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TSExternalModuleReference extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 89) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE) super(pointer) } @@ -49,6 +49,6 @@ export class TSExternalModuleReference extends Expression { export function isTSExternalModuleReference(node: AstNode): node is TSExternalModuleReference { return node instanceof TSExternalModuleReference } -if (!nodeByType.has(89)) { - nodeByType.set(89, TSExternalModuleReference) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE, TSExternalModuleReference) +} diff --git a/koala-wrapper/src/generated/peers/TSFunctionType.ts b/koala-wrapper/src/generated/peers/TSFunctionType.ts index f65d2fa56..6f2df8cb4 100644 --- a/koala-wrapper/src/generated/peers/TSFunctionType.ts +++ b/koala-wrapper/src/generated/peers/TSFunctionType.ts @@ -35,7 +35,7 @@ import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" import { Expression } from "./Expression" export class TSFunctionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 125) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_FUNCTION_TYPE) super(pointer) } @@ -63,6 +63,6 @@ export class TSFunctionType extends TypeNode { export function isTSFunctionType(node: AstNode): node is TSFunctionType { return node instanceof TSFunctionType } -if (!nodeByType.has(125)) { - nodeByType.set(125, TSFunctionType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_FUNCTION_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_FUNCTION_TYPE, TSFunctionType) +} diff --git a/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts b/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts index a04b88379..6f561a769 100644 --- a/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts @@ -34,7 +34,7 @@ import { Identifier } from "./Identifier" import { Expression } from "./Expression" export class TSImportEqualsDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 124) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION) super(pointer) } @@ -57,6 +57,6 @@ export class TSImportEqualsDeclaration extends Statement { export function isTSImportEqualsDeclaration(node: AstNode): node is TSImportEqualsDeclaration { return node instanceof TSImportEqualsDeclaration } -if (!nodeByType.has(124)) { - nodeByType.set(124, TSImportEqualsDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION, TSImportEqualsDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/TSImportType.ts b/koala-wrapper/src/generated/peers/TSImportType.ts index 43e08e49a..7f57afe79 100644 --- a/koala-wrapper/src/generated/peers/TSImportType.ts +++ b/koala-wrapper/src/generated/peers/TSImportType.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class TSImportType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 112) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_TYPE) super(pointer) } @@ -60,6 +60,6 @@ export class TSImportType extends TypeNode { export function isTSImportType(node: AstNode): node is TSImportType { return node instanceof TSImportType } -if (!nodeByType.has(112)) { - nodeByType.set(112, TSImportType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_TYPE, TSImportType) +} diff --git a/koala-wrapper/src/generated/peers/TSIndexSignature.ts b/koala-wrapper/src/generated/peers/TSIndexSignature.ts index 6a7bf5ea9..827218b25 100644 --- a/koala-wrapper/src/generated/peers/TSIndexSignature.ts +++ b/koala-wrapper/src/generated/peers/TSIndexSignature.ts @@ -35,7 +35,7 @@ import { TypeNode } from "./TypeNode" import { Es2pandaTSIndexSignatureKind } from "./../Es2pandaEnums" export class TSIndexSignature extends TypedAstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 136) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEX_SIGNATURE) super(pointer) } @@ -58,6 +58,6 @@ export class TSIndexSignature extends TypedAstNode { export function isTSIndexSignature(node: AstNode): node is TSIndexSignature { return node instanceof TSIndexSignature } -if (!nodeByType.has(136)) { - nodeByType.set(136, TSIndexSignature) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEX_SIGNATURE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEX_SIGNATURE, TSIndexSignature) +} diff --git a/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts b/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts index edb3a5c1f..7faab853a 100644 --- a/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts +++ b/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSIndexedAccessType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 130) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE) super(pointer) } @@ -52,6 +52,6 @@ export class TSIndexedAccessType extends TypeNode { export function isTSIndexedAccessType(node: AstNode): node is TSIndexedAccessType { return node instanceof TSIndexedAccessType } -if (!nodeByType.has(130)) { - nodeByType.set(130, TSIndexedAccessType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE, TSIndexedAccessType) +} diff --git a/koala-wrapper/src/generated/peers/TSInferType.ts b/koala-wrapper/src/generated/peers/TSInferType.ts index f2a5d6597..aea447732 100644 --- a/koala-wrapper/src/generated/peers/TSInferType.ts +++ b/koala-wrapper/src/generated/peers/TSInferType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { TSTypeParameter } from "./TSTypeParameter" export class TSInferType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 110) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INFER_TYPE) super(pointer) } @@ -50,6 +50,6 @@ export class TSInferType extends TypeNode { export function isTSInferType(node: AstNode): node is TSInferType { return node instanceof TSInferType } -if (!nodeByType.has(110)) { - nodeByType.set(110, TSInferType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INFER_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INFER_TYPE, TSInferType) +} diff --git a/koala-wrapper/src/generated/peers/TSInterfaceBody.ts b/koala-wrapper/src/generated/peers/TSInterfaceBody.ts index 103fa4a1a..fa9c4e80a 100644 --- a/koala-wrapper/src/generated/peers/TSInterfaceBody.ts +++ b/koala-wrapper/src/generated/peers/TSInterfaceBody.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TSInterfaceBody extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 132) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_BODY) super(pointer) } @@ -52,6 +52,6 @@ export class TSInterfaceBody extends Expression { export function isTSInterfaceBody(node: AstNode): node is TSInterfaceBody { return node instanceof TSInterfaceBody } -if (!nodeByType.has(132)) { - nodeByType.set(132, TSInterfaceBody) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_BODY)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_BODY, TSInterfaceBody) +} diff --git a/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts b/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts index 21c064fcf..a44a0c8e6 100644 --- a/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts @@ -39,7 +39,7 @@ import { ClassDeclaration } from "./ClassDeclaration" import { AnnotationUsage } from "./AnnotationUsage" export class TSInterfaceDeclaration extends TypedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 131) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_DECLARATION) super(pointer) } @@ -98,6 +98,6 @@ export class TSInterfaceDeclaration extends TypedStatement { export function isTSInterfaceDeclaration(node: AstNode): node is TSInterfaceDeclaration { return node instanceof TSInterfaceDeclaration } -if (!nodeByType.has(131)) { - nodeByType.set(131, TSInterfaceDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_DECLARATION, TSInterfaceDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts b/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts index 4af6bfb0f..4b22c6eaa 100644 --- a/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts +++ b/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSInterfaceHeritage extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 133) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_HERITAGE) super(pointer) } @@ -50,6 +50,6 @@ export class TSInterfaceHeritage extends Expression { export function isTSInterfaceHeritage(node: AstNode): node is TSInterfaceHeritage { return node instanceof TSInterfaceHeritage } -if (!nodeByType.has(133)) { - nodeByType.set(133, TSInterfaceHeritage) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_HERITAGE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_HERITAGE, TSInterfaceHeritage) +} diff --git a/koala-wrapper/src/generated/peers/TSIntersectionType.ts b/koala-wrapper/src/generated/peers/TSIntersectionType.ts index d21f48d7a..8f58edf65 100644 --- a/koala-wrapper/src/generated/peers/TSIntersectionType.ts +++ b/koala-wrapper/src/generated/peers/TSIntersectionType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSIntersectionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 113) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERSECTION_TYPE) super(pointer) } @@ -50,6 +50,6 @@ export class TSIntersectionType extends TypeNode { export function isTSIntersectionType(node: AstNode): node is TSIntersectionType { return node instanceof TSIntersectionType } -if (!nodeByType.has(113)) { - nodeByType.set(113, TSIntersectionType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERSECTION_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERSECTION_TYPE, TSIntersectionType) +} diff --git a/koala-wrapper/src/generated/peers/TSLiteralType.ts b/koala-wrapper/src/generated/peers/TSLiteralType.ts index f9ecdf774..a3ea5c9c1 100644 --- a/koala-wrapper/src/generated/peers/TSLiteralType.ts +++ b/koala-wrapper/src/generated/peers/TSLiteralType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSLiteralType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 109) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE) super(pointer) } @@ -50,6 +50,6 @@ export class TSLiteralType extends TypeNode { export function isTSLiteralType(node: AstNode): node is TSLiteralType { return node instanceof TSLiteralType } -if (!nodeByType.has(109)) { - nodeByType.set(109, TSLiteralType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE, TSLiteralType) +} diff --git a/koala-wrapper/src/generated/peers/TSMappedType.ts b/koala-wrapper/src/generated/peers/TSMappedType.ts index e8a2202dc..dc8344d7c 100644 --- a/koala-wrapper/src/generated/peers/TSMappedType.ts +++ b/koala-wrapper/src/generated/peers/TSMappedType.ts @@ -34,7 +34,7 @@ import { TSTypeParameter } from "./TSTypeParameter" import { Es2pandaMappedOption } from "./../Es2pandaEnums" export class TSMappedType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 114) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_MAPPED_TYPE) super(pointer) } @@ -60,6 +60,6 @@ export class TSMappedType extends TypeNode { export function isTSMappedType(node: AstNode): node is TSMappedType { return node instanceof TSMappedType } -if (!nodeByType.has(114)) { - nodeByType.set(114, TSMappedType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MAPPED_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MAPPED_TYPE, TSMappedType) +} diff --git a/koala-wrapper/src/generated/peers/TSMethodSignature.ts b/koala-wrapper/src/generated/peers/TSMethodSignature.ts index d16351da0..f0d05604b 100644 --- a/koala-wrapper/src/generated/peers/TSMethodSignature.ts +++ b/koala-wrapper/src/generated/peers/TSMethodSignature.ts @@ -35,7 +35,7 @@ import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" import { TypeNode } from "./TypeNode" export class TSMethodSignature extends AstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 106) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_METHOD_SIGNATURE) super(pointer) } @@ -67,6 +67,6 @@ export class TSMethodSignature extends AstNode { export function isTSMethodSignature(node: AstNode): node is TSMethodSignature { return node instanceof TSMethodSignature } -if (!nodeByType.has(106)) { - nodeByType.set(106, TSMethodSignature) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_METHOD_SIGNATURE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_METHOD_SIGNATURE, TSMethodSignature) +} diff --git a/koala-wrapper/src/generated/peers/TSModuleBlock.ts b/koala-wrapper/src/generated/peers/TSModuleBlock.ts index d25d54f36..57f8c51a3 100644 --- a/koala-wrapper/src/generated/peers/TSModuleBlock.ts +++ b/koala-wrapper/src/generated/peers/TSModuleBlock.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class TSModuleBlock extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 115) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_BLOCK) super(pointer) } @@ -49,6 +49,6 @@ export class TSModuleBlock extends Statement { export function isTSModuleBlock(node: AstNode): node is TSModuleBlock { return node instanceof TSModuleBlock } -if (!nodeByType.has(115)) { - nodeByType.set(115, TSModuleBlock) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_BLOCK)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_BLOCK, TSModuleBlock) +} diff --git a/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts b/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts index c4582a84c..f78854027 100644 --- a/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class TSModuleDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 123) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_DECLARATION) super(pointer) } @@ -59,6 +59,6 @@ export class TSModuleDeclaration extends Statement { export function isTSModuleDeclaration(node: AstNode): node is TSModuleDeclaration { return node instanceof TSModuleDeclaration } -if (!nodeByType.has(123)) { - nodeByType.set(123, TSModuleDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_DECLARATION, TSModuleDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts b/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts index 3252f8a47..93085dfa1 100644 --- a/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts +++ b/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSNamedTupleMember extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 135) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER) super(pointer) } @@ -56,6 +56,6 @@ export class TSNamedTupleMember extends TypeNode { export function isTSNamedTupleMember(node: AstNode): node is TSNamedTupleMember { return node instanceof TSNamedTupleMember } -if (!nodeByType.has(135)) { - nodeByType.set(135, TSNamedTupleMember) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER, TSNamedTupleMember) +} diff --git a/koala-wrapper/src/generated/peers/TSNeverKeyword.ts b/koala-wrapper/src/generated/peers/TSNeverKeyword.ts index 39b7de7ff..039db43d4 100644 --- a/koala-wrapper/src/generated/peers/TSNeverKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSNeverKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSNeverKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 99) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NEVER_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSNeverKeyword extends TypeNode { export function isTSNeverKeyword(node: AstNode): node is TSNeverKeyword { return node instanceof TSNeverKeyword } -if (!nodeByType.has(99)) { - nodeByType.set(99, TSNeverKeyword) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NEVER_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NEVER_KEYWORD, TSNeverKeyword) +} diff --git a/koala-wrapper/src/generated/peers/TSNonNullExpression.ts b/koala-wrapper/src/generated/peers/TSNonNullExpression.ts index 21bc3e670..6ed71ba17 100644 --- a/koala-wrapper/src/generated/peers/TSNonNullExpression.ts +++ b/koala-wrapper/src/generated/peers/TSNonNullExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TSNonNullExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 100) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NON_NULL_EXPRESSION) super(pointer) } @@ -54,6 +54,6 @@ export class TSNonNullExpression extends Expression { export function isTSNonNullExpression(node: AstNode): node is TSNonNullExpression { return node instanceof TSNonNullExpression } -if (!nodeByType.has(100)) { - nodeByType.set(100, TSNonNullExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NON_NULL_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NON_NULL_EXPRESSION, TSNonNullExpression) +} diff --git a/koala-wrapper/src/generated/peers/TSNullKeyword.ts b/koala-wrapper/src/generated/peers/TSNullKeyword.ts index c3b161938..2abd26dfe 100644 --- a/koala-wrapper/src/generated/peers/TSNullKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSNullKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSNullKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 101) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NULL_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSNullKeyword extends TypeNode { export function isTSNullKeyword(node: AstNode): node is TSNullKeyword { return node instanceof TSNullKeyword } -if (!nodeByType.has(101)) { - nodeByType.set(101, TSNullKeyword) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NULL_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NULL_KEYWORD, TSNullKeyword) +} diff --git a/koala-wrapper/src/generated/peers/TSNumberKeyword.ts b/koala-wrapper/src/generated/peers/TSNumberKeyword.ts index ff3c783af..6620e5c98 100644 --- a/koala-wrapper/src/generated/peers/TSNumberKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSNumberKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSNumberKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 90) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NUMBER_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSNumberKeyword extends TypeNode { export function isTSNumberKeyword(node: AstNode): node is TSNumberKeyword { return node instanceof TSNumberKeyword } -if (!nodeByType.has(90)) { - nodeByType.set(90, TSNumberKeyword) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NUMBER_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NUMBER_KEYWORD, TSNumberKeyword) +} diff --git a/koala-wrapper/src/generated/peers/TSObjectKeyword.ts b/koala-wrapper/src/generated/peers/TSObjectKeyword.ts index 2279f62af..0a345482b 100644 --- a/koala-wrapper/src/generated/peers/TSObjectKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSObjectKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSObjectKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 97) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_OBJECT_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSObjectKeyword extends TypeNode { export function isTSObjectKeyword(node: AstNode): node is TSObjectKeyword { return node instanceof TSObjectKeyword } -if (!nodeByType.has(97)) { - nodeByType.set(97, TSObjectKeyword) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_OBJECT_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_OBJECT_KEYWORD, TSObjectKeyword) +} diff --git a/koala-wrapper/src/generated/peers/TSParameterProperty.ts b/koala-wrapper/src/generated/peers/TSParameterProperty.ts index 9efa642c8..fc86857ec 100644 --- a/koala-wrapper/src/generated/peers/TSParameterProperty.ts +++ b/koala-wrapper/src/generated/peers/TSParameterProperty.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaAccessibilityOption } from "./../Es2pandaEnums" export class TSParameterProperty extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 122) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARAMETER_PROPERTY) super(pointer) } @@ -62,6 +62,6 @@ export class TSParameterProperty extends Expression { export function isTSParameterProperty(node: AstNode): node is TSParameterProperty { return node instanceof TSParameterProperty } -if (!nodeByType.has(122)) { - nodeByType.set(122, TSParameterProperty) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARAMETER_PROPERTY)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARAMETER_PROPERTY, TSParameterProperty) +} diff --git a/koala-wrapper/src/generated/peers/TSParenthesizedType.ts b/koala-wrapper/src/generated/peers/TSParenthesizedType.ts index 043431f71..1171f2f04 100644 --- a/koala-wrapper/src/generated/peers/TSParenthesizedType.ts +++ b/koala-wrapper/src/generated/peers/TSParenthesizedType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSParenthesizedType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 108) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARENT_TYPE) super(pointer) } @@ -50,6 +50,6 @@ export class TSParenthesizedType extends TypeNode { export function isTSParenthesizedType(node: AstNode): node is TSParenthesizedType { return node instanceof TSParenthesizedType } -if (!nodeByType.has(108)) { - nodeByType.set(108, TSParenthesizedType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARENT_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARENT_TYPE, TSParenthesizedType) +} diff --git a/koala-wrapper/src/generated/peers/TSPropertySignature.ts b/koala-wrapper/src/generated/peers/TSPropertySignature.ts index b2725a964..cf57e262d 100644 --- a/koala-wrapper/src/generated/peers/TSPropertySignature.ts +++ b/koala-wrapper/src/generated/peers/TSPropertySignature.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSPropertySignature extends AnnotatedAstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 105) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_PROPERTY_SIGNATURE) super(pointer) } @@ -68,6 +68,6 @@ export class TSPropertySignature extends AnnotatedAstNode { export function isTSPropertySignature(node: AstNode): node is TSPropertySignature { return node instanceof TSPropertySignature } -if (!nodeByType.has(105)) { - nodeByType.set(105, TSPropertySignature) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PROPERTY_SIGNATURE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PROPERTY_SIGNATURE, TSPropertySignature) +} diff --git a/koala-wrapper/src/generated/peers/TSQualifiedName.ts b/koala-wrapper/src/generated/peers/TSQualifiedName.ts index e0f4d87ea..e9e4806ef 100644 --- a/koala-wrapper/src/generated/peers/TSQualifiedName.ts +++ b/koala-wrapper/src/generated/peers/TSQualifiedName.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Identifier } from "./Identifier" export class TSQualifiedName extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 129) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_QUALIFIED_NAME) super(pointer) } @@ -53,6 +53,6 @@ export class TSQualifiedName extends Expression { export function isTSQualifiedName(node: AstNode): node is TSQualifiedName { return node instanceof TSQualifiedName } -if (!nodeByType.has(129)) { - nodeByType.set(129, TSQualifiedName) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_QUALIFIED_NAME)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_QUALIFIED_NAME, TSQualifiedName) +} diff --git a/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts b/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts index e70bbf176..053a2dc3d 100644 --- a/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts @@ -37,7 +37,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSSignatureDeclaration extends TypedAstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 107) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_SIGNATURE_DECLARATION) super(pointer) } @@ -63,6 +63,6 @@ export class TSSignatureDeclaration extends TypedAstNode { export function isTSSignatureDeclaration(node: AstNode): node is TSSignatureDeclaration { return node instanceof TSSignatureDeclaration } -if (!nodeByType.has(107)) { - nodeByType.set(107, TSSignatureDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_SIGNATURE_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_SIGNATURE_DECLARATION, TSSignatureDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/TSStringKeyword.ts b/koala-wrapper/src/generated/peers/TSStringKeyword.ts index 6f749be33..71fb6c6b1 100644 --- a/koala-wrapper/src/generated/peers/TSStringKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSStringKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSStringKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 92) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_STRING_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSStringKeyword extends TypeNode { export function isTSStringKeyword(node: AstNode): node is TSStringKeyword { return node instanceof TSStringKeyword } -if (!nodeByType.has(92)) { - nodeByType.set(92, TSStringKeyword) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_STRING_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_STRING_KEYWORD, TSStringKeyword) +} diff --git a/koala-wrapper/src/generated/peers/TSThisType.ts b/koala-wrapper/src/generated/peers/TSThisType.ts index e57be0ab0..7a87d159c 100644 --- a/koala-wrapper/src/generated/peers/TSThisType.ts +++ b/koala-wrapper/src/generated/peers/TSThisType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSThisType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 116) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_THIS_TYPE) super(pointer) } @@ -46,6 +46,6 @@ export class TSThisType extends TypeNode { export function isTSThisType(node: AstNode): node is TSThisType { return node instanceof TSThisType } -if (!nodeByType.has(116)) { - nodeByType.set(116, TSThisType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_THIS_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_THIS_TYPE, TSThisType) +} diff --git a/koala-wrapper/src/generated/peers/TSTupleType.ts b/koala-wrapper/src/generated/peers/TSTupleType.ts index 11bafff08..8780f3e66 100644 --- a/koala-wrapper/src/generated/peers/TSTupleType.ts +++ b/koala-wrapper/src/generated/peers/TSTupleType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSTupleType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 134) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TUPLE_TYPE) super(pointer) } @@ -49,6 +49,6 @@ export class TSTupleType extends TypeNode { export function isTSTupleType(node: AstNode): node is TSTupleType { return node instanceof TSTupleType } -if (!nodeByType.has(134)) { - nodeByType.set(134, TSTupleType) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TUPLE_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TUPLE_TYPE, TSTupleType) +} diff --git a/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts b/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts index 58e381c2d..025686869 100644 --- a/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts @@ -37,7 +37,7 @@ import { Decorator } from "./Decorator" import { AnnotationUsage } from "./AnnotationUsage" export class TSTypeAliasDeclaration extends AnnotatedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 127) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION) super(pointer) } @@ -87,6 +87,6 @@ export class TSTypeAliasDeclaration extends AnnotatedStatement { export function isTSTypeAliasDeclaration(node: AstNode): node is TSTypeAliasDeclaration { return node instanceof TSTypeAliasDeclaration } -if (!nodeByType.has(127)) { - nodeByType.set(127, TSTypeAliasDeclaration) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION, TSTypeAliasDeclaration) +} diff --git a/koala-wrapper/src/generated/peers/TSTypeAssertion.ts b/koala-wrapper/src/generated/peers/TSTypeAssertion.ts index e01615f9b..05bb8207b 100644 --- a/koala-wrapper/src/generated/peers/TSTypeAssertion.ts +++ b/koala-wrapper/src/generated/peers/TSTypeAssertion.ts @@ -34,7 +34,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSTypeAssertion extends AnnotatedExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 140) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ASSERTION) super(pointer) } @@ -59,6 +59,6 @@ export class TSTypeAssertion extends AnnotatedExpression { export function isTSTypeAssertion(node: AstNode): node is TSTypeAssertion { return node instanceof TSTypeAssertion } -if (!nodeByType.has(140)) { - nodeByType.set(140, TSTypeAssertion) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ASSERTION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ASSERTION, TSTypeAssertion) +} diff --git a/koala-wrapper/src/generated/peers/TSTypeLiteral.ts b/koala-wrapper/src/generated/peers/TSTypeLiteral.ts index 20e3a4f22..c6f790a26 100644 --- a/koala-wrapper/src/generated/peers/TSTypeLiteral.ts +++ b/koala-wrapper/src/generated/peers/TSTypeLiteral.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSTypeLiteral extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 104) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE) super(pointer) } @@ -49,6 +49,6 @@ export class TSTypeLiteral extends TypeNode { export function isTSTypeLiteral(node: AstNode): node is TSTypeLiteral { return node instanceof TSTypeLiteral } -if (!nodeByType.has(104)) { - nodeByType.set(104, TSTypeLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE, TSTypeLiteral) +} diff --git a/koala-wrapper/src/generated/peers/TSTypeOperator.ts b/koala-wrapper/src/generated/peers/TSTypeOperator.ts index 3f94d244f..e082c1075 100644 --- a/koala-wrapper/src/generated/peers/TSTypeOperator.ts +++ b/koala-wrapper/src/generated/peers/TSTypeOperator.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Es2pandaTSOperatorType } from "./../Es2pandaEnums" export class TSTypeOperator extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 117) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_OPERATOR) super(pointer) } @@ -59,6 +59,6 @@ export class TSTypeOperator extends TypeNode { export function isTSTypeOperator(node: AstNode): node is TSTypeOperator { return node instanceof TSTypeOperator } -if (!nodeByType.has(117)) { - nodeByType.set(117, TSTypeOperator) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_OPERATOR)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_OPERATOR, TSTypeOperator) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameter.ts b/koala-wrapper/src/generated/peers/TSTypeParameter.ts index 28012faf1..7451ad017 100644 --- a/koala-wrapper/src/generated/peers/TSTypeParameter.ts +++ b/koala-wrapper/src/generated/peers/TSTypeParameter.ts @@ -36,7 +36,7 @@ import { Es2pandaModifierFlags } from "./../Es2pandaEnums" import { AnnotationUsage } from "./AnnotationUsage" export class TSTypeParameter extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 118) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER) super(pointer) } @@ -83,6 +83,6 @@ export class TSTypeParameter extends Expression { export function isTSTypeParameter(node: AstNode): node is TSTypeParameter { return node instanceof TSTypeParameter } -if (!nodeByType.has(118)) { - nodeByType.set(118, TSTypeParameter) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER, TSTypeParameter) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts b/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts index 59f4ab594..61f91a8b6 100644 --- a/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TSTypeParameter } from "./TSTypeParameter" export class TSTypeParameterDeclaration extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 119) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION) super(pointer) } @@ -58,6 +58,6 @@ export class TSTypeParameterDeclaration extends Expression { export function isTSTypeParameterDeclaration(node: AstNode): node is TSTypeParameterDeclaration { return node instanceof TSTypeParameterDeclaration } -if (!nodeByType.has(119)) { - nodeByType.set(119, TSTypeParameterDeclaration) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION, TSTypeParameterDeclaration) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts b/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts index b6a23b329..8c30a3aa0 100644 --- a/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts +++ b/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSTypeParameterInstantiation extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 120) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION) super(pointer) } @@ -50,6 +50,6 @@ export class TSTypeParameterInstantiation extends Expression { export function isTSTypeParameterInstantiation(node: AstNode): node is TSTypeParameterInstantiation { return node instanceof TSTypeParameterInstantiation } -if (!nodeByType.has(120)) { - nodeByType.set(120, TSTypeParameterInstantiation) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION, TSTypeParameterInstantiation) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypePredicate.ts b/koala-wrapper/src/generated/peers/TSTypePredicate.ts index 551d62f98..27ce97a73 100644 --- a/koala-wrapper/src/generated/peers/TSTypePredicate.ts +++ b/koala-wrapper/src/generated/peers/TSTypePredicate.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSTypePredicate extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 121) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PREDICATE) super(pointer) } @@ -56,6 +56,6 @@ export class TSTypePredicate extends TypeNode { export function isTSTypePredicate(node: AstNode): node is TSTypePredicate { return node instanceof TSTypePredicate } -if (!nodeByType.has(121)) { - nodeByType.set(121, TSTypePredicate) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PREDICATE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PREDICATE, TSTypePredicate) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeQuery.ts b/koala-wrapper/src/generated/peers/TSTypeQuery.ts index d4576d1fa..603124f7f 100644 --- a/koala-wrapper/src/generated/peers/TSTypeQuery.ts +++ b/koala-wrapper/src/generated/peers/TSTypeQuery.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSTypeQuery extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 137) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_QUERY) super(pointer) } @@ -50,6 +50,6 @@ export class TSTypeQuery extends TypeNode { export function isTSTypeQuery(node: AstNode): node is TSTypeQuery { return node instanceof TSTypeQuery } -if (!nodeByType.has(137)) { - nodeByType.set(137, TSTypeQuery) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_QUERY)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_QUERY, TSTypeQuery) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeReference.ts b/koala-wrapper/src/generated/peers/TSTypeReference.ts index 50e62aafb..f70f708c7 100644 --- a/koala-wrapper/src/generated/peers/TSTypeReference.ts +++ b/koala-wrapper/src/generated/peers/TSTypeReference.ts @@ -35,7 +35,7 @@ import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" import { Identifier } from "./Identifier" export class TSTypeReference extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 128) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_REFERENCE) super(pointer) } @@ -55,6 +55,6 @@ export class TSTypeReference extends TypeNode { export function isTSTypeReference(node: AstNode): node is TSTypeReference { return node instanceof TSTypeReference } -if (!nodeByType.has(128)) { - nodeByType.set(128, TSTypeReference) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_REFERENCE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_REFERENCE, TSTypeReference) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts b/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts index 9129d02d9..c7809258a 100644 --- a/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSUndefinedKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 95) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNDEFINED_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSUndefinedKeyword extends TypeNode { export function isTSUndefinedKeyword(node: AstNode): node is TSUndefinedKeyword { return node instanceof TSUndefinedKeyword } -if (!nodeByType.has(95)) { - nodeByType.set(95, TSUndefinedKeyword) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNDEFINED_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNDEFINED_KEYWORD, TSUndefinedKeyword) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUnionType.ts b/koala-wrapper/src/generated/peers/TSUnionType.ts index 406ecc416..df5479501 100644 --- a/koala-wrapper/src/generated/peers/TSUnionType.ts +++ b/koala-wrapper/src/generated/peers/TSUnionType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSUnionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 103) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE) super(pointer) } @@ -49,6 +49,6 @@ export class TSUnionType extends TypeNode { export function isTSUnionType(node: AstNode): node is TSUnionType { return node instanceof TSUnionType } -if (!nodeByType.has(103)) { - nodeByType.set(103, TSUnionType) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE, TSUnionType) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts b/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts index 0371b243c..0eb71b7d2 100644 --- a/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSUnknownKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 96) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNKNOWN_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSUnknownKeyword extends TypeNode { export function isTSUnknownKeyword(node: AstNode): node is TSUnknownKeyword { return node instanceof TSUnknownKeyword } -if (!nodeByType.has(96)) { - nodeByType.set(96, TSUnknownKeyword) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNKNOWN_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNKNOWN_KEYWORD, TSUnknownKeyword) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSVoidKeyword.ts b/koala-wrapper/src/generated/peers/TSVoidKeyword.ts index 605cceb11..1cfe4091d 100644 --- a/koala-wrapper/src/generated/peers/TSVoidKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSVoidKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSVoidKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 94) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_VOID_KEYWORD) super(pointer) } @@ -46,6 +46,6 @@ export class TSVoidKeyword extends TypeNode { export function isTSVoidKeyword(node: AstNode): node is TSVoidKeyword { return node instanceof TSVoidKeyword } -if (!nodeByType.has(94)) { - nodeByType.set(94, TSVoidKeyword) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_VOID_KEYWORD)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_VOID_KEYWORD, TSVoidKeyword) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts b/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts index 0ccbf0f08..1f1a7dcc1 100644 --- a/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts +++ b/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts @@ -34,7 +34,7 @@ import { TemplateLiteral } from "./TemplateLiteral" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class TaggedTemplateExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 141) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION) super(pointer) } @@ -57,6 +57,6 @@ export class TaggedTemplateExpression extends Expression { export function isTaggedTemplateExpression(node: AstNode): node is TaggedTemplateExpression { return node instanceof TaggedTemplateExpression } -if (!nodeByType.has(141)) { - nodeByType.set(141, TaggedTemplateExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION, TaggedTemplateExpression) +} diff --git a/koala-wrapper/src/generated/peers/TemplateElement.ts b/koala-wrapper/src/generated/peers/TemplateElement.ts index 0c4108f47..32602cccc 100644 --- a/koala-wrapper/src/generated/peers/TemplateElement.ts +++ b/koala-wrapper/src/generated/peers/TemplateElement.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TemplateElement extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 142) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_ELEMENT) super(pointer) } @@ -58,6 +58,6 @@ export class TemplateElement extends Expression { export function isTemplateElement(node: AstNode): node is TemplateElement { return node instanceof TemplateElement } -if (!nodeByType.has(142)) { - nodeByType.set(142, TemplateElement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_ELEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_ELEMENT, TemplateElement) +} diff --git a/koala-wrapper/src/generated/peers/TemplateLiteral.ts b/koala-wrapper/src/generated/peers/TemplateLiteral.ts index 58039a87e..f67bc25da 100644 --- a/koala-wrapper/src/generated/peers/TemplateLiteral.ts +++ b/koala-wrapper/src/generated/peers/TemplateLiteral.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TemplateElement } from "./TemplateElement" export class TemplateLiteral extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 143) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_LITERAL) super(pointer) } @@ -53,6 +53,6 @@ export class TemplateLiteral extends Expression { export function isTemplateLiteral(node: AstNode): node is TemplateLiteral { return node instanceof TemplateLiteral } -if (!nodeByType.has(143)) { - nodeByType.set(143, TemplateLiteral) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_LITERAL, TemplateLiteral) +} diff --git a/koala-wrapper/src/generated/peers/ThisExpression.ts b/koala-wrapper/src/generated/peers/ThisExpression.ts index 1ec6476d8..c16668c4f 100644 --- a/koala-wrapper/src/generated/peers/ThisExpression.ts +++ b/koala-wrapper/src/generated/peers/ThisExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ThisExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 144) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_THIS_EXPRESSION) super(pointer) } @@ -46,6 +46,6 @@ export class ThisExpression extends Expression { export function isThisExpression(node: AstNode): node is ThisExpression { return node instanceof ThisExpression } -if (!nodeByType.has(144)) { - nodeByType.set(144, ThisExpression) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_THIS_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_THIS_EXPRESSION, ThisExpression) +} diff --git a/koala-wrapper/src/generated/peers/ThrowStatement.ts b/koala-wrapper/src/generated/peers/ThrowStatement.ts index 74cc30e59..e4f40a1fb 100644 --- a/koala-wrapper/src/generated/peers/ThrowStatement.ts +++ b/koala-wrapper/src/generated/peers/ThrowStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class ThrowStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 146) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_THROW_STATEMENT) super(pointer) } @@ -50,6 +50,6 @@ export class ThrowStatement extends Statement { export function isThrowStatement(node: AstNode): node is ThrowStatement { return node instanceof ThrowStatement } -if (!nodeByType.has(146)) { - nodeByType.set(146, ThrowStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_THROW_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_THROW_STATEMENT, ThrowStatement) +} diff --git a/koala-wrapper/src/generated/peers/TryStatement.ts b/koala-wrapper/src/generated/peers/TryStatement.ts index c855b8bfa..dd3a7571d 100644 --- a/koala-wrapper/src/generated/peers/TryStatement.ts +++ b/koala-wrapper/src/generated/peers/TryStatement.ts @@ -34,7 +34,7 @@ import { BlockStatement } from "./BlockStatement" import { CatchClause } from "./CatchClause" export class TryStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 147) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT) super(pointer) } @@ -62,6 +62,6 @@ export class TryStatement extends Statement { export function isTryStatement(node: AstNode): node is TryStatement { return node instanceof TryStatement } -if (!nodeByType.has(147)) { - nodeByType.set(147, TryStatement) -} \ No newline at end of file +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT, TryStatement) +} diff --git a/koala-wrapper/src/generated/peers/TypeofExpression.ts b/koala-wrapper/src/generated/peers/TypeofExpression.ts index 0c80ae8e8..8496fe19c 100644 --- a/koala-wrapper/src/generated/peers/TypeofExpression.ts +++ b/koala-wrapper/src/generated/peers/TypeofExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TypeofExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 145) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TYPEOF_EXPRESSION) super(pointer) } @@ -49,6 +49,6 @@ export class TypeofExpression extends Expression { export function isTypeofExpression(node: AstNode): node is TypeofExpression { return node instanceof TypeofExpression } -if (!nodeByType.has(145)) { - nodeByType.set(145, TypeofExpression) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TYPEOF_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TYPEOF_EXPRESSION, TypeofExpression) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UnaryExpression.ts b/koala-wrapper/src/generated/peers/UnaryExpression.ts index 2b2d1aec7..88a9071dc 100644 --- a/koala-wrapper/src/generated/peers/UnaryExpression.ts +++ b/koala-wrapper/src/generated/peers/UnaryExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaTokenType } from "./../Es2pandaEnums" export class UnaryExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 148) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_UNARY_EXPRESSION) super(pointer) } @@ -53,6 +53,6 @@ export class UnaryExpression extends Expression { export function isUnaryExpression(node: AstNode): node is UnaryExpression { return node instanceof UnaryExpression } -if (!nodeByType.has(148)) { - nodeByType.set(148, UnaryExpression) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_UNARY_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_UNARY_EXPRESSION, UnaryExpression) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UndefinedLiteral.ts b/koala-wrapper/src/generated/peers/UndefinedLiteral.ts index 833805c1f..b50432720 100644 --- a/koala-wrapper/src/generated/peers/UndefinedLiteral.ts +++ b/koala-wrapper/src/generated/peers/UndefinedLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class UndefinedLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 51) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL) super(pointer) } @@ -46,6 +46,6 @@ export class UndefinedLiteral extends Literal { export function isUndefinedLiteral(node: AstNode): node is UndefinedLiteral { return node instanceof UndefinedLiteral } -if (!nodeByType.has(51)) { - nodeByType.set(51, UndefinedLiteral) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL, UndefinedLiteral) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UpdateExpression.ts b/koala-wrapper/src/generated/peers/UpdateExpression.ts index 5c1b8d6f1..30d9f1839 100644 --- a/koala-wrapper/src/generated/peers/UpdateExpression.ts +++ b/koala-wrapper/src/generated/peers/UpdateExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaTokenType } from "./../Es2pandaEnums" export class UpdateExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 149) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_UPDATE_EXPRESSION) super(pointer) } @@ -56,6 +56,6 @@ export class UpdateExpression extends Expression { export function isUpdateExpression(node: AstNode): node is UpdateExpression { return node instanceof UpdateExpression } -if (!nodeByType.has(149)) { - nodeByType.set(149, UpdateExpression) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_UPDATE_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_UPDATE_EXPRESSION, UpdateExpression) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/VariableDeclaration.ts b/koala-wrapper/src/generated/peers/VariableDeclaration.ts index 751968ae5..6699e1f55 100644 --- a/koala-wrapper/src/generated/peers/VariableDeclaration.ts +++ b/koala-wrapper/src/generated/peers/VariableDeclaration.ts @@ -36,7 +36,7 @@ import { Decorator } from "./Decorator" import { AnnotationUsage } from "./AnnotationUsage" export class VariableDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 150) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION) super(pointer) } @@ -67,6 +67,6 @@ export class VariableDeclaration extends Statement { export function isVariableDeclaration(node: AstNode): node is VariableDeclaration { return node instanceof VariableDeclaration } -if (!nodeByType.has(150)) { - nodeByType.set(150, VariableDeclaration) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION, VariableDeclaration) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/VariableDeclarator.ts b/koala-wrapper/src/generated/peers/VariableDeclarator.ts index e0d9cb077..3913fc3d6 100644 --- a/koala-wrapper/src/generated/peers/VariableDeclarator.ts +++ b/koala-wrapper/src/generated/peers/VariableDeclarator.ts @@ -34,7 +34,7 @@ import { Es2pandaVariableDeclaratorFlag } from "./../Es2pandaEnums" import { Expression } from "./Expression" export class VariableDeclarator extends TypedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 151) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR) super(pointer) } @@ -68,6 +68,6 @@ export class VariableDeclarator extends TypedStatement { export function isVariableDeclarator(node: AstNode): node is VariableDeclarator { return node instanceof VariableDeclarator } -if (!nodeByType.has(151)) { - nodeByType.set(151, VariableDeclarator) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR, VariableDeclarator) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/WhileStatement.ts b/koala-wrapper/src/generated/peers/WhileStatement.ts index f71a1d5dd..548fd8bf2 100644 --- a/koala-wrapper/src/generated/peers/WhileStatement.ts +++ b/koala-wrapper/src/generated/peers/WhileStatement.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Statement } from "./Statement" export class WhileStatement extends LoopStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 152) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_WHILE_STATEMENT) super(pointer) } @@ -54,6 +54,6 @@ export class WhileStatement extends LoopStatement { export function isWhileStatement(node: AstNode): node is WhileStatement { return node instanceof WhileStatement } -if (!nodeByType.has(152)) { - nodeByType.set(152, WhileStatement) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_WHILE_STATEMENT)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_WHILE_STATEMENT, WhileStatement) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/YieldExpression.ts b/koala-wrapper/src/generated/peers/YieldExpression.ts index 55c0b9022..90846a933 100644 --- a/koala-wrapper/src/generated/peers/YieldExpression.ts +++ b/koala-wrapper/src/generated/peers/YieldExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class YieldExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, 153) + assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_YIELD_EXPRESSION) super(pointer) } @@ -52,6 +52,6 @@ export class YieldExpression extends Expression { export function isYieldExpression(node: AstNode): node is YieldExpression { return node instanceof YieldExpression } -if (!nodeByType.has(153)) { - nodeByType.set(153, YieldExpression) +if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_YIELD_EXPRESSION)) { + nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_YIELD_EXPRESSION, YieldExpression) } \ No newline at end of file -- Gitee From 286757c523c042cc8ec9e973f805fb4c3923fcee Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Tue, 8 Apr 2025 22:39:25 +0800 Subject: [PATCH 030/123] add irrelevant header files Signed-off-by: Jiakai Shi Change-Id: I1b098bfe1c2d2d49df003d0b836b577242a53f00 --- arkui-plugins/common/arkts-utils.ts | 61 ++++++++++++++++++------- arkui-plugins/common/predefines.ts | 14 +++++- arkui-plugins/common/program-visitor.ts | 6 +-- 3 files changed, 60 insertions(+), 21 deletions(-) diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index f79340995..86f04a280 100644 --- a/arkui-plugins/common/arkts-utils.ts +++ b/arkui-plugins/common/arkts-utils.ts @@ -13,24 +13,32 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; export function annotation(name: string): arkts.AnnotationUsage { - const ident: arkts.Identifier = arkts.factory.createIdentifier(name).setAnnotationUsage(); - const annotation: arkts.AnnotationUsage = arkts.factory.createAnnotationUsage(ident); + const ident: arkts.Identifier = arkts.factory + .createIdentifier(name) + .setAnnotationUsage(); + const annotation: arkts.AnnotationUsage = + arkts.factory.createAnnotationUsage(ident); - annotation.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ANNOTATION_USAGE; + annotation.modifiers = + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ANNOTATION_USAGE; ident.parent = annotation; return annotation; } export function isAnnotation(node: arkts.AnnotationUsage, annoName: string) { - return node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === annoName; + return ( + node.expr !== undefined && + arkts.isIdentifier(node.expr) && + node.expr.name === annoName + ); } export function removeAnnotationByName( - annotations: readonly arkts.AnnotationUsage[], + annotations: readonly arkts.AnnotationUsage[], annoName: string ): arkts.AnnotationUsage[] { return annotations.filter((it) => !isAnnotation(it, annoName)); @@ -38,10 +46,12 @@ export function removeAnnotationByName( export function expectName(node: arkts.AstNode | undefined): string { if (!node) { - throw new Error("Expected an identifier, got empty node"); + throw new Error('Expected an identifier, got empty node'); } if (!arkts.isIdentifier(node)) { - throw new Error("Expected an identifier, got: " + arkts.nodeType(node).toString()); + throw new Error( + 'Expected an identifier, got: ' + arkts.nodeType(node).toString() + ); } return node.name; } @@ -58,14 +68,27 @@ export function filterDefined(value: (T | undefined)[]): T[] { return value.filter((it: T | undefined): it is T => it != undefined); } -export function collect(...value: (ReadonlyArray | T | undefined)[]): T[] { - const empty: (T | undefined)[] = [] - return filterDefined(empty.concat(...value)) +export function collect( + ...value: (ReadonlyArray | T | undefined)[] +): T[] { + const empty: (T | undefined)[] = []; + return filterDefined(empty.concat(...value)); } -export function matchPrefix(prefixCollection: string[], name: string): boolean { +export function matchPrefix( + prefixCollection: (string | RegExp)[], + name: string +): boolean { for (const prefix of prefixCollection) { - if (name.startsWith(prefix)) { + let regex: RegExp; + + if (typeof prefix === 'string') { + regex = new RegExp('^' + prefix); + } else { + regex = new RegExp('^' + prefix.source); + } + + if (regex.test(name)) { return true; } } @@ -79,8 +102,14 @@ export function updateStructMetadata( modifiers: arkts.Es2pandaModifierFlags, hasStateManagementType?: boolean ): arkts.StructInfo { - const metadata: Record = structInfo.metadata ?? {}; - metadata[propertyName] = { name: propertyName, properties, modifiers, hasStateManagementType }; + const metadata: Record = + structInfo.metadata ?? {}; + metadata[propertyName] = { + name: propertyName, + properties, + modifiers, + hasStateManagementType, + }; structInfo.metadata = metadata; return structInfo; -} \ No newline at end of file +} diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 0f22930da..6d52388c5 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -13,9 +13,19 @@ * limitations under the License. */ -export const EXTERNAL_SOURCE_PREFIX_NAMES: string[] = [ +export const EXTERNAL_SOURCE_PREFIX_NAMES: (string | RegExp)[] = [ "std", - "escompat" + "escompat", + "security", + "application", + "permissions", + "bundleManager", + "commonEvent", + /@arkts\..*/, + /@ohos\.(?!arkui).*/, + /@system\..*/, + /arkui\.(?![Uu]serView$)[A-Z]/, // temporary solution + /ability\..*/, ]; export const ARKUI_COMPONENT_IMPORT_NAME: string = "@ohos.arkui.component"; diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 4dcfc724f..b0ada269d 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -24,7 +24,7 @@ export interface ProgramVisitorOptions extends VisitorOptions { pluginName: string; state: arkts.Es2pandaContextState; visitors: AbstractVisitor[]; - skipPrefixNames: string[]; + skipPrefixNames: (string | RegExp)[]; hooks?: ProgramHooks; pluginContext?: PluginContext; } @@ -80,7 +80,7 @@ export class ProgramVisitor extends AbstractVisitor { private readonly pluginName: string; private readonly state: arkts.Es2pandaContextState; private readonly visitors: AbstractVisitor[]; - private readonly skipPrefixNames: string[]; + private readonly skipPrefixNames: (string | RegExp)[]; private readonly hooks?: ProgramHooks; private filenames: Map; private pluginContext?: PluginContext; @@ -102,7 +102,7 @@ export class ProgramVisitor extends AbstractVisitor { } programVisitor(program: arkts.Program): arkts.Program { - const skipPrefixes: string[] = this.skipPrefixNames; + const skipPrefixes: (string | RegExp)[] = this.skipPrefixNames; const visited = new Set(); const queue: arkts.Program[] = [program]; -- Gitee From 6f43b4c8f58e2fbc8c0595a61cbe90579389fcb4 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Tue, 8 Apr 2025 17:22:34 +0800 Subject: [PATCH 031/123] merge struct-transformer and builder-lambda-transformer Signed-off-by: y00896775 Change-Id: I6b8b29d76afeeb66ad177ddd0b1007306c8955a1 --- .../instantiate-content.test.ts | 2 +- .../instantiate-multi-content.test.ts | 2 +- .../builder-lambda/instantiate.test.ts | 2 +- .../builder-lambda-transformer.ts | 274 ++++++ .../builder-lambda-translators/factory.ts | 162 ++++ .../builder-lambda-translators/utils.ts | 309 +++++++ ...-transformer.ts => checked-transformer.ts} | 780 ++++++++---------- .../ui-plugins/entry-translators/factory.ts | 139 ++-- arkui-plugins/ui-plugins/index.ts | 196 +++-- arkui-plugins/ui-plugins/name-collector.ts | 2 +- .../ui-plugins/struct-transformer.ts | 491 ----------- .../ui-plugins/struct-translators/factory.ts | 277 +++++++ .../struct-translators/struct-transformer.ts | 215 +++++ .../ui-plugins/struct-translators/utils.ts | 79 ++ arkui-plugins/ui-plugins/ui-factory.ts | 133 +-- arkui-plugins/ui-plugins/utils.ts | 81 -- 16 files changed, 1899 insertions(+), 1245 deletions(-) create mode 100644 arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts create mode 100644 arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts create mode 100644 arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts rename arkui-plugins/ui-plugins/{builder-lambda-transformer.ts => checked-transformer.ts} (34%) delete mode 100644 arkui-plugins/ui-plugins/struct-transformer.ts create mode 100644 arkui-plugins/ui-plugins/struct-translators/factory.ts create mode 100644 arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts create mode 100644 arkui-plugins/ui-plugins/struct-translators/utils.ts diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts index 16ddbc7f3..ba73b8157 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts @@ -21,7 +21,7 @@ import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; import { parseDumpSrc } from "../../../utils/parse-string"; import { PluginContext, Plugins } from "../../../../common/plugin-context"; import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; -import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-transformer"; +import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer"; const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda"); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts index 5170256d9..1279685ab 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts @@ -21,7 +21,7 @@ import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; import { parseDumpSrc } from "../../../utils/parse-string"; import { PluginContext, Plugins } from "../../../../common/plugin-context"; import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; -import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-transformer"; +import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer"; const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda"); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts index f7a104376..af9f56b59 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts @@ -21,7 +21,7 @@ import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; import { parseDumpSrc } from "../../../utils/parse-string"; import { PluginContext, Plugins } from "../../../../common/plugin-context"; import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; -import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-transformer"; +import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer"; const buildConfig: BuildConfig = mockBuildConfig(); buildConfig.compileFiles = [ diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts new file mode 100644 index 000000000..a0d1134c5 --- /dev/null +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor } from '../../common/abstract-visitor'; +import { BuilderLambdaNames } from '../utils'; +import { filterDefined, removeAnnotationByName, backingField } from '../../common/arkts-utils'; +import { DecoratorNames } from '../property-translators/utils'; +import { + BuilderLambdaDeclInfo, + isBuilderLambda, + builderLambdaFunctionName, + findBuilderLambdaDeclInfo, + isBuilderLambdaMethodDecl, + replaceBuilderLambdaDeclMethodName, + isBuilderLambdaFunctionCall, + callIsGoodForBuilderLambda, + builderLambdaTypeName, + builderLambdaMethodDeclType, + builderLambdaType, +} from './utils'; +import { factory } from './factory'; + +// TODO: very time-consuming... +function updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, isExternal?: boolean): arkts.AstNode { + if (arkts.isIfStatement(statement)) { + const alternate = !!statement.alternate + ? updateIfElseContentBodyInBuilderLambda(statement.alternate, isExternal) + : statement.alternate; + const consequence = updateIfElseContentBodyInBuilderLambda(statement.consequent, isExternal); + return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); + } + if (arkts.isBlockStatement(statement)) { + return arkts.factory.updateBlock( + statement, + statement.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) + ); + } + return statement; +} + +function updateContentBodyInBuilderLambda(statement: arkts.Statement, isExternal?: boolean): arkts.Statement { + if ( + arkts.isExpressionStatement(statement) && + arkts.isCallExpression(statement.expression) && + isBuilderLambda(statement.expression, isExternal) + ) { + return arkts.factory.updateExpressionStatement(statement, transformBuilderLambda(statement.expression)); + } + // TODO: very time-consuming... + if (arkts.isIfStatement(statement)) { + return updateIfElseContentBodyInBuilderLambda(statement, isExternal); + } + + return statement; +} + +function builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { + if (!callIsGoodForBuilderLambda(leaf)) { + return undefined; + } + const node = leaf.expression; + const funcName = builderLambdaFunctionName(leaf); + if (!funcName) { + return undefined; + } + if (arkts.isIdentifier(node)) { + return arkts.factory.createIdentifier(funcName); + } + if (arkts.isMemberExpression(node)) { + return arkts.factory.createMemberExpression( + node.object, + arkts.factory.createIdentifier(funcName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + node.computed, + node.optional + ); + } + return undefined; +} + +function createOrUpdateArgInBuilderLambda( + arg: arkts.Expression | undefined, + isExternal?: boolean, + typeName?: string, + fallback?: arkts.AstNode +): arkts.AstNode { + if (!arg) { + return fallback ?? arkts.factory.createUndefinedLiteral(); + } + if (arkts.isArrowFunctionExpression(arg)) { + return processArgArrowFunction(arg, isExternal); + } + if (arkts.isTSAsExpression(arg)) { + return processArgTSAsExpression(arg, typeName!); + } + return arg; +} + +function processArgArrowFunction( + arg: arkts.ArrowFunctionExpression, + isExternal?: boolean +): arkts.ArrowFunctionExpression { + const func: arkts.ScriptFunction = arg.scriptFunction; + const updateFunc = arkts.factory.updateScriptFunction( + func, + !!func.body && arkts.isBlockStatement(func.body) + ? arkts.factory.updateBlock( + func.body, + func.body.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) + ) + : undefined, + arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), + func.flags, + func.modifiers + ); + return arkts.factory.updateArrowFunction(arg, updateFunc); +} + +function updateParameterPassing( + prop: arkts.Property, + index: number, + currentStructInfo: arkts.StructInfo, + properties: arkts.Property[] +): void { + if ( + prop.key && + prop.value && + arkts.isIdentifier(prop.key) && + arkts.isMemberExpression(prop.value) && + arkts.isThisExpression(prop.value.object) && + arkts.isIdentifier(prop.value.property) + ) { + const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; + if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { + properties[index] = arkts.Property.updateProperty( + prop, + arkts.factory.createIdentifier(backingField(prop.key.name)), + factory.updateBackingMember(prop.value, prop.value.property.name) + ); + } + } +} + +function processArgTSAsExpression(arg: arkts.TSAsExpression, typeName: string): arkts.TSAsExpression { + if (!arg.expr || !arkts.isObjectExpression(arg.expr)) { + return arg; + } + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); + const properties = arg.expr.properties as arkts.Property[]; + properties.forEach((prop, index) => { + updateParameterPassing(prop, index, currentStructInfo, properties); + }); + const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( + arg.expr, + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + properties, + false + ); + return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); +} + +function generateArgsInBuilderLambda( + leaf: arkts.CallExpression, + lambdaBody: arkts.Identifier | arkts.CallExpression, + declInfo: BuilderLambdaDeclInfo, + isExternal?: boolean +): (arkts.AstNode | undefined)[] { + const { params } = declInfo; + const typeNode: arkts.TypeNode | undefined = builderLambdaType(leaf); + const typeName: string | undefined = builderLambdaTypeName(leaf); + const args: (arkts.AstNode | undefined)[] = [factory.createStyleArgInBuilderLambda(lambdaBody, typeNode)]; + let index = 0; + while (index < params.length) { + const isReusable: boolean = typeName + ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable + : false; + if (isReusable && index === params.length - 1) { + const reuseId = arkts.factory.createStringLiteral(typeName!); + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName, reuseId)); + } else { + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName)); + } + index++; + } + return args; +} + +function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { + let instanceCalls: arkts.CallExpression[] = []; + let leaf: arkts.CallExpression = node; + + while ( + true && + arkts.isMemberExpression(leaf.expression) && + arkts.isIdentifier(leaf.expression.property) && + arkts.isCallExpression(leaf.expression.object) + ) { + instanceCalls.push(arkts.factory.createCallExpression(leaf.expression.property, undefined, leaf.arguments)); + leaf = leaf.expression.object; + } + + const replace: arkts.Identifier | arkts.MemberExpression | undefined = builderLambdaReplace(leaf); + const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(leaf); + if (!replace || !declInfo) { + return node; + } + let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; + if (instanceCalls.length > 0) { + instanceCalls = instanceCalls.reverse(); + lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); + instanceCalls.forEach((call) => { + if (!arkts.isIdentifier(call.expression)) { + throw new Error('call expression should be identifier'); + } + lambdaBody = factory.createStyleLambdaBody(lambdaBody!, call); + }); + } + const args: (arkts.AstNode | undefined)[] = generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, isExternal); + return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); +} + +function transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { + const func: arkts.ScriptFunction = node.scriptFunction; + const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); + const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); + const styleArg: arkts.ETSParameterExpression = factory.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall); + return factory.updateBuilderLambdaMethodDecl( + node, + styleArg, + removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), + replaceBuilderLambdaDeclMethodName(node.name.name) + ); +} + +export class BuilderLambdaTransformer extends AbstractVisitor { + visitEachChild(node: arkts.AstNode): arkts.AstNode { + if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + return node; + } + if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + return node; + } + + return super.visitEachChild(node); + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + const node = this.visitEachChild(beforeChildren); + + if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + const lambda = transformBuilderLambda(node, this.isExternal); + return lambda; + } + if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + const lambda = transformBuilderLambdaMethodDecl(node); + return lambda; + } + + return node; + } +} diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts new file mode 100644 index 000000000..5cf2d1240 --- /dev/null +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -0,0 +1,162 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { BuilderLambdaNames } from '../utils'; +import { annotation, backingField } from '../../common/arkts-utils'; + +export class factory { + /* + * update @ComponentBuilder decorated method. + */ + static updateBuilderLambdaMethodDecl( + node: arkts.MethodDefinition, + styleArg: arkts.ETSParameterExpression, + newAnno: arkts.AnnotationUsage[], + newName: string | undefined + ): arkts.AstNode { + const func: arkts.ScriptFunction = node.scriptFunction; + const updateFunc = arkts.factory + .updateScriptFunction( + func, + func.body, + arkts.FunctionSignature.createFunctionSignature( + func.typeParams, + [styleArg, ...func.params], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + func.flags, + func.modifiers + ) + .setAnnotations(newAnno); + + return arkts.factory.updateMethodDefinition( + node, + node.kind, + arkts.factory.updateIdentifier(node.name, newName ?? node.name.name), + arkts.factory.createFunctionExpression(updateFunc), + node.modifiers, + false // TODO: how do I get it? + ); + } + + /* + * create style instance call, e.g. `instance.margin(10)`. + */ + static createStyleLambdaBody(lambdaBody: arkts.AstNode, call: arkts.CallExpression): arkts.CallExpression { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + lambdaBody, + call.expression, + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + call.arguments + ); + } + + /* + * update parameter passing, e.g. `: __backing_`. + */ + static updateBackingMember(val: arkts.MemberExpression, originName: string): arkts.MemberExpression { + return arkts.factory.updateMemberExpression( + val, + val.object, + arkts.factory.createIdentifier(backingField(originName)), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); + } + + /* + * create style arguments in builder lambda. + */ + static createStyleArgInBuilderLambda( + lambdaBody: arkts.Expression | undefined, + typeNode: arkts.TypeNode | undefined + ): arkts.UndefinedLiteral | arkts.ArrowFunctionExpression { + if (!lambdaBody) { + return arkts.factory.createUndefinedLiteral(); + } + + const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, typeNode), + undefined + ); + + const body: arkts.BlockStatement = arkts.factory.createBlock([ + arkts.factory.createExpressionStatement(lambdaBody), + arkts.factory.createReturnStatement(), + ]); + + const func = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [styleLambdaParam], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ); + + return arkts.factory.createArrowFunction(func); + } + + /* + * create style arguments in builder lambda declaration. + */ + static createStyleArgInBuilderLambdaDecl( + typeNode: arkts.TypeNode | undefined, + isFunctionCall: boolean + ): arkts.ETSParameterExpression { + const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, typeNode), + undefined + ); + const funcType = arkts.factory.createFunctionType( + arkts.FunctionSignature.createFunctionSignature( + undefined, + [styleLambdaParam], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + ); + + let parameter: arkts.ETSParameterExpression; + if (isFunctionCall) { + parameter = arkts.factory + .createParameterDeclaration( + arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_PARAM_NAME, funcType), + undefined + ) + .setOptional(true); + } else { + const optionalFuncType = arkts.factory.createUnionType([funcType, arkts.factory.createETSUndefinedType()]); + parameter = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_PARAM_NAME, optionalFuncType), + undefined + ); + } + parameter.annotations = [annotation('memo')]; + return parameter; + } +} diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts new file mode 100644 index 000000000..b31f6e284 --- /dev/null +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -0,0 +1,309 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { isAnnotation } from '../../common/arkts-utils'; +import { BuilderLambdaNames } from '../utils'; + +export type BuilderLambdaDeclInfo = { + isFunctionCall: boolean; // isFunctionCall means it is from $_instantiate. + params: readonly arkts.Expression[]; +}; + +export type BuilderLambdaAstNode = arkts.ScriptFunction | arkts.ETSParameterExpression | arkts.FunctionDeclaration; + +/** + * Used in finding "XXX" in BuilderLambda("XXX") + * @deprecated + */ +export function builderLambdaArgumentName(annotation: arkts.AnnotationUsage): string | undefined { + if (!isBuilderLambdaAnnotation(annotation)) { + return undefined; + } + + const property = annotation.properties.at(0); + if (!property || !arkts.isClassProperty(property)) { + return undefined; + } + if (!property.value || !arkts.isStringLiteral(property.value)) { + return undefined; + } + + return property.value.str; +} + +/** + * Determine whether it is a custom component. + * + * @param node class declaration node + */ +export function isBuilderLambda(node: arkts.AstNode, isExternal?: boolean): boolean { + const builderLambdaCall: arkts.AstNode | undefined = getDeclForBuilderLambda(node); + return !!builderLambdaCall; +} + +/** + * replace $_instantiate with _instantiateImpl. + * + * @param name origin name + */ +export function replaceBuilderLambdaDeclMethodName(name: string | undefined): string | undefined { + if (!!name && name === BuilderLambdaNames.ORIGIN_METHOD_NAME) { + return BuilderLambdaNames.TRANSFORM_METHOD_NAME; + } + return undefined; +} + +export function isBuilderLambdaMethodDecl(node: arkts.AstNode, isExternal?: boolean): boolean { + const builderLambdaMethodDecl: arkts.AstNode | undefined = getDeclForBuilderLambdaMethodDecl(node); + return !!builderLambdaMethodDecl; +} + +export function getDeclForBuilderLambdaMethodDecl( + node: arkts.AstNode, + isExternal?: boolean +): arkts.AstNode | undefined { + if (!node || !arkts.isMethodDefinition(node)) { + return undefined; + } + + const isBuilderLambda: boolean = !!node.name && isBuilderLambdaCall(node.name); + const isMethodDecl: boolean = + !!node.scriptFunction && + arkts.hasModifierFlag(node.scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE); + if (isBuilderLambda && isMethodDecl) { + return node; + } + return undefined; +} + +export function getDeclForBuilderLambda(node: arkts.AstNode, isExternal?: boolean): arkts.AstNode | undefined { + if (!node || !arkts.isCallExpression(node)) { + return undefined; + } + + let currNode: arkts.AstNode = node; + while ( + !!currNode && + arkts.isCallExpression(currNode) && + !!currNode.expression && + arkts.isMemberExpression(currNode.expression) + ) { + const _node: arkts.MemberExpression = currNode.expression; + + if (!!_node.property && arkts.isIdentifier(_node.property) && isBuilderLambdaCall(_node.property)) { + return node; + } + + if (!!_node.object && arkts.isCallExpression(_node.object) && isBuilderLambdaCall(_node.object)) { + return node; + } + + currNode = _node.object; + } + + if (isBuilderLambdaCall(node)) { + return node; + } + return undefined; +} + +export function isBuilderLambdaCall(node: arkts.CallExpression | arkts.Identifier): boolean { + const expr = arkts.isIdentifier(node) ? node : node.expression; + const decl = arkts.getDecl(expr); + + if (!decl) { + return false; + } + + if (arkts.isMethodDefinition(decl)) { + return isBuilderLambdaMethod(decl); + } + if (arkts.isFunctionExpression(decl)) { + return hasBuilderLambdaAnnotation(decl.scriptFunction); + } + return false; +} + +export function isBuilderLambdaMethod(node: arkts.MethodDefinition): boolean { + if (!node || !arkts.isMethodDefinition(node)) { + return false; + } + + const result = hasBuilderLambdaAnnotation(node.scriptFunction); + if (result) { + return true; + } + if (node.overloads.length > 0) { + return node.overloads.some(isBuilderLambdaMethod); + } + return false; +} + +export function hasBuilderLambdaAnnotation(node: BuilderLambdaAstNode): boolean { + return node.annotations.some(isBuilderLambdaAnnotation); +} + +export function isBuilderLambdaAnnotation(node: arkts.AnnotationUsage): boolean { + return isAnnotation(node, BuilderLambdaNames.ANNOTATION_NAME); +} + +export function findBuilderLambdaAnnotation( + node: arkts.ScriptFunction | arkts.ETSParameterExpression +): arkts.AnnotationUsage | undefined { + return node.annotations.find(isBuilderLambdaAnnotation); +} + +export function findBuilderLambdaInMethod(node: arkts.MethodDefinition): arkts.AnnotationUsage | undefined { + if (!node || !arkts.isMethodDefinition(node)) { + return undefined; + } + const result = findBuilderLambdaAnnotation(node.scriptFunction); + if (!!result) { + return result; + } + node.overloads.forEach((overload) => { + const anno: arkts.AnnotationUsage | undefined = findBuilderLambdaInMethod(overload); + if (!!anno) { + return anno; + } + }); + return undefined; +} + +export function findBuilderLambdaInCall( + node: arkts.CallExpression | arkts.Identifier +): arkts.AnnotationUsage | undefined { + const decl = findBuilderLambdaDecl(node); + if (!decl) { + return undefined; + } + + if (arkts.isMethodDefinition(decl)) { + return findBuilderLambdaInMethod(decl); + } + if (arkts.isFunctionExpression(decl)) { + return findBuilderLambdaAnnotation(decl.scriptFunction); + } + return undefined; +} + +export function findBuilderLambdaDecl(node: arkts.CallExpression | arkts.Identifier): arkts.AstNode | undefined { + const expr = arkts.isIdentifier(node) ? node : node.expression; + const decl = arkts.getDecl(expr); + if (!decl) { + return undefined; + } + return decl; +} + +/** + * check whether `` is the passing parameter. + * + * @param name origin name + */ +export function isParameterPassing(prop: arkts.Property): boolean | undefined { + return ( + prop.key && + prop.value && + arkts.isIdentifier(prop.key) && + arkts.isMemberExpression(prop.value) && + arkts.isThisExpression(prop.value.object) && + arkts.isIdentifier(prop.value.property) + ); +} + +export function findBuilderLambdaDeclInfo(node: arkts.CallExpression): BuilderLambdaDeclInfo | undefined { + const decl = findBuilderLambdaDecl(node); + if (!decl) { + return undefined; + } + if (arkts.isMethodDefinition(decl)) { + const params = decl.scriptFunction.params.map((p) => p.clone()); + const isFunctionCall = isBuilderLambdaFunctionCall(decl); + return { isFunctionCall, params }; + } + + return undefined; +} + +export function isBuilderLambdaFunctionCall(decl: arkts.AstNode | undefined): boolean { + if (!decl) { + return false; + } + if (arkts.isMethodDefinition(decl)) { + return ( + decl.name.name !== BuilderLambdaNames.ORIGIN_METHOD_NAME && + decl.name.name !== BuilderLambdaNames.TRANSFORM_METHOD_NAME + ); + } + return false; +} + +export function callIsGoodForBuilderLambda(leaf: arkts.CallExpression): boolean { + const node = leaf.expression; + return arkts.isIdentifier(node) || arkts.isMemberExpression(node); +} + +export function builderLambdaType(leaf: arkts.CallExpression): arkts.TypeNode | undefined { + const name: string | undefined = builderLambdaTypeName(leaf); + if (!name) { + return undefined; + } + // TODO: it should be the return type of the function annotated with the @BuilderLambda + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(`${name}Attribute`)) + ); +} + +export function builderLambdaMethodDeclType(method: arkts.MethodDefinition): arkts.TypeNode | undefined { + if (!method || !method.scriptFunction) { + return undefined; + } + return method.scriptFunction.returnTypeAnnotation; +} + +export function builderLambdaTypeName(leaf: arkts.CallExpression): string | undefined { + if (!callIsGoodForBuilderLambda(leaf)) { + return undefined; + } + const node = leaf.expression; + let name: string | undefined; + if (arkts.isIdentifier(node)) { + name = node.name; + } + if (arkts.isMemberExpression(node) && arkts.isIdentifier(node.object)) { + name = node.object.name; + } + return name; +} + +export function builderLambdaFunctionName(node: arkts.CallExpression): string | undefined { + const annotation = findBuilderLambdaInCall(node); + if (!annotation) { + return undefined; + } + if (arkts.isIdentifier(node.expression)) { + return node.expression.name; + } + if ( + arkts.isMemberExpression(node.expression) && + arkts.isIdentifier(node.expression.property) && + node.expression.property.name === BuilderLambdaNames.ORIGIN_METHOD_NAME + ) { + return BuilderLambdaNames.TRANSFORM_METHOD_NAME; + } + return undefined; +} diff --git a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts similarity index 34% rename from arkui-plugins/ui-plugins/builder-lambda-transformer.ts rename to arkui-plugins/ui-plugins/checked-transformer.ts index 49207f00f..c2946d51a 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -13,291 +13,303 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { AbstractVisitor } from "../common/abstract-visitor"; +import * as arkts from '@koalaui/libarkts'; +import { ProjectConfig } from '../common/plugin-context'; +import { factory as structFactory } from './struct-translators/factory'; +import { factory as builderLambdaFactory } from './builder-lambda-translators/factory'; +import { factory as uiFactory } from './ui-factory'; +import { factory as entryFactory } from './entry-translators/factory'; +import { AbstractVisitor } from '../common/abstract-visitor'; +import { annotation, collect, filterDefined, removeAnnotationByName, backingField } from '../common/arkts-utils'; import { + CustomComponentNames, + getCustomComponentOptionsName, + getTypeNameFromTypeParameter, + getTypeParamsFromClassDecl, BuilderLambdaNames, - findBuilderLambdaDecl, - findBuilderLambdaInCall, - isBuilderLambdaAnnotation, - isBuilderLambdaCall -} from "./utils"; +} from './utils'; +import { hasDecorator, DecoratorNames } from './property-translators/utils'; import { - annotation, - filterDefined, - removeAnnotationByName, - backingField -} from "../common/arkts-utils"; -import { DecoratorNames } from "./property-translators/utils"; - -function createStyleArgInBuilderLambda( - lambdaBody: arkts.Expression | undefined, - typeNode: arkts.TypeNode | undefined, -): arkts.UndefinedLiteral | arkts.ArrowFunctionExpression { - if (!lambdaBody) { - return arkts.factory.createUndefinedLiteral(); + ScopeInfo, + isCustomComponentClass, + isKnownMethodDefinition, + isEtsGlobalClass, + isReourceNode, +} from './struct-translators/utils'; +import { + isBuilderLambda, + isBuilderLambdaMethodDecl, + isBuilderLambdaFunctionCall, + builderLambdaMethodDeclType, + replaceBuilderLambdaDeclMethodName, + findBuilderLambdaDeclInfo, + callIsGoodForBuilderLambda, + builderLambdaFunctionName, + BuilderLambdaDeclInfo, + builderLambdaType, + builderLambdaTypeName, +} from './builder-lambda-translators/utils'; +import { isEntryWrapperClass } from './entry-translators/utils'; +import { classifyProperty, PropertyTranslator } from './property-translators'; + +export class CheckedTransformer extends AbstractVisitor { + private scopeInfos: ScopeInfo[] = []; + projectConfig: ProjectConfig | undefined; + + constructor(projectConfig: ProjectConfig | undefined) { + super(); + this.projectConfig = projectConfig; } - const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, - typeNode - ), - undefined - ); - - const body: arkts.BlockStatement = arkts.factory.createBlock([ - arkts.factory.createExpressionStatement(lambdaBody), - arkts.factory.createReturnStatement() - ]); + reset(): void { + super.reset(); + this.scopeInfos = []; + } - const func = arkts.factory.createScriptFunction( - body, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [styleLambdaParam], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ) + enter(node: arkts.AstNode): void { + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + this.scopeInfos.push({ name: node.definition!.ident!.name }); + } + if (arkts.isMethodDefinition(node) && this.scopeInfos.length > 0) { + const name = node.name.name; + const scopeInfo = this.scopeInfos.pop()!; + scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; + scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; + scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; + this.scopeInfos.push(scopeInfo); + } + } - return arkts.factory.createArrowFunction(func); -} + exit(node: arkts.AstNode): void { + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + this.scopeInfos.pop(); + } + } -function createStyleArgInBuilderLambdaDecl( - typeNode: arkts.TypeNode | undefined, - isFunctionCall: boolean -): arkts.ETSParameterExpression { - const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, - typeNode - ), - undefined - ); - const funcType = arkts.factory.createFunctionType( - arkts.FunctionSignature.createFunctionSignature( - undefined, - [styleLambdaParam], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW - ) + visitEachChild(node: arkts.AstNode): arkts.AstNode { + if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + return node; + } + if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + return node; + } - let parameter: arkts.ETSParameterExpression; - if (isFunctionCall) { - parameter = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - BuilderLambdaNames.STYLE_PARAM_NAME, - funcType - ), - undefined - ).setOptional(true); - } else { - const optionalFuncType = arkts.factory.createUnionType([ - funcType, - arkts.factory.createETSUndefinedType() - ]); - parameter = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - BuilderLambdaNames.STYLE_PARAM_NAME, - optionalFuncType - ), - undefined - ); + return super.visitEachChild(node); } - parameter.annotations = [annotation("memo")]; - return parameter; -} - -function updateFactoryArgInBuilderLambda( - arg: arkts.Expression | undefined, - typeNode: arkts.TypeNode | undefined -): arkts.ArrowFunctionExpression | undefined { - if (!arg || !arkts.isArrowFunctionExpression(arg)) { - throw new Error("first argument in $_instantiate is undefined"); - }; - const func: arkts.ScriptFunction = arg.scriptFunction; - const updateFunc = arkts.factory.updateScriptFunction( - func, - func.body, - arkts.FunctionSignature.createFunctionSignature( - func.typeParams, - func.params, - typeNode, - false - ), - func.flags, - func.modifiers - ) - return arkts.factory.updateArrowFunction( - arg, - updateFunc - ); + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + this.enter(beforeChildren); + const node = this.visitEachChild(beforeChildren); + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + let scope: ScopeInfo | undefined; + if (this.scopeInfos.length > 0) { + scope = this.scopeInfos[this.scopeInfos.length - 1]; + } + const newClass: arkts.ClassDeclaration = tranformClassMembers( + node, + arkts.hasModifierFlag(node, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE), + scope + ); + this.exit(beforeChildren); + return newClass; + } else if (isEntryWrapperClass(node)) { + entryFactory.addMemoToEntryWrapperClassMethods(node); + return node; + } else if (arkts.isClassDeclaration(node) && isEtsGlobalClass(node)) { + return transformEtsGlobalClassMembers(node); + } else if (arkts.isCallExpression(node) && isReourceNode(node)) { + return transformResource(node, this.projectConfig); + } else if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + const lambda = transformBuilderLambda(node, this.isExternal); + return lambda; + } else if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + const lambda = transformBuilderLambdaMethodDecl(node); + return lambda; + } + return node; + } } -// TODO: very time-consuming... -function updateIfElseContentBodyInBuilderLambda( - statement: arkts.AstNode, - isExternal?: boolean -): arkts.AstNode { - if (arkts.isIfStatement(statement)) { - const alternate = !!statement.alternate - ? updateIfElseContentBodyInBuilderLambda(statement.alternate, isExternal) - : statement.alternate; - const consequence = updateIfElseContentBodyInBuilderLambda(statement.consequent, isExternal); - return arkts.factory.updateIfStatement( - statement, - statement.test, - consequence!, - alternate - ) - } - if (arkts.isBlockStatement(statement)) { - return arkts.factory.updateBlock( - statement, - statement.statements.map( - (st) => updateContentBodyInBuilderLambda(st, isExternal) - ) - ) +function tranformClassMembers( + node: arkts.ClassDeclaration, + isDecl?: boolean, + scope?: ScopeInfo +): arkts.ClassDeclaration { + if (!node.definition) { + return node; } - return statement; -} -function updateContentBodyInBuilderLambda( - statement: arkts.Statement, - isExternal?: boolean -): arkts.Statement { - if ( - arkts.isExpressionStatement(statement) - && arkts.isCallExpression(statement.expression) - && isBuilderLambda(statement.expression, isExternal) - ) { - return arkts.factory.updateExpressionStatement( - statement, - transformBuilderLambda(statement.expression) - ); + let classTypeName: string | undefined; + let classOptionsName: string | undefined; + if (isDecl) { + const [classType, classOptions] = getTypeParamsFromClassDecl(node); + classTypeName = getTypeNameFromTypeParameter(classType); + classOptionsName = getTypeNameFromTypeParameter(classOptions); } - // TODO: very time-consuming... - if (arkts.isIfStatement(statement)) { - return updateIfElseContentBodyInBuilderLambda(statement, isExternal); + const definition: arkts.ClassDefinition = node.definition; + const className: string | undefined = node.definition.ident?.name; + if (!className) { + throw new Error('Non Empty className expected for Component'); } - return statement; -} - -/** - * Used in finding "XXX" in BuilderLambda("XXX") - * @deprecated - */ -function builderLambdaArgumentName(annotation: arkts.AnnotationUsage): string | undefined { - if (!isBuilderLambdaAnnotation(annotation)) return undefined; - - const property = annotation.properties.at(0); - if (!property || !arkts.isClassProperty(property)) return undefined; - if (!property.value || !arkts.isStringLiteral(property.value)) return undefined; + const propertyTranslators: PropertyTranslator[] = filterDefined( + definition.body.map((it) => classifyProperty(it, className)) + ); + const translatedMembers: arkts.AstNode[] = tranformPropertyMembers( + className, + propertyTranslators, + classOptionsName ?? getCustomComponentOptionsName(className), + isDecl, + scope + ); + const updateMembers: arkts.AstNode[] = definition.body + .filter((member) => !arkts.isClassProperty(member)) + .map((member: arkts.AstNode) => + transformOtherMembersInClass(member, classTypeName, classOptionsName, className, isDecl) + ); - return property.value.str; + const updateClassDef: arkts.ClassDefinition = structFactory.updateCustomComponentClass(definition, [ + ...translatedMembers, + ...updateMembers, + ]); + return arkts.factory.updateClassDeclaration(node, updateClassDef); } -function builderLambdaFunctionName(node: arkts.CallExpression): string | undefined { - const annotation = findBuilderLambdaInCall(node); - if (!annotation) return undefined; - - if (arkts.isIdentifier(node.expression)) { - return node.expression.name; +function transformOtherMembersInClass( + member: arkts.AstNode, + classTypeName: string | undefined, + classOptionsName: string | undefined, + className: string, + isDecl?: boolean +): arkts.AstNode { + if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { + member.scriptFunction.setAnnotations([annotation('memo')]); + return member; } if ( - arkts.isMemberExpression(node.expression) - && arkts.isIdentifier(node.expression.property) - && node.expression.property.name === BuilderLambdaNames.ORIGIN_METHOD_NAME + arkts.isMethodDefinition(member) && + isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI) && + !isDecl ) { - return BuilderLambdaNames.TRANSFORM_METHOD_NAME + return uiFactory.createConstructorMethod(member); } - return undefined; -} - -function replaceBuilderLambdaDeclMethodName(name: string | undefined): string | undefined { - if (!!name && name === BuilderLambdaNames.ORIGIN_METHOD_NAME) { - return BuilderLambdaNames.TRANSFORM_METHOD_NAME + if (arkts.isMethodDefinition(member) && isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI)) { + return structFactory.transformBuildMethodWithOriginBuild( + member, + classTypeName ?? className, + classOptionsName ?? getCustomComponentOptionsName(className), + isDecl + ); } - return undefined; + return member; } -function callIsGoodForBuilderLambda(leaf: arkts.CallExpression): boolean { - const node = leaf.expression; - return arkts.isIdentifier(node) || arkts.isMemberExpression(node); -} - -function builderLambdaTypeName(leaf: arkts.CallExpression): string | undefined{ - if (!callIsGoodForBuilderLambda(leaf)) return undefined; - const node = leaf.expression; - let name: string | undefined; - if (arkts.isIdentifier(node)) { - name = node.name; +function tranformPropertyMembers( + className: string, + propertyTranslators: PropertyTranslator[], + optionsTypeName: string, + isDecl?: boolean, + scope?: ScopeInfo +): arkts.AstNode[] { + const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); + const collections = []; + if (!scope?.hasInitializeStruct) { + collections.push(structFactory.createInitializeStruct(currentStructInfo, optionsTypeName, isDecl)); } - if (arkts.isMemberExpression(node) && arkts.isIdentifier(node.object)) { - name = node.object.name; + if (!scope?.hasUpdateStruct) { + collections.push(structFactory.createUpdateStruct(currentStructInfo, optionsTypeName, isDecl)); } - return name; + if ( currentStructInfo.isReusable ) { + collections.push(structFactory.toRecord(optionsTypeName, currentStructInfo.toRecordBody)); + } + return collect(...collections, ...propertyMembers); } -function builderLambdaType( - leaf: arkts.CallExpression, -): arkts.TypeNode | undefined { - const name: string | undefined = builderLambdaTypeName(leaf); - if(!name) return undefined; - - // TODO: it should be the return type of the function annotated with the @BuilderLambda - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(`${name}Attribute`) - ) +function transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { + const func: arkts.ScriptFunction = node.scriptFunction; + const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); + const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); + const styleArg: arkts.ETSParameterExpression = builderLambdaFactory.createStyleArgInBuilderLambdaDecl( + typeNode, + isFunctionCall + ); + return builderLambdaFactory.updateBuilderLambdaMethodDecl( + node, + styleArg, + removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), + replaceBuilderLambdaDeclMethodName(node.name.name) ); } -function builderLambdaMethodDeclType(method: arkts.MethodDefinition): arkts.TypeNode | undefined { - if (!method || !method.scriptFunction) return undefined; - return method.scriptFunction.returnTypeAnnotation; +function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.ClassDeclaration { + if (!node.definition) { + return node; + } + node.definition.body.map((member: arkts.AstNode) => { + if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { + member.scriptFunction.setAnnotations([annotation('memo')]); + } + return member; + }); + return node; } -function isBuilderLambdaFunctionCall(decl: arkts.AstNode | undefined): boolean { - if (!decl) return false; - if (arkts.isMethodDefinition(decl)) { - return ( - decl.name.name != BuilderLambdaNames.ORIGIN_METHOD_NAME - && decl.name.name != BuilderLambdaNames.TRANSFORM_METHOD_NAME - ); - } - return false; +function transformResource( + resourceNode: arkts.CallExpression, + projectConfig: ProjectConfig | undefined +): arkts.CallExpression { + const newArgs: arkts.AstNode[] = [ + arkts.factory.create1StringLiteral(projectConfig?.bundleName ? projectConfig.bundleName : ''), + arkts.factory.create1StringLiteral(projectConfig?.moduleName ? projectConfig.moduleName : ''), + ...resourceNode.arguments, + ]; + return structFactory.generateTransformedResource(resourceNode, newArgs); } -function findBuilderLambdaDeclInfo( - node: arkts.CallExpression -): BuilderLambdaDeclInfo | undefined { - const decl = findBuilderLambdaDecl(node); - if (!decl) return undefined; +function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { + let instanceCalls: arkts.CallExpression[] = []; + let leaf: arkts.CallExpression = node; - if (arkts.isMethodDefinition(decl)) { - const params = decl.scriptFunction.params.map((p) => p.clone()); - const isFunctionCall = isBuilderLambdaFunctionCall(decl); - return { isFunctionCall, params }; + while ( + true && + arkts.isMemberExpression(leaf.expression) && + arkts.isIdentifier(leaf.expression.property) && + arkts.isCallExpression(leaf.expression.object) + ) { + instanceCalls.push(arkts.factory.createCallExpression(leaf.expression.property, undefined, leaf.arguments)); + leaf = leaf.expression.object; } - return undefined; + const replace: arkts.Identifier | arkts.MemberExpression | undefined = builderLambdaReplace(leaf); + const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(leaf); + if (!replace || !declInfo) { + return node; + } + let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; + if (instanceCalls.length > 0) { + instanceCalls = instanceCalls.reverse(); + lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); + instanceCalls.forEach((call) => { + if (!arkts.isIdentifier(call.expression)) { + throw new Error('call expression should be identifier'); + } + lambdaBody = builderLambdaFactory.createStyleLambdaBody(lambdaBody!, call); + }); + } + const args: (arkts.AstNode | undefined)[] = generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, isExternal); + return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); } function builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { - if (!callIsGoodForBuilderLambda(leaf)) return undefined; - const node = leaf.expression; - + if (!callIsGoodForBuilderLambda(leaf)) { + return undefined; + } + const node = leaf.expression; const funcName = builderLambdaFunctionName(leaf); - if (!funcName) return undefined; - + if (!funcName) { + return undefined; + } if (arkts.isIdentifier(node)) { return arkts.factory.createIdentifier(funcName); } @@ -308,11 +320,39 @@ function builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | ar arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, node.computed, node.optional - ) + ); } return undefined; } +function generateArgsInBuilderLambda( + leaf: arkts.CallExpression, + lambdaBody: arkts.Identifier | arkts.CallExpression, + declInfo: BuilderLambdaDeclInfo, + isExternal?: boolean +): (arkts.AstNode | undefined)[] { + const { params } = declInfo; + const typeNode: arkts.TypeNode | undefined = builderLambdaType(leaf); + const typeName: string | undefined = builderLambdaTypeName(leaf); + const args: (arkts.AstNode | undefined)[] = [ + builderLambdaFactory.createStyleArgInBuilderLambda(lambdaBody, typeNode), + ]; + let index = 0; + while (index < params.length) { + const isReusable: boolean = typeName + ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable + : false; + if (isReusable && index === params.length - 1) { + const reuseId = arkts.factory.createStringLiteral(typeName!); + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName, reuseId)); + } else { + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName)); + } + index++; + } + return args; +} + function createOrUpdateArgInBuilderLambda( arg: arkts.Expression | undefined, isExternal?: boolean, @@ -354,34 +394,11 @@ function processArgArrowFunction( function processArgTSAsExpression(arg: arkts.TSAsExpression, typeName: string): arkts.TSAsExpression { if (!arg.expr || !arkts.isObjectExpression(arg.expr)) { return arg; - } + } const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); const properties = arg.expr.properties as arkts.Property[]; properties.forEach((prop, index) => { - if ( - prop.key && - prop.value && - arkts.isIdentifier(prop.key) && - arkts.isMemberExpression(prop.value) && - arkts.isThisExpression(prop.value.object) && - arkts.isIdentifier(prop.value.property) - ) { - const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; - if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { - properties[index] = arkts.Property.updateProperty( - prop, - arkts.factory.createIdentifier(backingField(prop.key.name)), - arkts.factory.updateMemberExpression( - prop.value, - prop.value.object, - arkts.factory.createIdentifier(backingField(prop.value.property.name)), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ); - } - } + updateParameterPassing(prop, index, currentStructInfo, properties); }); const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( arg.expr, @@ -392,208 +409,61 @@ function processArgTSAsExpression(arg: arkts.TSAsExpression, typeName: string): return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); } -function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { - let instanceCalls: arkts.CallExpression[] = []; - let leaf: arkts.CallExpression = node; - - while (true - && arkts.isMemberExpression(leaf.expression) - && arkts.isIdentifier(leaf.expression.property) - && arkts.isCallExpression(leaf.expression.object) +function updateContentBodyInBuilderLambda(statement: arkts.Statement, isExternal?: boolean): arkts.Statement { + if ( + arkts.isExpressionStatement(statement) && + arkts.isCallExpression(statement.expression) && + isBuilderLambda(statement.expression, isExternal) ) { - instanceCalls.push( - arkts.factory.createCallExpression( - leaf.expression.property, - undefined, - leaf.arguments - ) - ); - leaf = leaf.expression.object; - } - - const replace: arkts.Identifier | arkts.MemberExpression | undefined - = builderLambdaReplace(leaf); - const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(leaf); - if (!replace || !declInfo) return node; - - const { params } = declInfo; - - let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; - if (instanceCalls.length > 0) { - instanceCalls = instanceCalls.reverse(); - lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); - instanceCalls.forEach((call)=> { - if (!arkts.isIdentifier(call.expression)) { - throw new Error('call expression should be identifier'); - } - lambdaBody = arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - lambdaBody!, - call.expression, - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - call.arguments - ); - }); + return arkts.factory.updateExpressionStatement(statement, transformBuilderLambda(statement.expression)); } - - - const typeNode: arkts.TypeNode | undefined = builderLambdaType(leaf); - const typeName: string | undefined = builderLambdaTypeName(leaf); - const args: (arkts.AstNode | undefined)[] = [ - createStyleArgInBuilderLambda(lambdaBody, typeNode) - ] - let index = 0; - while (index < params.length) { - const isReusable: boolean = typeName - ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable - : false; - if (isReusable && index == params.length - 1) { - const reuseId = arkts.factory.createStringLiteral(typeName!); - args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName, reuseId)); - } else { - args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName)); - } - index++; + // TODO: very time-consuming... + if (arkts.isIfStatement(statement)) { + return updateIfElseContentBodyInBuilderLambda(statement, isExternal); } - return arkts.factory.updateCallExpression( - node, - replace, - undefined, - filterDefined(args) - ); -} - -function transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { - const func: arkts.ScriptFunction = node.scriptFunction; - const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); - const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); - const updateFunc = arkts.factory.updateScriptFunction( - func, - func.body, - arkts.FunctionSignature.createFunctionSignature( - func.typeParams, - [ - createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall), - ...func.params - ], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - func.flags, - func.modifiers - ).setAnnotations( - removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME) - ); - - return arkts.factory.updateMethodDefinition( - node, - node.kind, - arkts.factory.updateIdentifier( - node.name, - replaceBuilderLambdaDeclMethodName(node.name.name) ?? node.name.name - ), - arkts.factory.createFunctionExpression(updateFunc), - node.modifiers, - false // TODO: how do I get it? - ); -} - -function isBuilderLambda(node: arkts.AstNode, isExternal?: boolean): boolean { - const builderLambdaCall: arkts.AstNode | undefined = getDeclForBuilderLambda(node); - return !!builderLambdaCall; -} - -function isBuilderLambdaMethodDecl(node: arkts.AstNode, isExternal?: boolean): boolean { - const builderLambdaMethodDecl: arkts.AstNode | undefined = getDeclForBuilderLambdaMethodDecl(node); - return !!builderLambdaMethodDecl; + return statement; } -function getDeclForBuilderLambdaMethodDecl(node: arkts.AstNode, isExternal?: boolean): arkts.AstNode | undefined { - if (!node || !arkts.isMethodDefinition(node)) return undefined; - - const isBuilderLambda: boolean = !!node.name && isBuilderLambdaCall(node.name); - const isMethodDecl: boolean = !!node.scriptFunction - && arkts.hasModifierFlag(node.scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE); +function updateParameterPassing( + prop: arkts.Property, + index: number, + currentStructInfo: arkts.StructInfo, + properties: arkts.Property[] +): void { if ( - isBuilderLambda - && isMethodDecl + prop.key && + prop.value && + arkts.isIdentifier(prop.key) && + arkts.isMemberExpression(prop.value) && + arkts.isThisExpression(prop.value.object) && + arkts.isIdentifier(prop.value.property) ) { - return node; - } - return undefined; -} - -function getDeclForBuilderLambda(node: arkts.AstNode, isExternal?: boolean): arkts.AstNode | undefined { - if (!node || !arkts.isCallExpression(node)) return undefined; - - let currNode: arkts.AstNode = node; - while ( - !!currNode - && arkts.isCallExpression(currNode) - && !!currNode.expression - && arkts.isMemberExpression(currNode.expression) - ) { - const _node: arkts.MemberExpression = currNode.expression; - - if ( - !!_node.property - && arkts.isIdentifier(_node.property) - && isBuilderLambdaCall(_node.property) - ) { - return node; - } - - if ( - !!_node.object - && arkts.isCallExpression(_node.object) - && isBuilderLambdaCall(_node.object) - ) { - return node; + const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; + if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { + properties[index] = arkts.Property.updateProperty( + prop, + arkts.factory.createIdentifier(backingField(prop.key.name)), + builderLambdaFactory.updateBackingMember(prop.value, prop.value.property.name) + ); } - - currNode = _node.object; - } - - if (isBuilderLambdaCall(node)) { - return node; } - return undefined; -} - -type BuilderLambdaDeclInfo = { - isFunctionCall: boolean, // isFunctionCall means it is from $_instantiate. - params: readonly arkts.Expression[] } -export class BuilderLambdaTransformer extends AbstractVisitor { - visitEachChild(node: arkts.AstNode): arkts.AstNode { - if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { - return node; - } - if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { - return node; - } - - return super.visitEachChild(node); +// TODO: very time-consuming... +function updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, isExternal?: boolean): arkts.AstNode { + if (arkts.isIfStatement(statement)) { + const alternate = !!statement.alternate + ? updateIfElseContentBodyInBuilderLambda(statement.alternate, isExternal) + : statement.alternate; + const consequence = updateIfElseContentBodyInBuilderLambda(statement.consequent, isExternal); + return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); } - - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - const node = this.visitEachChild(beforeChildren) - - if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { - const lambda = transformBuilderLambda(node, this.isExternal); - return lambda; - } - if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { - const lambda = transformBuilderLambdaMethodDecl(node); - return lambda; - } - - return node; + if (arkts.isBlockStatement(statement)) { + return arkts.factory.updateBlock( + statement, + statement.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) + ); } + return statement; } diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index dd4992100..d1f0e33d4 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -13,25 +13,25 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { getInteropPath } from "../../path" -const interop = require(getInteropPath()) -const nullptr = interop.nullptr -import { EntryWrapperNames } from "./utils"; -import { annotation } from "../../common/arkts-utils"; -import { factory as uiFactory } from "../ui-factory"; +import * as arkts from '@koalaui/libarkts'; +import { getInteropPath } from '../../path'; +const interop = require(getInteropPath()); +const nullptr = interop.nullptr; +import { EntryWrapperNames } from './utils'; +import { annotation } from '../../common/arkts-utils'; +import { factory as uiFactory } from '../ui-factory'; export class factory { /** * insert an 'entry' method to an entry wrapper class. - * + * * @param node entry wrapper class declaration node. */ static registerEntryFunction(node: arkts.ClassDeclaration): arkts.AstNode { const definition: arkts.ClassDefinition | undefined = node.definition; - const classname = node?.definition?.ident?.name + const classname = node?.definition?.ident?.name; if (!definition || !classname) { - throw new Error("Node definition is undefined"); + throw new Error('Node definition is undefined'); } const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( definition, @@ -50,15 +50,15 @@ export class factory { /** * insert an 'entry' property to an entry wrapper class. - * + * * @param node entry wrapper class declaration node. * @deprecated */ static registerEntryProperty(node: arkts.ClassDeclaration): arkts.AstNode { const definition: arkts.ClassDefinition | undefined = node.definition; - const classname = node?.definition?.ident?.name + const classname = node?.definition?.ident?.name; if (!definition || !classname) { - throw new Error("Node definition is undefined"); + throw new Error('Node definition is undefined'); } const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( definition, @@ -78,7 +78,7 @@ export class factory { /** * create `entry(): void { (); }` class method for the entry wrapper class, * which calls the struct within the method. - * + * * @param name class/struct name that has `@Entry` annotation. */ static generateEntryFunction(name: string): arkts.MethodDefinition { @@ -86,22 +86,24 @@ export class factory { arkts.factory.createCallExpression( arkts.factory.createIdentifier(name), undefined, - [arkts.factory.createUndefinedLiteral()], // TODO: Add this undefined later + [arkts.factory.createUndefinedLiteral()] // TODO: Add this undefined later ) ); const key: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_FUNC); const block = arkts.factory.createBlock([exp]); - const entryScript = arkts.factory.createScriptFunction( - block, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ).setIdent(key); + const entryScript = arkts.factory + .createScriptFunction( + block, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ) + .setIdent(key); const def = arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, @@ -117,7 +119,7 @@ export class factory { /** * create `entry = (): void => { (); }` class property for the entry wrapper class, * which calls the struct within the arrow function. - * + * * @param name class/struct name that has `@Entry` annotation. * @deprecated */ @@ -126,7 +128,7 @@ export class factory { arkts.factory.createCallExpression( arkts.factory.createIdentifier(name), undefined, - [arkts.factory.createUndefinedLiteral()], // TODO: Add this undefined later + [arkts.factory.createUndefinedLiteral()] // TODO: Add this undefined later ) ); const key: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_FUNC); @@ -137,20 +139,19 @@ export class factory { arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), false ); - const entryScript: arkts.ScriptFunction = arkts.factory.createScriptFunction( - block, - signature, - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ).setIdent(key); + const entryScript: arkts.ScriptFunction = arkts.factory + .createScriptFunction( + block, + signature, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ) + .setIdent(key); const def = arkts.factory.createClassProperty( key, arkts.factory.createArrowFunction(entryScript), - arkts.factory.createFunctionType( - signature, - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW - ), + arkts.factory.createFunctionType(signature, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -161,7 +162,7 @@ export class factory { /** * create `__EntryWrapper_Entry` entry wrapper class that contains an 'entry' method that * calls the struct within the method. - * + * * @param name class/struct name that has `@Entry` annotation. */ static generateEntryWrapper(name: string): arkts.ClassDeclaration { @@ -177,11 +178,11 @@ export class factory { ) ), [factory.generateEntryFunction(name)], - arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_CLASS_DECL - | arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_DECLARATION - | arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_ID_REQUIRED, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ) + arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_CLASS_DECL | + arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_DECLARATION | + arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_ID_REQUIRED, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); const newClass = arkts.factory.createClassDeclaration(definition); newClass.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE; return newClass; @@ -189,54 +190,52 @@ export class factory { /** * add `@memo` to all class methods that are named 'entry'. - * + * * @param node class declaration node */ static addMemoToEntryWrapperClassMethods(node: arkts.ClassDeclaration): void { - node.definition?.body.forEach(member => { + node.definition?.body.forEach((member) => { if ( - arkts.isMethodDefinition(member) - && !!member.scriptFunction.id - && member.scriptFunction.id.name == EntryWrapperNames.ENTRY_FUNC + arkts.isMethodDefinition(member) && + !!member.scriptFunction.id && + member.scriptFunction.id.name === EntryWrapperNames.ENTRY_FUNC ) { - member.scriptFunction.setAnnotations([annotation("memo")]); + member.scriptFunction.setAnnotations([annotation('memo')]); } }); } /** * add `@memo` to the class property's value (expecting an arrow function), where the property is named 'entry'. - * + * * @param node class declaration node * @deprecated */ static addMemoToEntryWrapperPropertyValue(node: arkts.ClassDeclaration): void { - node.definition?.body.forEach(member => { + node.definition?.body.forEach((member) => { if ( - arkts.isClassProperty(member) - && !!member.value - && arkts.isArrowFunctionExpression(member.value) - && !!member.key - && arkts.isIdentifier(member.key) - && member.key.name == EntryWrapperNames.ENTRY_FUNC + arkts.isClassProperty(member) && + !!member.value && + arkts.isArrowFunctionExpression(member.value) && + !!member.key && + arkts.isIdentifier(member.key) && + member.key.name === EntryWrapperNames.ENTRY_FUNC ) { - member.setAnnotations([annotation("memo")]); + member.setAnnotations([annotation('memo')]); } }); } /** - * create `private _entry_local_storage_ = ;` class property + * create `private _entry_local_storage_ = ;` class property * from `{storage: ""}` in `@Entry`'s properties. - * + * * @param annotation `@Entry` annotation. */ static createEntryLocalStorageInClass(property: arkts.ClassProperty) { const value = property.value as arkts.StringLiteral; return arkts.factory.createClassProperty( - arkts.factory.createIdentifier( - EntryWrapperNames.ENTRY_STORAGE_LOCAL_STORAGE_PROPERTY_NAME - ), + arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_STORAGE_LOCAL_STORAGE_PROPERTY_NAME), arkts.factory.createIdentifier(value.str), undefined, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, @@ -249,15 +248,11 @@ export class factory { * to the top of script's statements. */ static createAndInsertEntryPointImport(program?: arkts.Program) { - const source: arkts.StringLiteral = arkts.factory.create1StringLiteral( - EntryWrapperNames.ENTRY_DEFAULT_IMPORT - ); - const imported: arkts.Identifier = arkts.factory.createIdentifier( - EntryWrapperNames.ENTRY_POINT_CLASS_NAME - ); + const source: arkts.StringLiteral = arkts.factory.create1StringLiteral(EntryWrapperNames.ENTRY_DEFAULT_IMPORT); + const imported: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME); // Insert this import at the top of the script's statements. if (!program) { - throw Error("Failed to insert import: Transformer has no program"); + throw Error('Failed to insert import: Transformer has no program'); } uiFactory.createAndInsertImportDeclaration( source, @@ -267,4 +262,4 @@ export class factory { program ); } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index 05dec1426..76e2e6883 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -13,102 +13,116 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { ComponentTransformer } from './component-transformer' -import { PreprocessorTransformer } from './preprocessor-transform' -import { BuilderLambdaTransformer } from './builder-lambda-transformer' -import { StructTransformer } from './struct-transformer' -import { Plugins, PluginContext } from "../common/plugin-context" -import { ProgramVisitor } from "../common/program-visitor" -import { EXTERNAL_SOURCE_PREFIX_NAMES } from "../common/predefines" -import { debugDump, debugLog, getDumpFileName } from "../common/debug" +import * as arkts from '@koalaui/libarkts'; +import { ComponentTransformer } from './component-transformer'; +import { PreprocessorTransformer } from './preprocessor-transform'; +import { CheckedTransformer } from './checked-transformer'; +import { Plugins, PluginContext } from '../common/plugin-context'; +import { ProgramVisitor } from '../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; +import { debugDump, debugLog, getDumpFileName } from '../common/debug'; export function uiTransform(): Plugins { return { name: 'ui-plugin', - parsed(this: PluginContext) { - console.log('[UI PLUGIN] AFTER PARSED ENTER'); - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - let script = program.astNode; - - const cachePath: string | undefined = this.getProjectConfig()?.cachePath; - debugLog('[BEFORE PARSED SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true, cachePath, program.programFileNameWithExtension); - - arkts.Performance.getInstance().createEvent("ui-parsed"); - - const componentTransformer = new ComponentTransformer(); - const preprocessorTransformer = new PreprocessorTransformer(); - const programVisitor = new ProgramVisitor({ - pluginName: uiTransform.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, - visitors: [componentTransformer, preprocessorTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - - program = programVisitor.programVisitor(program); - script = program.astNode; - - arkts.Performance.getInstance().stopEvent("ui-parsed", true); - - debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), true, cachePath, program.programFileNameWithExtension); - - this.setArkTSAst(script); - console.log('[UI PLUGIN] AFTER PARSED EXIT'); - return script; - } - console.log('[UI PLUGIN] AFTER PARSED EXIT WITH NO TRANSFORM'); - }, - checked(this: PluginContext) { - console.log('[UI PLUGIN] AFTER CHECKED ENTER'); - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - let script = program.astNode; - - const cachePath: string | undefined = this.getProjectConfig()?.cachePath; - debugLog('[BEFORE STRUCT SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true, cachePath, program.programFileNameWithExtension); - - arkts.Performance.getInstance().createEvent("ui-checked"); - - const builderLambdaTransformer = new BuilderLambdaTransformer(); - const structTransformer = new StructTransformer(this.getProjectConfig()); - const programVisitor = new ProgramVisitor({ - pluginName: uiTransform.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [structTransformer, builderLambdaTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - - program = programVisitor.programVisitor(program); - script = program.astNode; - - arkts.Performance.getInstance().stopEvent("ui-checked", true); - - debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true, cachePath, program.programFileNameWithExtension); - - arkts.GlobalInfo.getInfoInstance().reset(); - arkts.Performance.getInstance().createEvent("ui-recheck"); - arkts.recheckSubtree(script); - arkts.Performance.getInstance().stopEvent("ui-recheck", true); - - arkts.Performance.getInstance().clearAllEvents(); - - this.setArkTSAst(script); - console.log('[UI PLUGIN] AFTER CHECKED EXIT'); - return script; - } - console.log('[UI PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); - }, + parsed: parsedTransform, + checked: checkedTransform, clean() { arkts.arktsGlobal.clearContext(); - } + }, }; } + +function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + console.log('[UI PLUGIN] AFTER PARSED ENTER'); + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; + debugLog('[BEFORE PARSED SCRIPT] script: ', script.dumpSrc()); + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), + true, + cachePath, + program.programFileNameWithExtension + ); + arkts.Performance.getInstance().createEvent('ui-parsed'); + const componentTransformer = new ComponentTransformer(); + const preprocessorTransformer = new PreprocessorTransformer(); + const programVisitor = new ProgramVisitor({ + pluginName: uiTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + visitors: [componentTransformer, preprocessorTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); + script = program.astNode; + arkts.Performance.getInstance().stopEvent('ui-parsed', true); + debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), + true, + cachePath, + program.programFileNameWithExtension + ); + this.setArkTSAst(script); + console.log('[UI PLUGIN] AFTER PARSED EXIT'); + return script; + } + console.log('[UI PLUGIN] AFTER PARSED EXIT WITH NO TRANSFORM'); + return script; +} + +function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + console.log('[UI PLUGIN] AFTER CHECKED ENTER'); + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; + debugLog('[BEFORE STRUCT SCRIPT] script: ', script.dumpSrc()); + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), + true, + cachePath, + program.programFileNameWithExtension + ); + arkts.Performance.getInstance().createEvent('ui-checked'); + const checkedTransformer = new CheckedTransformer(this.getProjectConfig()); + const programVisitor = new ProgramVisitor({ + pluginName: uiTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [checkedTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); + script = program.astNode; + arkts.Performance.getInstance().stopEvent('ui-checked', true); + debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), + true, + cachePath, + program.programFileNameWithExtension + ); + arkts.GlobalInfo.getInfoInstance().reset(); + arkts.Performance.getInstance().createEvent('ui-recheck'); + arkts.recheckSubtree(script); + arkts.Performance.getInstance().stopEvent('ui-recheck', true); + arkts.Performance.getInstance().clearAllEvents(); + this.setArkTSAst(script); + console.log('[UI PLUGIN] AFTER CHECKED EXIT'); + return script; + } + console.log('[UI PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); + return script; +} diff --git a/arkui-plugins/ui-plugins/name-collector.ts b/arkui-plugins/ui-plugins/name-collector.ts index 0609f26b9..52611d21a 100644 --- a/arkui-plugins/ui-plugins/name-collector.ts +++ b/arkui-plugins/ui-plugins/name-collector.ts @@ -15,7 +15,7 @@ import * as arkts from "@koalaui/libarkts"; import { AbstractVisitor } from "../common/abstract-visitor"; -import { hasBuilderLambdaAnnotation } from "./utils"; +import { hasBuilderLambdaAnnotation } from "./builder-lambda-translators/utils"; interface ComponentInfo { argsNum: number; diff --git a/arkui-plugins/ui-plugins/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-transformer.ts deleted file mode 100644 index e9f6d73e7..000000000 --- a/arkui-plugins/ui-plugins/struct-transformer.ts +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from "@koalaui/libarkts" -import { AbstractVisitor } from "../common/abstract-visitor"; -import { - annotation, - collect, - filterDefined -} from "../common/arkts-utils"; -import { ProjectConfig } from "../common/plugin-context"; -import { - classifyProperty, - PropertyTranslator -} from "./property-translators"; -import { - CustomComponentNames, - getCustomComponentOptionsName, - getTypeNameFromTypeParameter, - getTypeParamsFromClassDecl, - Dollars -} from "./utils"; -import { - factory -} from "./ui-factory"; -import { - isEntryWrapperClass -} from "./entry-translators/utils"; -import { - factory as entryFactory -} from "./entry-translators/factory"; -import { DecoratorNames, hasDecorator } from "./property-translators/utils"; - -function isCustomComponentClass(node: arkts.ClassDeclaration): boolean { - if (!node.definition?.ident?.name) return false; - const name: string = node.definition.ident.name; - const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); - return ( - name === CustomComponentNames.COMPONENT_CLASS_NAME - || structCollection.has(name) - ); -} - -function isKnownMethodDefinition(method: arkts.MethodDefinition, name: string): boolean { - if (!method || !arkts.isMethodDefinition(method)) return false; - - // For now, we only considered matched method name. - const isNameMatched: boolean = method.name?.name === name; - return isNameMatched; -} - -function isEtsGlobalClass(node: arkts.ClassDeclaration): boolean { - if (node.definition?.ident?.name === 'ETSGLOBAL') { - return true; - } - return false; -} - -function isReourceNode(node: arkts.CallExpression): boolean { - if (node.expression.dumpSrc() === Dollars.DOLLAR_RESOURCE || - node.expression.dumpSrc() === Dollars.DOLLAR_RAWFILE) { - return true; - } - return false; -} - -function transformBuildMethod( - method: arkts.MethodDefinition, - typeName: string, - optionsName: string, - isDecl?: boolean -): arkts.MethodDefinition { - const updateKey: arkts.Identifier = arkts.factory.createIdentifier( - CustomComponentNames.COMPONENT_BUILD - ); - - const scriptFunction: arkts.ScriptFunction = method.scriptFunction; - const updateScriptFunction = arkts.factory.createScriptFunction( - scriptFunction.body, - arkts.FunctionSignature.createFunctionSignature( - scriptFunction.typeParams, - [ - factory.createStyleParameter(typeName), - factory.createContentParameter(), - factory.createInitializersOptionsParameter(optionsName) - ], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - scriptFunction.flags, - scriptFunction.modifiers - ).setAnnotations([annotation("memo")]); - - const modifiers: arkts.Es2pandaModifierFlags = isDecl - ? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT - : arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - updateKey, - arkts.factory.createFunctionExpression(updateScriptFunction), - modifiers, - false - ); -} - -function createInitializeStruct( - structInfo: arkts.StructInfo, - optionsTypeName: string, - isDecl?: boolean -) { - const updateKey: arkts.Identifier = arkts.factory.createIdentifier( - CustomComponentNames.COMPONENT_INITIALIZE_STRUCT - ); - - let body: arkts.BlockStatement | undefined; - let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT; - if (!isDecl) { - body = arkts.factory.createBlock(structInfo.initializeBody); - modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; - } - const scriptFunction: arkts.ScriptFunction = arkts.factory.createScriptFunction( - body, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [ - factory.createInitializersOptionsParameter(optionsTypeName), - factory.createContentParameter() - ], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - modifiers - ) - .setIdent(updateKey); - - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - updateKey, - arkts.factory.createFunctionExpression(scriptFunction), - modifiers, - false - ); -} - -function createUpdateStruct( - structInfo: arkts.StructInfo, - optionsTypeName: string, - isDecl?: boolean -) { - const updateKey: arkts.Identifier = arkts.factory.createIdentifier( - CustomComponentNames.COMPONENT_UPDATE_STRUCT - ); - - let body: arkts.BlockStatement | undefined; - let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT; - if (!isDecl) { - body = arkts.factory.createBlock(structInfo.updateBody); - modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; - } - - const scriptFunction: arkts.ScriptFunction = arkts.factory.createScriptFunction( - body, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [ - factory.createInitializersOptionsParameter(optionsTypeName) - ], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - modifiers - ) - .setIdent(updateKey); - - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - updateKey, - arkts.factory.createFunctionExpression(scriptFunction), - modifiers, - false - ); -} - -function toRecord(optionsTypeName: string, toRecordBody: arkts.Property[]){ - // const paramsCasted = params as ChildOptions - const paramsCasted = arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, - [arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_CONST, - arkts.factory.createIdentifier("paramsCasted"), - arkts.TSAsExpression.createTSAsExpression( - arkts.factory.createIdentifier("params"), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(optionsTypeName) - ) - ), - false - ) - )] - ) - - const returnRecord = arkts.factory.createReturnStatement( - arkts.ObjectExpression.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - toRecordBody, - false - ) - ) - - const body: arkts.BlockStatement = arkts.factory.createBlock([paramsCasted, returnRecord]); - - const params = arkts.ETSParameterExpression.create( - arkts.factory.createIdentifier( - "params", - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier("Object") - ) - ) - ), - undefined - ) - - const typeRecord = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier("Record"), - arkts.factory.createTSTypeParameterInstantiation( - [ - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier("string"), - ) - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier("Object") - ) - ) - ] - ) - ) - ) - - const toRecordScriptFunction = arkts.factory.createScriptFunction( - body, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [ params ], - typeRecord, - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ) - - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, - arkts.factory.createIdentifier('__toRecord'), - arkts.factory.createFunctionExpression(toRecordScriptFunction), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE, - false - ); -} - -function tranformPropertyMembers( - className: string, - propertyTranslators: PropertyTranslator[], - optionsTypeName: string, - isDecl?: boolean, - scope?: ScopeInfo -): arkts.AstNode[] { - const propertyMembers = propertyTranslators.map(translator => - translator.translateMember() - ); - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo - .getInfoInstance() - .getStructInfo(className); - const collections = []; - if (!scope?.hasInitializeStruct) { - collections.push(createInitializeStruct(currentStructInfo, optionsTypeName, isDecl)) - } - if (!scope?.hasUpdateStruct) { - collections.push(createUpdateStruct(currentStructInfo, optionsTypeName, isDecl)) - } - if(currentStructInfo.isReusable){ - collections.push(toRecord(optionsTypeName, currentStructInfo.toRecordBody)) - } - return collect(...collections, ...propertyMembers); -} - -function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.ClassDeclaration { - if (!node.definition) { - return node; - } - node.definition.body.map((member: arkts.AstNode) => { - if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { - member.scriptFunction.setAnnotations([annotation("memo")]); - } - return member; - }); - return node; -} - -function tranformClassMembers( - node: arkts.ClassDeclaration, - isDecl?: boolean, - scope?: ScopeInfo -): arkts.ClassDeclaration { - if (!node.definition) { - return node; - } - - let classTypeName: string | undefined; - let classOptionsName: string | undefined; - if (isDecl) { - const [classType, classOptions] = getTypeParamsFromClassDecl(node); - classTypeName = getTypeNameFromTypeParameter(classType); - classOptionsName = getTypeNameFromTypeParameter(classOptions); - } - - const definition: arkts.ClassDefinition = node.definition; - const className: string | undefined = node.definition.ident?.name; - if (!className) { - throw new Error("Non Empty className expected for Component") - } - - const propertyTranslators: PropertyTranslator[] = filterDefined( - definition.body.map(it => classifyProperty(it, className)) - ); - - const translatedMembers: arkts.AstNode[] = tranformPropertyMembers( - className, - propertyTranslators, - classOptionsName ?? getCustomComponentOptionsName(className), - isDecl, - scope - ); - - const updateMembers: arkts.AstNode[] = definition.body - .filter((member)=>!arkts.isClassProperty(member)) - .map((member: arkts.AstNode) => { - if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { - member.scriptFunction.setAnnotations([annotation("memo")]); - return member; - } - if ( - arkts.isMethodDefinition(member) - && isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI) - && !isDecl - ) { - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, - member.name, - arkts.factory.createFunctionExpression(member.scriptFunction), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, - false - ); - } - if ( - arkts.isMethodDefinition(member) - && isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI) - ) { - const buildMethod = transformBuildMethod( - member, - classTypeName ?? className, - classOptionsName ?? getCustomComponentOptionsName(className), - isDecl - ); - return buildMethod; - } - - return member; - } - ); - - const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( - definition, - definition.ident, - definition.typeParams, - definition.superTypeParams, - definition.implements, - undefined, - definition.super, - [...translatedMembers, ...updateMembers], - definition.modifiers, - arkts.classDefinitionFlags(definition) - ); - - return arkts.factory.updateClassDeclaration(node, updateClassDef); -} - -function transformResource(resourceNode: arkts.CallExpression, projectConfig: ProjectConfig | undefined): arkts.CallExpression { - const newArgs: arkts.AstNode[] = [ - arkts.factory.create1StringLiteral(projectConfig?.bundleName ? projectConfig.bundleName : ""), - arkts.factory.create1StringLiteral(projectConfig?.moduleName ? projectConfig.moduleName : ""), - ...resourceNode.arguments - ]; - const transformedKey: string = - resourceNode.expression.dumpSrc() === Dollars.DOLLAR_RESOURCE ? '_r' : '_rawfile'; - return arkts.factory.updateCallExpression( - resourceNode, - arkts.factory.createIdentifier(transformedKey), - resourceNode.typeArguments, - newArgs - ); -} - -type ScopeInfo = { - name: string, - hasInitializeStruct?: boolean, - hasUpdateStruct?: boolean, - hasReusableRebind?: boolean -} - -export class StructTransformer extends AbstractVisitor { - private scopeInfos: ScopeInfo[] = []; - projectConfig: ProjectConfig | undefined; - - constructor(projectConfig: ProjectConfig | undefined) { - super() - this.projectConfig = projectConfig; - } - - reset(): void { - super.reset(); - this.scopeInfos = []; - } - - enter(node: arkts.AstNode) { - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfos.push({ name: node.definition!.ident!.name }); - } - if (arkts.isMethodDefinition(node) && this.scopeInfos.length > 0) { - const name = node.name.name; - const scopeInfo = this.scopeInfos.pop()!; - scopeInfo.hasInitializeStruct ||= (name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT); - scopeInfo.hasUpdateStruct ||= (name === CustomComponentNames.COMPONENT_UPDATE_STRUCT); - scopeInfo.hasReusableRebind ||= (name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE); - this.scopeInfos.push(scopeInfo); - } - } - - exit(node: arkts.AstNode) { - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfos.pop(); - } - } - - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - this.enter(beforeChildren); - const node = this.visitEachChild(beforeChildren); - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - let scope: ScopeInfo | undefined; - if (this.scopeInfos.length > 0) { - scope = this.scopeInfos[this.scopeInfos.length - 1]; - } - const newClass: arkts.ClassDeclaration = tranformClassMembers( - node, - arkts.hasModifierFlag(node, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE), - scope - ); - this.exit(beforeChildren); - return newClass; - } else if (isEntryWrapperClass(node)) { - entryFactory.addMemoToEntryWrapperClassMethods(node); - return node; - } else if (arkts.isClassDeclaration(node) && isEtsGlobalClass(node)) { - return transformEtsGlobalClassMembers(node); - } else if (arkts.isCallExpression(node) && isReourceNode(node)) { - return transformResource(node, this.projectConfig); - } - return node; - } -} - diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts new file mode 100644 index 000000000..4b2d08594 --- /dev/null +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -0,0 +1,277 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { CustomComponentNames, Dollars } from '../utils'; +import { factory as uiFactory } from '../ui-factory'; +import { annotation } from '../../common/arkts-utils'; + +export class factory { + /* + * create `constructor() {}`. + */ + static createConstructorMethod(member: arkts.MethodDefinition): arkts.MethodDefinition { + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, + member.name, + arkts.factory.createFunctionExpression(member.scriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, + false + ); + } + + /* + * create _build menthod. + */ + static transformBuildMethodWithOriginBuild( + method: arkts.MethodDefinition, + typeName: string, + optionsName: string, + isDecl?: boolean + ): arkts.MethodDefinition { + const updateKey: arkts.Identifier = arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_BUILD); + + const scriptFunction: arkts.ScriptFunction = method.scriptFunction; + const updateScriptFunction = arkts.factory + .createScriptFunction( + scriptFunction.body, + arkts.FunctionSignature.createFunctionSignature( + scriptFunction.typeParams, + [ + uiFactory.createStyleParameter(typeName), + uiFactory.createContentParameter(), + uiFactory.createInitializersOptionsParameter(optionsName), + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + scriptFunction.flags, + scriptFunction.modifiers + ) + .setAnnotations([annotation('memo')]); + + const modifiers: arkts.Es2pandaModifierFlags = isDecl + ? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT + : arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + updateKey, + arkts.factory.createFunctionExpression(updateScriptFunction), + modifiers, + false + ); + } + + /* + * generate _r() or _rawfile(). + */ + static generateTransformedResource( + resourceNode: arkts.CallExpression, + newArgs: arkts.AstNode[] + ): arkts.CallExpression { + const transformedKey: string = + resourceNode.expression.dumpSrc() === Dollars.DOLLAR_RESOURCE ? '_r' : '_rawfile'; + return arkts.factory.updateCallExpression( + resourceNode, + arkts.factory.createIdentifier(transformedKey), + resourceNode.typeArguments, + newArgs + ); + } + + /* + * create __initializeStruct menthod. + */ + static createInitializeStruct( + structInfo: arkts.StructInfo, + optionsTypeName: string, + isDecl?: boolean + ): arkts.MethodDefinition { + const updateKey: arkts.Identifier = arkts.factory.createIdentifier( + CustomComponentNames.COMPONENT_INITIALIZE_STRUCT + ); + + let body: arkts.BlockStatement | undefined; + let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT; + if (!isDecl) { + body = arkts.factory.createBlock(structInfo.initializeBody); + modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; + } + const scriptFunction: arkts.ScriptFunction = arkts.factory + .createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [uiFactory.createInitializersOptionsParameter(optionsTypeName), uiFactory.createContentParameter()], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + modifiers + ) + .setIdent(updateKey); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + updateKey, + arkts.factory.createFunctionExpression(scriptFunction), + modifiers, + false + ); + } + + /* + * create __updateStruct menthod. + */ + static createUpdateStruct( + structInfo: arkts.StructInfo, + optionsTypeName: string, + isDecl?: boolean + ): arkts.MethodDefinition { + const updateKey: arkts.Identifier = arkts.factory.createIdentifier( + CustomComponentNames.COMPONENT_UPDATE_STRUCT + ); + + let body: arkts.BlockStatement | undefined; + let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT; + if (!isDecl) { + body = arkts.factory.createBlock(structInfo.updateBody); + modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; + } + + const scriptFunction: arkts.ScriptFunction = arkts.factory + .createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature( + undefined, + [uiFactory.createInitializersOptionsParameter(optionsTypeName)], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + modifiers + ) + .setIdent(updateKey); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + updateKey, + arkts.factory.createFunctionExpression(scriptFunction), + modifiers, + false + ); + } + + /* + * create __toRecord menthod when the component is decorated with @Reusable. + */ + static toRecord(optionsTypeName: string, toRecordBody: arkts.Property[]): arkts.MethodDefinition { + const paramsCasted = factory.generateParamsCasted(optionsTypeName); + const returnRecord = arkts.factory.createReturnStatement( + arkts.ObjectExpression.createObjectExpression( + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + toRecordBody, + false + ) + ); + const body: arkts.BlockStatement = arkts.factory.createBlock([paramsCasted, returnRecord]); + + const params = arkts.ETSParameterExpression.create( + arkts.factory.createIdentifier('params', factory.generateTypeReferenceWithTypeName('Object')), + undefined + ); + + const toRecordScriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature(undefined, [params], factory.generateTypeRecord(), false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, + arkts.factory.createIdentifier('__toRecord'), + arkts.factory.createFunctionExpression(toRecordScriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE, + false + ); + } + + /* + * generate `const paramsCasted = (params as )`. + */ + static generateParamsCasted(optionsTypeName: string): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_CONST, + arkts.factory.createIdentifier('paramsCasted'), + arkts.TSAsExpression.createTSAsExpression( + arkts.factory.createIdentifier('params'), + factory.generateTypeReferenceWithTypeName(optionsTypeName), + false + ) + ), + ] + ); + } + + /* + * generate Record type. + */ + static generateTypeRecord(): arkts.ETSTypeReference { + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('Record'), + arkts.factory.createTSTypeParameterInstantiation([ + factory.generateTypeReferenceWithTypeName('string'), + factory.generateTypeReferenceWithTypeName('Object'), + ]) + ) + ); + } + + /* + * create type reference with type name, e.g. number. + */ + static generateTypeReferenceWithTypeName(typeName: string): arkts.ETSTypeReference { + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(typeName)) + ); + } + + /* + * create type reference with type name, e.g. number. + */ + static updateCustomComponentClass( + definition: arkts.ClassDefinition, + members: arkts.AstNode[] + ): arkts.ClassDefinition { + return arkts.factory.updateClassDefinition( + definition, + definition.ident, + definition.typeParams, + definition.superTypeParams, + definition.implements, + undefined, + definition.super, + members, + definition.modifiers, + arkts.classDefinitionFlags(definition) + ); + } +} diff --git a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts new file mode 100644 index 000000000..25dc8c97e --- /dev/null +++ b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor } from '../../common/abstract-visitor'; +import { annotation, collect, filterDefined } from '../../common/arkts-utils'; +import { ProjectConfig } from '../../common/plugin-context'; +import { classifyProperty, PropertyTranslator } from '../property-translators'; +import { + CustomComponentNames, + getCustomComponentOptionsName, + getTypeNameFromTypeParameter, + getTypeParamsFromClassDecl, +} from '../utils'; +import { isCustomComponentClass, isKnownMethodDefinition, isEtsGlobalClass, isReourceNode } from './utils'; +import { factory as uiFactory } from '../ui-factory'; +import { factory } from './factory'; +import { isEntryWrapperClass } from '../entry-translators/utils'; +import { factory as entryFactory } from '../entry-translators/factory'; +import { DecoratorNames, hasDecorator } from '../property-translators/utils'; +import { ScopeInfo } from './utils'; + +function tranformPropertyMembers( + className: string, + propertyTranslators: PropertyTranslator[], + optionsTypeName: string, + isDecl?: boolean, + scope?: ScopeInfo +): arkts.AstNode[] { + const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); + const collections = []; + if (!scope?.hasInitializeStruct) { + collections.push(factory.createInitializeStruct(currentStructInfo, optionsTypeName, isDecl)); + } + if (!scope?.hasUpdateStruct) { + collections.push(factory.createUpdateStruct(currentStructInfo, optionsTypeName, isDecl)); + } + if ( currentStructInfo.isReusable ) { + collections.push(factory.toRecord(optionsTypeName, currentStructInfo.toRecordBody)); + } + return collect(...collections, ...propertyMembers); +} + +function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.ClassDeclaration { + if (!node.definition) { + return node; + } + node.definition.body.map((member: arkts.AstNode) => { + if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { + member.scriptFunction.setAnnotations([annotation('memo')]); + } + return member; + }); + return node; +} + +function transformOtherMembersInClass( + member: arkts.AstNode, + classTypeName: string | undefined, + classOptionsName: string | undefined, + className: string, + isDecl?: boolean +): arkts.AstNode { + if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { + member.scriptFunction.setAnnotations([annotation('memo')]); + return member; + } + if ( + arkts.isMethodDefinition(member) && + isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI) && + !isDecl + ) { + return uiFactory.createConstructorMethod(member); + } + if (arkts.isMethodDefinition(member) && isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI)) { + return factory.transformBuildMethodWithOriginBuild( + member, + classTypeName ?? className, + classOptionsName ?? getCustomComponentOptionsName(className), + isDecl + ); + } + return member; +} + +function tranformClassMembers( + node: arkts.ClassDeclaration, + isDecl?: boolean, + scope?: ScopeInfo +): arkts.ClassDeclaration { + if (!node.definition) { + return node; + } + + let classTypeName: string | undefined; + let classOptionsName: string | undefined; + if (isDecl) { + const [classType, classOptions] = getTypeParamsFromClassDecl(node); + classTypeName = getTypeNameFromTypeParameter(classType); + classOptionsName = getTypeNameFromTypeParameter(classOptions); + } + const definition: arkts.ClassDefinition = node.definition; + const className: string | undefined = node.definition.ident?.name; + if (!className) { + throw new Error('Non Empty className expected for Component'); + } + + const propertyTranslators: PropertyTranslator[] = filterDefined( + definition.body.map((it) => classifyProperty(it, className)) + ); + const translatedMembers: arkts.AstNode[] = tranformPropertyMembers( + className, + propertyTranslators, + classOptionsName ?? getCustomComponentOptionsName(className), + isDecl, + scope + ); + const updateMembers: arkts.AstNode[] = definition.body + .filter((member) => !arkts.isClassProperty(member)) + .map((member: arkts.AstNode) => + transformOtherMembersInClass(member, classTypeName, classOptionsName, className, isDecl) + ); + + const updateClassDef: arkts.ClassDefinition = factory.updateCustomComponentClass(definition, [ + ...translatedMembers, + ...updateMembers, + ]); + return arkts.factory.updateClassDeclaration(node, updateClassDef); +} + +function transformResource( + resourceNode: arkts.CallExpression, + projectConfig: ProjectConfig | undefined +): arkts.CallExpression { + const newArgs: arkts.AstNode[] = [ + arkts.factory.create1StringLiteral(projectConfig?.bundleName ? projectConfig.bundleName : ''), + arkts.factory.create1StringLiteral(projectConfig?.moduleName ? projectConfig.moduleName : ''), + ...resourceNode.arguments, + ]; + return factory.generateTransformedResource(resourceNode, newArgs); +} + +export class StructTransformer extends AbstractVisitor { + private scopeInfos: ScopeInfo[] = []; + projectConfig: ProjectConfig | undefined; + + constructor(projectConfig: ProjectConfig | undefined) { + super(); + this.projectConfig = projectConfig; + } + + reset(): void { + super.reset(); + this.scopeInfos = []; + } + + enter(node: arkts.AstNode): void { + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + this.scopeInfos.push({ name: node.definition!.ident!.name }); + } + if (arkts.isMethodDefinition(node) && this.scopeInfos.length > 0) { + const name = node.name.name; + const scopeInfo = this.scopeInfos.pop()!; + scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; + scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; + scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; + this.scopeInfos.push(scopeInfo); + } + } + + exit(node: arkts.AstNode): void { + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + this.scopeInfos.pop(); + } + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + this.enter(beforeChildren); + const node = this.visitEachChild(beforeChildren); + if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { + let scope: ScopeInfo | undefined; + if (this.scopeInfos.length > 0) { + scope = this.scopeInfos[this.scopeInfos.length - 1]; + } + const newClass: arkts.ClassDeclaration = tranformClassMembers( + node, + arkts.hasModifierFlag(node, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE), + scope + ); + this.exit(beforeChildren); + return newClass; + } else if (isEntryWrapperClass(node)) { + entryFactory.addMemoToEntryWrapperClassMethods(node); + return node; + } else if (arkts.isClassDeclaration(node) && isEtsGlobalClass(node)) { + return transformEtsGlobalClassMembers(node); + } else if (arkts.isCallExpression(node) && isReourceNode(node)) { + return transformResource(node, this.projectConfig); + } + return node; + } +} diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts new file mode 100644 index 000000000..18e9e51a1 --- /dev/null +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { Dollars } from '../utils'; +import { CustomComponentNames } from '../utils'; + +export type ScopeInfo = { + name: string; + hasInitializeStruct?: boolean; + hasUpdateStruct?: boolean; + hasReusableRebind?: boolean; +}; + +/** + * Determine whether it is a custom component. + * + * @param node class declaration node + */ +export function isCustomComponentClass(node: arkts.ClassDeclaration): boolean { + if (!node.definition?.ident?.name) { + return false; + }; + const name: string = node.definition.ident.name; + const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); + return name === CustomComponentNames.COMPONENT_CLASS_NAME || structCollection.has(name); +} + +/** + * Determine whether it is method with specified name. + * + * @param method method definition node + * @param name specified method name + */ +export function isKnownMethodDefinition(method: arkts.MethodDefinition, name: string): boolean { + if (!method || !arkts.isMethodDefinition(method)) { + return false; + }; + + // For now, we only considered matched method name. + const isNameMatched: boolean = method.name?.name === name; + return isNameMatched; +} + +/** + * Determine whether it is ETSGLOBAL class. + * + * @param node class declaration node + */ +export function isEtsGlobalClass(node: arkts.ClassDeclaration): boolean { + if (node.definition?.ident?.name === 'ETSGLOBAL') { + return true; + } + return false; +} + +/** + * Determine whether it is resource node begin with '$r' or '$rawfile'. + * + * @param node call expression node + */ +export function isReourceNode(node: arkts.CallExpression): boolean { + if (node.expression.dumpSrc() === Dollars.DOLLAR_RESOURCE || node.expression.dumpSrc() === Dollars.DOLLAR_RAWFILE) { + return true; + } + return false; +} diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index 5cf4028df..3c0c59e6b 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -13,12 +13,9 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { - BuilderLambdaNames, - CustomComponentNames -} from "./utils"; -import { annotation } from "../common/arkts-utils"; +import * as arkts from '@koalaui/libarkts'; +import { BuilderLambdaNames, CustomComponentNames } from './utils'; +import { annotation } from '../common/arkts-utils'; export class factory { /** @@ -28,17 +25,14 @@ export class factory { return arkts.factory.createIdentifier( BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, factory.createTypeReferenceFromString(typeName) - ) + ); } /** * create `instance: ` as parameter */ static createInstanceParameter(typeName: string): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration( - factory.createInstanceIdentifier(typeName), - undefined - ) + return arkts.factory.createParameterDeclaration(factory.createInstanceIdentifier(typeName), undefined); } /** @@ -48,9 +42,7 @@ export class factory { return arkts.factory.createFunctionType( arkts.FunctionSignature.createFunctionSignature( undefined, - [ - factory.createInstanceParameter(typeName) - ], + [factory.createInstanceParameter(typeName)], factory.createTypeReferenceFromString(typeName), false ), @@ -66,9 +58,9 @@ export class factory { BuilderLambdaNames.STYLE_PARAM_NAME, arkts.factory.createUnionType([ factory.createStyleLambdaFunctionType(typeName), - arkts.factory.createETSUndefinedType() + arkts.factory.createETSUndefinedType(), ]) - ) + ); } /** @@ -77,7 +69,7 @@ export class factory { static createStyleParameter(typeName: string): arkts.ETSParameterExpression { const styleParam: arkts.Identifier = factory.createStyleIdentifier(typeName); const param = arkts.factory.createParameterDeclaration(styleParam, undefined); - param.annotations = [annotation("memo")]; + param.annotations = [annotation('memo')]; return param; } @@ -89,9 +81,9 @@ export class factory { CustomComponentNames.COMPONENT_INITIALIZERS_NAME, arkts.factory.createUnionType([ factory.createTypeReferenceFromString(optionsName), - arkts.factory.createETSUndefinedType() + arkts.factory.createETSUndefinedType(), ]) - ) + ); } /** @@ -99,11 +91,9 @@ export class factory { */ static createInitializersOptionsParameter(optionsName: string): arkts.ETSParameterExpression { return arkts.factory.createParameterDeclaration( - factory.createInitializerOptionsIdentifier( - optionsName - ), + factory.createInitializerOptionsIdentifier(optionsName), undefined - ) + ); } /** @@ -112,10 +102,7 @@ export class factory { static createContentIdentifier(): arkts.Identifier { return arkts.factory.createIdentifier( BuilderLambdaNames.CONTENT_PARAM_NAME, - arkts.factory.createUnionType([ - factory.createLambdaFunctionType(), - arkts.factory.createETSUndefinedType() - ]) + arkts.factory.createUnionType([factory.createLambdaFunctionType(), arkts.factory.createETSUndefinedType()]) ); } @@ -125,18 +112,16 @@ export class factory { static createContentParameter(): arkts.ETSParameterExpression { const contentParam: arkts.Identifier = factory.createContentIdentifier(); const param = arkts.factory.createParameterDeclaration(contentParam, undefined); - param.annotations = [annotation("memo")]; + param.annotations = [annotation('memo')]; return param; } /** * create type from string */ - static createTypeReferenceFromString(name: string): arkts.TypeNode { + static createTypeReferenceFromString(name: string): arkts.TypeNode { return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(name) - ) + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(name)) ); } @@ -151,12 +136,11 @@ export class factory { arkts.FunctionSignature.createFunctionSignature( undefined, params ?? [], - returnType - ?? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + returnType ?? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), false ), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW - ) + ); } /** @@ -171,28 +155,75 @@ export class factory { ): void { const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, - [ - arkts.factory.createImportSpecifier( - imported, - local - ) - ], + [arkts.factory.createImportSpecifier(imported, local)], importKind - ) + ); arkts.importDeclarationInsert(importDecl, program); return; } - + /* - * create `import { as } ...`. - */ - static createAdditionalImportSpecifier( - name1: string, - name2: string - ): arkts.ImportSpecifier { + * create `import { as } ...`. + */ + static createAdditionalImportSpecifier(imported: string, local: string): arkts.ImportSpecifier { return arkts.factory.createImportSpecifier( - arkts.factory.createIdentifier(name1), - arkts.factory.createIdentifier(name2), + arkts.factory.createIdentifier(imported), + arkts.factory.createIdentifier(local) + ); + } + + /* + * create `constructor() {}`. + */ + static createConstructorMethod(member: arkts.MethodDefinition): arkts.MethodDefinition { + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, + member.name, + arkts.factory.createFunctionExpression(member.scriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, + false + ); + } + + /* + * create `@memo() _build(<>)`. + */ + static transformBuildMethodWithOriginBuild( + method: arkts.MethodDefinition, + typeName: string, + optionsName: string, + isDecl?: boolean + ): arkts.MethodDefinition { + const updateKey: arkts.Identifier = arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_BUILD); + + const scriptFunction: arkts.ScriptFunction = method.scriptFunction; + const updateScriptFunction = arkts.factory + .createScriptFunction( + scriptFunction.body, + arkts.FunctionSignature.createFunctionSignature( + scriptFunction.typeParams, + [ + factory.createStyleParameter(typeName), + factory.createContentParameter(), + factory.createInitializersOptionsParameter(optionsName), + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + scriptFunction.flags, + scriptFunction.modifiers + ) + .setAnnotations([annotation('memo')]); + + const modifiers: arkts.Es2pandaModifierFlags = isDecl + ? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT + : arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + updateKey, + arkts.factory.createFunctionExpression(updateScriptFunction), + modifiers, + false ); } } diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index ab9cc8571..6408164b1 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -14,7 +14,6 @@ */ import * as arkts from '@koalaui/libarkts'; -import { isAnnotation } from '../common/arkts-utils'; export enum CustomComponentNames { ENTRY_ANNOTATION_NAME = 'Entry', @@ -84,86 +83,6 @@ export function isStatic(node: arkts.AstNode): boolean { return node.isStatic; } -export function isBuilderLambdaAnnotation(node: arkts.AnnotationUsage): boolean { - return isAnnotation(node, BuilderLambdaNames.ANNOTATION_NAME); -} - -export type BuilderLambdaAstNode = arkts.ScriptFunction - | arkts.ETSParameterExpression - | arkts.FunctionDeclaration; - -export function hasBuilderLambdaAnnotation(node: BuilderLambdaAstNode): boolean { - return node.annotations.some(isBuilderLambdaAnnotation); -} - -export function findBuilderLambdaAnnotation( - node: arkts.ScriptFunction | arkts.ETSParameterExpression, -): arkts.AnnotationUsage | undefined { - return node.annotations.find(isBuilderLambdaAnnotation); -} - -export function isBuilderLambdaMethod(node: arkts.MethodDefinition): boolean { - if (!node || !arkts.isMethodDefinition(node)) return false; - - const result = hasBuilderLambdaAnnotation(node.scriptFunction); - if (result) return true; - if (node.overloads.length > 0) { - return node.overloads.some(isBuilderLambdaMethod); - } - return false; -} - -export function findBuilderLambdaInMethod(node: arkts.MethodDefinition): arkts.AnnotationUsage | undefined { - if (!node || !arkts.isMethodDefinition(node)) return undefined; - - const result = findBuilderLambdaAnnotation(node.scriptFunction); - if (!!result) return result; - node.overloads.forEach((overload) => { - const anno: arkts.AnnotationUsage | undefined = findBuilderLambdaInMethod(overload); - if (!!anno) return anno; - }); - return undefined; -} - -export function isBuilderLambdaCall(node: arkts.CallExpression | arkts.Identifier): boolean { - const expr = arkts.isIdentifier(node) ? node : node.expression; - const decl = arkts.getDecl(expr); - - if (!decl) return false; - - if (arkts.isMethodDefinition(decl)) { - return isBuilderLambdaMethod(decl); - } - if (arkts.isFunctionExpression(decl)) { - return hasBuilderLambdaAnnotation(decl.scriptFunction); - } - return false; -} - -export function findBuilderLambdaInCall( - node: arkts.CallExpression | arkts.Identifier, -): arkts.AnnotationUsage | undefined { - const decl = findBuilderLambdaDecl(node); - if (!decl) return undefined; - - if (arkts.isMethodDefinition(decl)) { - return findBuilderLambdaInMethod(decl); - } - if (arkts.isFunctionExpression(decl)) { - return findBuilderLambdaAnnotation(decl.scriptFunction); - } - return undefined; -} - -export function findBuilderLambdaDecl(node: arkts.CallExpression | arkts.Identifier): arkts.AstNode | undefined { - const expr = arkts.isIdentifier(node) ? node : node.expression; - const decl = arkts.getDecl(expr); - - if (!decl) return undefined; - - return decl; -} - export function getTypeParamsFromClassDecl(node: arkts.ClassDeclaration | undefined): readonly arkts.TSTypeParameter[] { return node?.definition?.typeParams?.params ?? []; } -- Gitee From 66c0388a8294669e0a65eb0abaa48ff9de687dbf Mon Sep 17 00:00:00 2001 From: seaside_wu Date: Wed, 9 Apr 2025 16:33:48 +0800 Subject: [PATCH 032/123] code format Signed-off-by: seaside_wu Change-Id: I85da33d5b995dcd3b0e4440ce39ee699eccb41bf --- arkui-plugins/.prettierrc | 8 + arkui-plugins/build_ui_plugins.py | 1 + arkui-plugins/common/abstract-visitor.ts | 29 +- arkui-plugins/common/arkts-utils.ts | 32 +- arkui-plugins/common/debug.ts | 22 +- arkui-plugins/common/etsglobal-remover.ts | 17 +- arkui-plugins/common/gensym-generator.ts | 16 +- arkui-plugins/common/plugin-context.ts | 44 +-- arkui-plugins/common/predefines.ts | 111 +++---- arkui-plugins/common/print-visitor.ts | 14 +- arkui-plugins/common/program-visitor.ts | 58 ++-- .../interop-plugins/decl_transformer.ts | 109 +++---- .../interop-plugins/emit_transformer.ts | 72 ++--- arkui-plugins/interop-plugins/index.ts | 2 +- .../interop-plugins/interop_plugin.ts | 128 ++++---- arkui-plugins/interop-plugins/types.ts | 78 ++--- arkui-plugins/jest-test.config.ts | 15 +- .../memo-plugins/function-transformer.ts | 305 +++++++++--------- .../memo-plugins/import-transformer.ts | 13 +- arkui-plugins/memo-plugins/index.ts | 68 ++-- arkui-plugins/memo-plugins/memo-factory.ts | 193 ++++++----- .../memo-plugins/memo-transformer.ts | 55 ++-- .../memo-plugins/parameter-transformer.ts | 122 ++++--- .../memo-plugins/return-transformer.ts | 36 +-- .../memo-plugins/signature-transformer.ts | 60 ++-- arkui-plugins/memo-plugins/utils.ts | 146 +++++---- arkui-plugins/path.ts | 16 +- .../test/ut/common/annotation.test.ts | 34 +- .../instantiate-content.test.ts | 63 ++-- .../instantiate-multi-content.test.ts | 66 ++-- .../builder-lambda/instantiate.test.ts | 54 ++-- .../transform-struct-to-class.test.ts | 54 ++-- arkui-plugins/test/utils/artkts-config.ts | 175 +++++----- arkui-plugins/test/utils/compile.ts | 39 +-- arkui-plugins/test/utils/global.ts | 22 +- arkui-plugins/test/utils/parse-string.ts | 14 +- arkui-plugins/test/utils/path-config.ts | 16 +- arkui-plugins/test/utils/plugin-driver.ts | 33 +- arkui-plugins/test/utils/plugin-tester.ts | 78 ++--- arkui-plugins/test/utils/safe-types.ts | 4 +- .../ui-plugins/checked-transformer.ts | 2 +- .../ui-plugins/component-transformer.ts | 56 ++-- .../entry-translators/entry-transformer.ts | 10 +- .../ui-plugins/entry-translators/utils.ts | 40 ++- arkui-plugins/ui-plugins/name-collector.ts | 19 +- .../ui-plugins/preprocessor-transform.ts | 125 +++---- .../ui-plugins/printer-transformer.ts | 14 +- .../ui-plugins/property-translators/base.ts | 20 +- .../property-translators/builderParam.ts | 72 +++-- .../property-translators/consume.ts | 60 ++-- .../property-translators/factory.ts | 139 ++++---- .../ui-plugins/property-translators/index.ts | 5 +- .../ui-plugins/property-translators/link.ts | 28 +- .../property-translators/localstoragelink.ts | 8 +- .../property-translators/localstorageprop.ts | 26 +- .../property-translators/objectlink.ts | 16 +- .../ui-plugins/property-translators/prop.ts | 99 +++--- .../property-translators/provide.ts | 100 +++--- .../property-translators/regularProperty.ts | 34 +- .../ui-plugins/property-translators/state.ts | 75 +++-- .../property-translators/staticProperty.ts | 29 +- .../property-translators/storageProp.ts | 24 +- .../property-translators/storagelink.ts | 24 +- .../ui-plugins/property-translators/types.ts | 22 +- .../ui-plugins/property-translators/utils.ts | 61 ++-- .../struct-translators/struct-transformer.ts | 2 +- .../ui-plugins/struct-translators/utils.ts | 4 +- arkui-plugins/ui-plugins/utils.ts | 25 +- 68 files changed, 1686 insertions(+), 1875 deletions(-) create mode 100644 arkui-plugins/.prettierrc diff --git a/arkui-plugins/.prettierrc b/arkui-plugins/.prettierrc new file mode 100644 index 000000000..e9e9c6fdb --- /dev/null +++ b/arkui-plugins/.prettierrc @@ -0,0 +1,8 @@ +{ + "semi": true, + "singleQuote": true, + "tabWidth": 4, + "trailingComma": "es5", + "bracketSpacing": true, + "printWidth": 120 +} \ No newline at end of file diff --git a/arkui-plugins/build_ui_plugins.py b/arkui-plugins/build_ui_plugins.py index 0d56133ba..3fe73510c 100755 --- a/arkui-plugins/build_ui_plugins.py +++ b/arkui-plugins/build_ui_plugins.py @@ -56,6 +56,7 @@ def copy_output(options): copy_files(os.path.join(options.source_path, 'package.json'), os.path.join(options.output_path, 'package.json'), True) + def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--npm', help='path to a npm exetuable') diff --git a/arkui-plugins/common/abstract-visitor.ts b/arkui-plugins/common/abstract-visitor.ts index bccf6408a..2c7a307da 100644 --- a/arkui-plugins/common/abstract-visitor.ts +++ b/arkui-plugins/common/abstract-visitor.ts @@ -13,13 +13,13 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; export interface VisitorOptions { - isExternal?: boolean, - externalSourceName?: string, - program?: arkts.Program -} + isExternal?: boolean; + externalSourceName?: string; + program?: arkts.Program; +} export abstract class AbstractVisitor implements VisitorOptions { public isExternal: boolean; @@ -32,27 +32,22 @@ export abstract class AbstractVisitor implements VisitorOptions { this.program = options?.program; } - indentation = 0 + indentation = 0; withIndentation(exec: () => T) { - this.indentation++ - const result = exec() - this.indentation-- - return result + this.indentation++; + const result = exec(); + this.indentation--; + return result; } - abstract visitor(node: arkts.AstNode): arkts.AstNode + abstract visitor(node: arkts.AstNode): arkts.AstNode; reset(): void { this.indentation = 0; } visitEachChild(node: arkts.AstNode): arkts.AstNode { - return this.withIndentation(() => - arkts.visitEachChild( - node, - it => this.visitor(it) - ) - ) + return this.withIndentation(() => arkts.visitEachChild(node, (it) => this.visitor(it))); } } diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index 86f04a280..771442543 100644 --- a/arkui-plugins/common/arkts-utils.ts +++ b/arkui-plugins/common/arkts-utils.ts @@ -16,25 +16,17 @@ import * as arkts from '@koalaui/libarkts'; export function annotation(name: string): arkts.AnnotationUsage { - const ident: arkts.Identifier = arkts.factory - .createIdentifier(name) - .setAnnotationUsage(); - const annotation: arkts.AnnotationUsage = - arkts.factory.createAnnotationUsage(ident); + const ident: arkts.Identifier = arkts.factory.createIdentifier(name).setAnnotationUsage(); + const annotation: arkts.AnnotationUsage = arkts.factory.createAnnotationUsage(ident); - annotation.modifiers = - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ANNOTATION_USAGE; + annotation.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ANNOTATION_USAGE; ident.parent = annotation; return annotation; } export function isAnnotation(node: arkts.AnnotationUsage, annoName: string) { - return ( - node.expr !== undefined && - arkts.isIdentifier(node.expr) && - node.expr.name === annoName - ); + return node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === annoName; } export function removeAnnotationByName( @@ -49,9 +41,7 @@ export function expectName(node: arkts.AstNode | undefined): string { throw new Error('Expected an identifier, got empty node'); } if (!arkts.isIdentifier(node)) { - throw new Error( - 'Expected an identifier, got: ' + arkts.nodeType(node).toString() - ); + throw new Error('Expected an identifier, got: ' + arkts.nodeType(node).toString()); } return node.name; } @@ -68,17 +58,12 @@ export function filterDefined(value: (T | undefined)[]): T[] { return value.filter((it: T | undefined): it is T => it != undefined); } -export function collect( - ...value: (ReadonlyArray | T | undefined)[] -): T[] { +export function collect(...value: (ReadonlyArray | T | undefined)[]): T[] { const empty: (T | undefined)[] = []; return filterDefined(empty.concat(...value)); } -export function matchPrefix( - prefixCollection: (string | RegExp)[], - name: string -): boolean { +export function matchPrefix(prefixCollection: (string | RegExp)[], name: string): boolean { for (const prefix of prefixCollection) { let regex: RegExp; @@ -102,8 +87,7 @@ export function updateStructMetadata( modifiers: arkts.Es2pandaModifierFlags, hasStateManagementType?: boolean ): arkts.StructInfo { - const metadata: Record = - structInfo.metadata ?? {}; + const metadata: Record = structInfo.metadata ?? {}; metadata[propertyName] = { name: propertyName, properties, diff --git a/arkui-plugins/common/debug.ts b/arkui-plugins/common/debug.ts index 3008ff789..f39940e8f 100644 --- a/arkui-plugins/common/debug.ts +++ b/arkui-plugins/common/debug.ts @@ -33,7 +33,13 @@ function mkDir(filePath: string): void { fs.mkdirSync(filePath); } -export function debugDump(content: string, fileName: string, isInit: boolean, cachePath: string | undefined, programFileName: string): void { +export function debugDump( + content: string, + fileName: string, + isInit: boolean, + cachePath: string | undefined, + programFileName: string +): void { if (!isDebugDump) return; const currentDirectory = process.cwd(); const modifiedFileName = programFileName.replaceAll('.', '_'); @@ -47,9 +53,10 @@ export function debugDump(content: string, fileName: string, isInit: boolean, ca try { if (!isInit && fs.existsSync(filePath)) { const existingContent = fs.readFileSync(filePath, 'utf8'); - const newContent = existingContent &&!existingContent.endsWith('\n') - ? existingContent + '\n' + content - : existingContent + content; + const newContent = + existingContent && !existingContent.endsWith('\n') + ? existingContent + '\n' + content + : existingContent + content; fs.writeFileSync(filePath, newContent, 'utf8'); } else { fs.writeFileSync(filePath, content, 'utf8'); @@ -64,11 +71,6 @@ export function debugLog(message?: any, ...optionalParams: any[]): void { console.log(message, ...optionalParams); } -export function getDumpFileName( - state: number, - prefix: string, - index: number | undefined, - suffix: string -): string { +export function getDumpFileName(state: number, prefix: string, index: number | undefined, suffix: string): string { return `${state}_${prefix}_${index ?? ''}_${suffix}.sts`; } diff --git a/arkui-plugins/common/etsglobal-remover.ts b/arkui-plugins/common/etsglobal-remover.ts index d2936a10a..3d9711799 100644 --- a/arkui-plugins/common/etsglobal-remover.ts +++ b/arkui-plugins/common/etsglobal-remover.ts @@ -13,22 +13,19 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { AbstractVisitor } from "./abstract-visitor" +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor } from './abstract-visitor'; -const ETSGLOBAL = "ETSGLOBAL" +const ETSGLOBAL = 'ETSGLOBAL'; export class EtsglobalRemover extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { if (arkts.isEtsScript(node)) { const keep = node.statements.filter((it) => { - return !(arkts.isClassDeclaration(it) && it.definition?.ident?.name == ETSGLOBAL) - }) - return arkts.factory.updateEtsScript( - node, - keep - ) + return !(arkts.isClassDeclaration(it) && it.definition?.ident?.name == ETSGLOBAL); + }); + return arkts.factory.updateEtsScript(node, keep); } - return node + return node; } } diff --git a/arkui-plugins/common/gensym-generator.ts b/arkui-plugins/common/gensym-generator.ts index aa48a70f3..6e05f109d 100644 --- a/arkui-plugins/common/gensym-generator.ts +++ b/arkui-plugins/common/gensym-generator.ts @@ -13,9 +13,9 @@ * limitations under the License. */ -import { getCommonPath } from "../path" -const common = require(getCommonPath()) -const UniqueId = common.UniqueId +import { getCommonPath } from '../path'; +const common = require(getCommonPath()); +const UniqueId = common.UniqueId; export class GenSymGenerator { // Global for the whole program. @@ -39,7 +39,7 @@ export class GenSymGenerator { sha1Id(callName: string): string { const uniqId = new UniqueId(); - uniqId.addString("gensym uniqid"); + uniqId.addString('gensym uniqid'); uniqId.addString(callName); uniqId.addI32(GenSymGenerator.callCount++); return uniqId.compute().substring(0, 7); @@ -49,14 +49,12 @@ export class GenSymGenerator { return `${GenSymGenerator.callCount++}_${callName}_id`; } - id(callName: string = ""): string { - const positionId = (this.stableForTests) ? - this.stringId(callName) : - this.sha1Id(callName); + id(callName: string = ''): string { + const positionId = this.stableForTests ? this.stringId(callName) : this.sha1Id(callName); const coreceToStr = parseInt(positionId, 16).toString(); // compiler use gensym%%_ but % is illegal before after-check phase return `gensym___${coreceToStr}`; } -} \ No newline at end of file +} diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts index eb110a8bc..f0ad9ccb4 100644 --- a/arkui-plugins/common/plugin-context.ts +++ b/arkui-plugins/common/plugin-context.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; // This is the same plugin-context in the build-system. export class PluginContext { @@ -21,14 +21,14 @@ export class PluginContext { private program: arkts.Program | undefined; private projectConfig: ProjectConfig | undefined; private contextPtr: number | undefined; - + constructor() { this.ast = undefined; this.program = undefined; this.projectConfig = undefined; this.contextPtr = undefined; } - + /** * @deprecated */ @@ -58,11 +58,11 @@ export class PluginContext { } public setProjectConfig(projectConfig: ProjectConfig): void { - throw new Error("do not set projectConfig!"); + throw new Error('do not set projectConfig!'); } public getProjectConfig(): ProjectConfig | undefined { - return this.projectConfig; + return this.projectConfig; } public setContextPtr(ptr: number): void { @@ -75,35 +75,35 @@ export class PluginContext { } export interface ProjectConfig { - bundleName: string, - moduleName: string, - cachePath: string + bundleName: string; + moduleName: string; + cachePath: string; } export type PluginHandlerFunction = () => void; export type PluginHandlerObject = { - order: 'pre' | 'post' | undefined - handler: PluginHandlerFunction + order: 'pre' | 'post' | undefined; + handler: PluginHandlerFunction; }; export type PluginHandler = PluginHandlerFunction | PluginHandlerObject; export interface Plugins { name: string; - afterNew?: PluginHandler, - parsed?: PluginHandler, - scopeInited?: PluginHandler, - checked?: PluginHandler, - lowered?: PluginHandler, - asmGenerated?: PluginHandler, - binGenerated?: PluginHandler, - clean?: PluginHandler, -}; + afterNew?: PluginHandler; + parsed?: PluginHandler; + scopeInited?: PluginHandler; + checked?: PluginHandler; + lowered?: PluginHandler; + asmGenerated?: PluginHandler; + binGenerated?: PluginHandler; + clean?: PluginHandler; +} -export type PluginState = keyof Omit; +export type PluginState = keyof Omit; export type PluginExecutor = { - name: string - handler: PluginHandlerFunction + name: string; + handler: PluginHandlerFunction; }; diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 6d52388c5..08ce2babe 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -14,13 +14,13 @@ */ export const EXTERNAL_SOURCE_PREFIX_NAMES: (string | RegExp)[] = [ - "std", - "escompat", - "security", - "application", - "permissions", - "bundleManager", - "commonEvent", + 'std', + 'escompat', + 'security', + 'application', + 'permissions', + 'bundleManager', + 'commonEvent', /@arkts\..*/, /@ohos\.(?!arkui).*/, /@system\..*/, @@ -28,60 +28,63 @@ export const EXTERNAL_SOURCE_PREFIX_NAMES: (string | RegExp)[] = [ /ability\..*/, ]; -export const ARKUI_COMPONENT_IMPORT_NAME: string = "@ohos.arkui.component"; +export const ARKUI_COMPONENT_IMPORT_NAME: string = '@ohos.arkui.component'; -export const ARKUI_STATEMANAGEMENT_IMPORT_NAME: string = "@ohos.arkui.stateManagement"; +export const ARKUI_STATEMANAGEMENT_IMPORT_NAME: string = '@ohos.arkui.stateManagement'; export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ ARKUI_COMPONENT_IMPORT_NAME, - ARKUI_STATEMANAGEMENT_IMPORT_NAME + ARKUI_STATEMANAGEMENT_IMPORT_NAME, ]; export const IMPORT_SOURCE_MAP: Map> = new Map>([ - ["@ohos.arkui.component", new Set(["$r", "$rawfile", "_r", "_rawfile"])], - ["@ohos.arkui.stateManagement", new Set([ - "State", - "Prop", - "Provide", - "Consume", - "StorageLink", - "StorageProp", - "LocalStorageLink", - "LocalStorageProp", - "Watch", - "ObjectLink", - "StateDecoratedVariable", - "MutableState", - "contextLocalStateOf", - "contextLocal", - "observableProxy", - "SyncedProperty", - "objectLinkState", - "propState", - "AppStorageLinkState", - "StorageLinkState", - "DecoratedV1VariableBase", - "LinkDecoratedVariable", - "PropDecoratedVariable", - "StorageLinkDecoratedVariable", - "StoragePropDecoratedVariable", - "memo", - "__memo_context_type", - "__memo_id_type" - ])] + ['@ohos.arkui.component', new Set(['$r', '$rawfile', '_r', '_rawfile'])], + [ + '@ohos.arkui.stateManagement', + new Set([ + 'State', + 'Prop', + 'Provide', + 'Consume', + 'StorageLink', + 'StorageProp', + 'LocalStorageLink', + 'LocalStorageProp', + 'Watch', + 'ObjectLink', + 'StateDecoratedVariable', + 'MutableState', + 'contextLocalStateOf', + 'contextLocal', + 'observableProxy', + 'SyncedProperty', + 'objectLinkState', + 'propState', + 'AppStorageLinkState', + 'StorageLinkState', + 'DecoratedV1VariableBase', + 'LinkDecoratedVariable', + 'PropDecoratedVariable', + 'StorageLinkDecoratedVariable', + 'StoragePropDecoratedVariable', + 'memo', + '__memo_context_type', + '__memo_id_type', + ]), + ], ]); export const OUTPUT_DEPENDENCY_MAP: Map = new Map([ - ["$r", ["_r"]], - ["$rawfile", ["_rawfile"]], - ["State", ["StateDecoratedVariable"]], - ["Link", ["LinkDecoratedVariable", "DecoratedV1VariableBase"]], - ["Prop", ["PropDecoratedVariable"]], - ["Provide", ["MutableState", "contextLocalStateOf", "observableProxy"]], - ["Consume", ["MutableState", "contextLocal", "observableProxy"]], - ["StorageProp", ["StoragePropDecoratedVariable"]], - ["StorageLink", ["StorageLinkDecoratedVariable"]], - ["LocalStorageLink", ["StorageLinkState", "MutableState", "observableProxy"]], - ["LocalStorageProp", ["StorageLinkState", "MutableState", "observableProxy", "propState"]], - ["ObjectLink", ["objectLinkState", "observableProxy", "SyncedProperty"]] -]); \ No newline at end of file + ['$r', ['_r']], + ['$rawfile', ['_rawfile']], + ['State', ['StateDecoratedVariable']], + ['Link', ['LinkDecoratedVariable', 'DecoratedV1VariableBase']], + ['Prop', ['PropDecoratedVariable']], + ['Provide', ['MutableState', 'contextLocalStateOf', 'observableProxy']], + ['Consume', ['MutableState', 'contextLocal', 'observableProxy']], + ['StorageProp', ['StoragePropDecoratedVariable']], + ['StorageLink', ['StorageLinkDecoratedVariable']], + ['LocalStorageLink', ['StorageLinkState', 'MutableState', 'observableProxy']], + ['LocalStorageProp', ['StorageLinkState', 'MutableState', 'observableProxy', 'propState']], + ['ObjectLink', ['objectLinkState', 'observableProxy', 'SyncedProperty']], +]); diff --git a/arkui-plugins/common/print-visitor.ts b/arkui-plugins/common/print-visitor.ts index 9a48a2085..9f69e250d 100644 --- a/arkui-plugins/common/print-visitor.ts +++ b/arkui-plugins/common/print-visitor.ts @@ -13,22 +13,22 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { AbstractVisitor } from "../common/abstract-visitor"; +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor } from '../common/abstract-visitor'; export class PrintVisitor extends AbstractVisitor { - private result = "" + private result = ''; private printNode(node: arkts.AstNode) { - return `${" ".repeat(4 * this.indentation) + node.constructor.name} ${this.nameIfIdentifier(node)}` + return `${' '.repeat(4 * this.indentation) + node.constructor.name} ${this.nameIfIdentifier(node)}`; } private nameIfIdentifier(node: arkts.AstNode): string { - return arkts.isIdentifier(node) ? `'${node.name}'` : "" + return arkts.isIdentifier(node) ? `'${node.name}'` : ''; } visitor(node: arkts.AstNode): arkts.AstNode { - console.log(this.printNode(node)) - return this.visitEachChild(node) + console.log(this.printNode(node)); + return this.visitEachChild(node); } } diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index b0ada269d..e50bcbe08 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -13,12 +13,12 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { AbstractVisitor, VisitorOptions } from "./abstract-visitor"; -import { matchPrefix } from "./arkts-utils"; -import { debugDump, getDumpFileName } from "./debug"; -import { ARKUI_COMPONENT_IMPORT_NAME } from "./predefines"; -import { PluginContext } from "./plugin-context"; +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor, VisitorOptions } from './abstract-visitor'; +import { matchPrefix } from './arkts-utils'; +import { debugDump, getDumpFileName } from './debug'; +import { ARKUI_COMPONENT_IMPORT_NAME } from './predefines'; +import { PluginContext } from './plugin-context'; export interface ProgramVisitorOptions extends VisitorOptions { pluginName: string; @@ -30,30 +30,30 @@ export interface ProgramVisitorOptions extends VisitorOptions { } export interface ProgramHookConfig { - visitors: AbstractVisitor[], - resetAfter?: arkts.Es2pandaContextState + visitors: AbstractVisitor[]; + resetAfter?: arkts.Es2pandaContextState; } export type ProgramHookLifeCycle = Partial>; export interface ProgramHooks { - external?: ProgramHookLifeCycle, - source?: ProgramHookLifeCycle + external?: ProgramHookLifeCycle; + source?: ProgramHookLifeCycle; } function flattenVisitorsInHooks( - programHooks?: ProgramHooks, + programHooks?: ProgramHooks, resetAfterValue?: arkts.Es2pandaContextState ): AbstractVisitor[] { if (!programHooks) return []; const flatMapInHook = (config: ProgramHookConfig): AbstractVisitor[] => { if (!resetAfterValue) return []; - if (!config.resetAfter || (resetAfterValue !== config.resetAfter)) return []; + if (!config.resetAfter || resetAfterValue !== config.resetAfter) return []; return config.visitors; - } + }; return [ ...Object.values(programHooks.external || {}).flatMap(flatMapInHook), - ...Object.values(programHooks.source || {}).flatMap(flatMapInHook) + ...Object.values(programHooks.source || {}).flatMap(flatMapInHook), ]; } @@ -62,14 +62,14 @@ function sortExternalSources(externalSources: arkts.ExternalSource[]): arkts.Ext const prefix = ARKUI_COMPONENT_IMPORT_NAME; const hasPrefixA = a.getName().startsWith(prefix); const hasPrefixB = b.getName().startsWith(prefix); - + // If both have the prefix, maintain their original order if (hasPrefixA && hasPrefixB) { - return 0; + return 0; } // If neither has the prefix, maintain their original order if (!hasPrefixA && !hasPrefixB) { - return 0; + return 0; } // If only one has the prefix, the one with the prefix comes first return hasPrefixA ? -1 : 1; @@ -87,7 +87,7 @@ export class ProgramVisitor extends AbstractVisitor { constructor(options: ProgramVisitorOptions) { super(options); - this.pluginName = options.pluginName + this.pluginName = options.pluginName; this.state = options.state; this.visitors = options.visitors; this.skipPrefixNames = options.skipPrefixNames ?? []; @@ -112,13 +112,13 @@ export class ProgramVisitor extends AbstractVisitor { if (visited.has(currProgram.peer)) { continue; } - + if (currProgram.peer !== program.peer) { const name: string = this.filenames.get(currProgram.peer)!; - const cachePath: string | undefined = this.pluginContext?.getProjectConfig()?.cachePath; + const cachePath: string | undefined = this.pluginContext?.getProjectConfig()?.cachePath; debugDump( - currProgram.astNode.dumpSrc(), - getDumpFileName(this.state, "ORI", undefined, name), + currProgram.astNode.dumpSrc(), + getDumpFileName(this.state, 'ORI', undefined, name), true, cachePath, program.programFileNameWithExtension @@ -126,7 +126,7 @@ export class ProgramVisitor extends AbstractVisitor { const script = this.visitor(currProgram.astNode, currProgram, name); if (script) { debugDump( - script.dumpSrc(), + script.dumpSrc(), getDumpFileName(this.state, this.pluginName, undefined, name), true, cachePath, @@ -162,11 +162,7 @@ export class ProgramVisitor extends AbstractVisitor { return program; } - visitor( - node: arkts.AstNode, - program?: arkts.Program, - externalSourceName?: string - ): arkts.EtsScript { + visitor(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): arkts.EtsScript { let hook: ProgramHookLifeCycle | undefined; let script: arkts.EtsScript = node as arkts.EtsScript; @@ -193,8 +189,8 @@ export class ProgramVisitor extends AbstractVisitor { arkts.setAllParents(script); if (!transformer.isExternal) { debugDump( - script.dumpSrc(), - getDumpFileName(this.state, this.pluginName, count, transformer.constructor.name), + script.dumpSrc(), + getDumpFileName(this.state, this.pluginName, count, transformer.constructor.name), true, this.pluginContext?.getProjectConfig()?.cachePath, program!.programFileNameWithExtension @@ -216,4 +212,4 @@ export class ProgramVisitor extends AbstractVisitor { return script; } -} \ No newline at end of file +} diff --git a/arkui-plugins/interop-plugins/decl_transformer.ts b/arkui-plugins/interop-plugins/decl_transformer.ts index 2aee8e9f5..57cf9906d 100644 --- a/arkui-plugins/interop-plugins/decl_transformer.ts +++ b/arkui-plugins/interop-plugins/decl_transformer.ts @@ -13,76 +13,77 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; +import * as arkts from '@koalaui/libarkts'; -import { AbstractVisitor } from "../common/abstract-visitor"; +import { AbstractVisitor } from '../common/abstract-visitor'; import { debugLog } from '../common/debug'; export class DeclTransformer extends AbstractVisitor { - constructor(private options?: interop.DeclTransformerOptions) { - super(); - } - - processComponent(node: arkts.StructDeclaration): arkts.ClassDeclaration { - const className = node.definition?.ident?.name; - if (!className) { - throw "Non Empty className expected for Component"; + constructor(private options?: interop.DeclTransformerOptions) { + super(); } - let newDec: arkts.ClassDeclaration = arkts.factory.createClassDeclaration(node.definition); + processComponent(node: arkts.StructDeclaration): arkts.ClassDeclaration { + const className = node.definition?.ident?.name; + if (!className) { + throw 'Non Empty className expected for Component'; + } - const newDefinition = arkts.factory.updateClassDefinition( - newDec.definition!, - newDec.definition?.ident, - undefined, - undefined, - newDec.definition?.implements!, - undefined, - undefined, - node.definition?.body, - newDec.definition?.modifiers!, - arkts.classDefinitionFlags(newDec.definition!) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE - ); + let newDec: arkts.ClassDeclaration = arkts.factory.createClassDeclaration(node.definition); - arkts.factory.updateClassDeclaration(newDec, newDefinition); - newDec.modifiers = node.modifiers; - return newDec; - } + const newDefinition = arkts.factory.updateClassDefinition( + newDec.definition!, + newDec.definition?.ident, + undefined, + undefined, + newDec.definition?.implements!, + undefined, + undefined, + node.definition?.body, + newDec.definition?.modifiers!, + arkts.classDefinitionFlags(newDec.definition!) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - let astNode:arkts.AstNode = beforeChildren; - if (arkts.isEtsScript(astNode)) { - astNode = this.transformImportDecl(astNode); + arkts.factory.updateClassDeclaration(newDec, newDefinition); + newDec.modifiers = node.modifiers; + return newDec; } - const node = this.visitEachChild(astNode); - if (arkts.isStructDeclaration(node)) { - debugLog(`DeclTransformer:before:flag:${arkts.classDefinitionIsFromStructConst(node.definition!)}`); - arkts.classDefinitionSetFromStructModifier(node.definition!); - let newnode = this.processComponent(node); - debugLog(`DeclTransformer:after:flag:${arkts.classDefinitionIsFromStructConst(newnode.definition!)}`); - return newnode; - } - return node; - } + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + let astNode: arkts.AstNode = beforeChildren; + if (arkts.isEtsScript(astNode)) { + astNode = this.transformImportDecl(astNode); + } - transformImportDecl(estNode: arkts.AstNode):arkts.AstNode { - if (!arkts.isEtsScript(estNode)) { - return estNode; + const node = this.visitEachChild(astNode); + if (arkts.isStructDeclaration(node)) { + debugLog(`DeclTransformer:before:flag:${arkts.classDefinitionIsFromStructConst(node.definition!)}`); + arkts.classDefinitionSetFromStructModifier(node.definition!); + let newnode = this.processComponent(node); + debugLog(`DeclTransformer:after:flag:${arkts.classDefinitionIsFromStructConst(newnode.definition!)}`); + return newnode; + } + return node; } - let statements = estNode.statements.filter(node => this.isImportDeclarationNeedFilter(node)) - .map(node => this.updateImportDeclaration(node)); + transformImportDecl(estNode: arkts.AstNode): arkts.AstNode { + if (!arkts.isEtsScript(estNode)) { + return estNode; + } + + let statements = estNode.statements + .filter((node) => this.isImportDeclarationNeedFilter(node)) + .map((node) => this.updateImportDeclaration(node)); - return arkts.factory.updateEtsScript(estNode,statements) - } + return arkts.factory.updateEtsScript(estNode, statements); + } - isImportDeclarationNeedFilter(astNode: arkts.AstNode):boolean { - return !arkts.isETSImportDeclaration(astNode); - } + isImportDeclarationNeedFilter(astNode: arkts.AstNode): boolean { + return !arkts.isETSImportDeclaration(astNode); + } - updateImportDeclaration(astNode: arkts.AstNode):arkts.AstNode { - return astNode; - } + updateImportDeclaration(astNode: arkts.AstNode): arkts.AstNode { + return astNode; + } } diff --git a/arkui-plugins/interop-plugins/emit_transformer.ts b/arkui-plugins/interop-plugins/emit_transformer.ts index dc1b6df03..d68dfbc2f 100644 --- a/arkui-plugins/interop-plugins/emit_transformer.ts +++ b/arkui-plugins/interop-plugins/emit_transformer.ts @@ -13,48 +13,48 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; +import * as arkts from '@koalaui/libarkts'; -import { AbstractVisitor } from "../common/abstract-visitor"; +import { AbstractVisitor } from '../common/abstract-visitor'; import { debugLog } from '../common/debug'; export class EmitTransformer extends AbstractVisitor { - constructor(private options?: interop.EmitTransformerOptions) { - super(); - } - - processComponent(node: arkts.ClassDeclaration): arkts.ClassDeclaration { - const className = node.definition?.ident?.name; - if (!className) { - throw "Non Empty className expected for Component"; + constructor(private options?: interop.EmitTransformerOptions) { + super(); } - const newDefinition = arkts.factory.updateClassDefinition( - node.definition, - node.definition?.ident, - undefined, - undefined, - node.definition?.implements, - undefined, - undefined, - node.definition?.body, - node.definition?.modifiers, - arkts.classDefinitionFlags(node.definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE - ); - - let newDec: arkts.ClassDeclaration = arkts.factory.updateClassDeclaration(node, newDefinition); - - debugLog(`DeclTransformer:checked:struct_ast:${newDefinition.dumpJson()}`); - newDec.modifiers = node.modifiers; - return newDec; - } - - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - const node = this.visitEachChild(beforeChildren); - if (arkts.isClassDeclaration(node) && arkts.classDefinitionIsFromStructConst(node.definition!)) { - return this.processComponent(node); + processComponent(node: arkts.ClassDeclaration): arkts.ClassDeclaration { + const className = node.definition?.ident?.name; + if (!className) { + throw 'Non Empty className expected for Component'; + } + + const newDefinition = arkts.factory.updateClassDefinition( + node.definition, + node.definition?.ident, + undefined, + undefined, + node.definition?.implements, + undefined, + undefined, + node.definition?.body, + node.definition?.modifiers, + arkts.classDefinitionFlags(node.definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); + + let newDec: arkts.ClassDeclaration = arkts.factory.updateClassDeclaration(node, newDefinition); + + debugLog(`DeclTransformer:checked:struct_ast:${newDefinition.dumpJson()}`); + newDec.modifiers = node.modifiers; + return newDec; + } + + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + const node = this.visitEachChild(beforeChildren); + if (arkts.isClassDeclaration(node) && arkts.classDefinitionIsFromStructConst(node.definition!)) { + return this.processComponent(node); + } + return node; } - return node; - } } diff --git a/arkui-plugins/interop-plugins/index.ts b/arkui-plugins/interop-plugins/index.ts index f2c502e43..bac3e903b 100644 --- a/arkui-plugins/interop-plugins/index.ts +++ b/arkui-plugins/interop-plugins/index.ts @@ -16,5 +16,5 @@ import { interopPlugin } from './interop_plugin'; export function interopTransform() { - return interopPlugin; + return interopPlugin; } diff --git a/arkui-plugins/interop-plugins/interop_plugin.ts b/arkui-plugins/interop-plugins/interop_plugin.ts index b998bac8f..e0ef5ddec 100644 --- a/arkui-plugins/interop-plugins/interop_plugin.ts +++ b/arkui-plugins/interop-plugins/interop_plugin.ts @@ -13,74 +13,74 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; +import * as arkts from '@koalaui/libarkts'; import { DeclTransformer } from './decl_transformer'; import { EmitTransformer } from './emit_transformer'; -import { ProgramVisitor } from "../common/program-visitor"; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from "../common/predefines"; +import { ProgramVisitor } from '../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; import { debugLog } from '../common/debug'; export const interopPlugin: interop.Plugin = { - name: 'interop-plugin', - parsed(this: interop.PluginContext) { - debugLog("interopTransform:parsed"); - let node = this.getArkTSAst(); - - if (node) { - debugLog("interopTransform:parsed:before:source: ", node.dumpSrc()); - debugLog("interopTransform:parsed:before:ast: ", node.dumpJson()); - - let script: arkts.EtsScript = node as arkts.EtsScript; - - const declTransformer = new DeclTransformer({ - arkui: "@koalaui.arkts-arkui.StructParse" as interop.TransfromerName - }); - - const programVisitor = new ProgramVisitor({ - pluginName: "decl", - state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, - visitors: [declTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES - }); - - script = programVisitor.visitor(script); - - debugLog("interopTransform:parsed:after:source: ", script.dumpSrc()); - debugLog("interopTransform:parsed:after:ast: ", script.dumpJson()); - - this.setArkTSAst(script); - return script as interop.EtsScript; - } - }, - checked(this: interop.PluginContext) { - debugLog("interopTransform:checked"); - let node = this.getArkTSAst(); - if (node) { - debugLog("interopTransform:checked:before:source: ", node.dumpSrc()); - debugLog("interopTransform:parsed:before:ast: ", node.dumpJson()); - - let script: arkts.EtsScript = node as arkts.EtsScript; - - const emitTransformer = new EmitTransformer({ - arkui: "@koalaui.arkts-arkui.EmitBase" as interop.TransfromerName - }); - - const programVisitor = new ProgramVisitor({ - pluginName: "emit", - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [emitTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES - }); - - // script = programVisitor.visitor(script); - - debugLog("interopTransform:checked:after:source: ", script.dumpSrc()); - debugLog("interopTransform:checked:after:ast: ", script.dumpJson()); - - this.setArkTSAst(script); - return script as interop.EtsScript; - } - } -} + name: 'interop-plugin', + parsed(this: interop.PluginContext) { + debugLog('interopTransform:parsed'); + let node = this.getArkTSAst(); + + if (node) { + debugLog('interopTransform:parsed:before:source: ', node.dumpSrc()); + debugLog('interopTransform:parsed:before:ast: ', node.dumpJson()); + + let script: arkts.EtsScript = node as arkts.EtsScript; + + const declTransformer = new DeclTransformer({ + arkui: '@koalaui.arkts-arkui.StructParse' as interop.TransfromerName, + }); + + const programVisitor = new ProgramVisitor({ + pluginName: 'decl', + state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + visitors: [declTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + }); + + script = programVisitor.visitor(script); + + debugLog('interopTransform:parsed:after:source: ', script.dumpSrc()); + debugLog('interopTransform:parsed:after:ast: ', script.dumpJson()); + + this.setArkTSAst(script); + return script as interop.EtsScript; + } + }, + checked(this: interop.PluginContext) { + debugLog('interopTransform:checked'); + let node = this.getArkTSAst(); + if (node) { + debugLog('interopTransform:checked:before:source: ', node.dumpSrc()); + debugLog('interopTransform:parsed:before:ast: ', node.dumpJson()); + + let script: arkts.EtsScript = node as arkts.EtsScript; + + const emitTransformer = new EmitTransformer({ + arkui: '@koalaui.arkts-arkui.EmitBase' as interop.TransfromerName, + }); + + const programVisitor = new ProgramVisitor({ + pluginName: 'emit', + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [emitTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + }); + + // script = programVisitor.visitor(script); + + debugLog('interopTransform:checked:after:source: ', script.dumpSrc()); + debugLog('interopTransform:checked:after:ast: ', script.dumpJson()); + + this.setArkTSAst(script); + return script as interop.EtsScript; + } + }, +}; diff --git a/arkui-plugins/interop-plugins/types.ts b/arkui-plugins/interop-plugins/types.ts index cefbb302d..49b257dc5 100644 --- a/arkui-plugins/interop-plugins/types.ts +++ b/arkui-plugins/interop-plugins/types.ts @@ -14,43 +14,43 @@ */ namespace interop { - export type NativePointer = number; - - export interface PluginContext { - setArkTSAst(ast: Node): void; - getArkTSAst(): Node | undefined; - setArkTSProgram(program: Node): void; - getArkTSProgram(): Node | undefined; - setProjectConfig(projectConfig: Node): void; - getProjectConfig(): Node | undefined; - } - - export interface ArktsObject { - readonly peer: NativePointer; - } - - export interface Node extends ArktsObject { - get originalPeer(): NativePointer; - set originalPeer(peer: NativePointer); - dumpJson(): string; - dumpSrc(): string; - } - - export interface EtsScript extends Node {} - - export interface Plugin { - name: string, - parsed?(context: PluginContext): EtsScript | undefined; - checked?(context: PluginContext): EtsScript | undefined; - } - - export type TransfromerName = string & {__TransfromerNameBrand: any }; - - export interface EmitTransformerOptions { - arkui: TransfromerName; - } - - export interface DeclTransformerOptions { - arkui: TransfromerName; - } + export type NativePointer = number; + + export interface PluginContext { + setArkTSAst(ast: Node): void; + getArkTSAst(): Node | undefined; + setArkTSProgram(program: Node): void; + getArkTSProgram(): Node | undefined; + setProjectConfig(projectConfig: Node): void; + getProjectConfig(): Node | undefined; + } + + export interface ArktsObject { + readonly peer: NativePointer; + } + + export interface Node extends ArktsObject { + get originalPeer(): NativePointer; + set originalPeer(peer: NativePointer); + dumpJson(): string; + dumpSrc(): string; + } + + export interface EtsScript extends Node {} + + export interface Plugin { + name: string; + parsed?(context: PluginContext): EtsScript | undefined; + checked?(context: PluginContext): EtsScript | undefined; + } + + export type TransfromerName = string & { __TransfromerNameBrand: any }; + + export interface EmitTransformerOptions { + arkui: TransfromerName; + } + + export interface DeclTransformerOptions { + arkui: TransfromerName; + } } diff --git a/arkui-plugins/jest-test.config.ts b/arkui-plugins/jest-test.config.ts index 4b278d2e6..8295964bc 100644 --- a/arkui-plugins/jest-test.config.ts +++ b/arkui-plugins/jest-test.config.ts @@ -16,18 +16,11 @@ export default { testEnvironment: 'node', transform: { - '^.+\\.ts$': [ - 'ts-jest', - { isolatedModules: true } - ] + '^.+\\.ts$': ['ts-jest', { isolatedModules: true }], }, testRegex: './test/ut/.+\\.test\\.ts$', moduleFileExtensions: ['ts', 'js', 'json', 'node'], coverageDirectory: './test/report', - collectCoverageFrom: [ - 'common/**', - 'memo-plugins/**', - 'ui-plugins/**', - ], - verbose: true -} \ No newline at end of file + collectCoverageFrom: ['common/**', 'memo-plugins/**', 'ui-plugins/**'], + verbose: true, +}; diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 004b9496f..330a1296b 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -13,9 +13,9 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { factory } from "./memo-factory" -import { AbstractVisitor, VisitorOptions } from "../common/abstract-visitor" +import * as arkts from '@koalaui/libarkts'; +import { factory } from './memo-factory'; +import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { PositionalIdTracker, castFunctionExpression, @@ -25,16 +25,18 @@ import { hasMemoStableAnnotation, isStandaloneArrowFunction, isVoidType, - removeMemoAnnotation -} from "./utils" -import { ParameterTransformer } from "./parameter-transformer" -import { ReturnTransformer } from "./return-transformer" -import { SignatureTransformer } from "./signature-transformer" + removeMemoAnnotation, +} from './utils'; +import { ParameterTransformer } from './parameter-transformer'; +import { ReturnTransformer } from './return-transformer'; +import { SignatureTransformer } from './signature-transformer'; function mayAddLastReturn(node: arkts.BlockStatement): boolean { - return node.statements.length > 0 && + return ( + node.statements.length > 0 && !arkts.isReturnStatement(node.statements[node.statements.length - 1]) && !arkts.isThrowStatement(node.statements[node.statements.length - 1]) + ); } function updateFunctionBody( @@ -48,59 +50,55 @@ function updateFunctionBody( arkts.VariableDeclaration | undefined, arkts.ReturnStatement | arkts.BlockStatement | undefined, ] { - let returnTypeAnno = (!returnTypeAnnotation ||stableThis) - ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) - : returnTypeAnnotation; - const scopeDeclaration = factory.createScopeDeclaration( - returnTypeAnno, - hash, parameters.length - ) - const memoParameters = parameters.map((name, id) => { return factory.createMemoParameterDeclarator(id, name.identifier.name) }) + let returnTypeAnno = + !returnTypeAnnotation || stableThis + ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + : returnTypeAnnotation; + const scopeDeclaration = factory.createScopeDeclaration(returnTypeAnno, hash, parameters.length); + const memoParameters = parameters.map((name, id) => { + return factory.createMemoParameterDeclarator(id, name.identifier.name); + }); const memoParametersDeclaration = memoParameters.length ? [ - arkts.factory.createVariableDeclaration( - 0, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, - memoParameters, - ) - ] - : [] - const syntheticReturnStatement = factory.createSyntheticReturnStatement(stableThis) - const isVoidValue = isVoidType(returnTypeAnno) - const unchangedCheck = factory.createIfStatementWithSyntheticReturnStatement(syntheticReturnStatement, isVoidValue) + arkts.factory.createVariableDeclaration( + 0, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, + memoParameters + ), + ] + : []; + const syntheticReturnStatement = factory.createSyntheticReturnStatement(stableThis); + const isVoidValue = isVoidType(returnTypeAnno); + const unchangedCheck = factory.createIfStatementWithSyntheticReturnStatement(syntheticReturnStatement, isVoidValue); if (node) { return [ - arkts.factory.updateBlock( - node, - [ - scopeDeclaration, - ...memoParametersDeclaration, - unchangedCheck, - ...node.statements, - ...(mayAddLastReturn(node) ? [arkts.factory.createReturnStatement()] : []), - ] - ), + arkts.factory.updateBlock(node, [ + scopeDeclaration, + ...memoParametersDeclaration, + unchangedCheck, + ...node.statements, + ...(mayAddLastReturn(node) ? [arkts.factory.createReturnStatement()] : []), + ]), memoParametersDeclaration.length ? memoParametersDeclaration[0] : undefined, syntheticReturnStatement, - ] + ]; } else { return [ node, memoParametersDeclaration.length ? memoParametersDeclaration[0] : undefined, syntheticReturnStatement, - ] + ]; } } function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | undefined): boolean { if (!typeAnnotation) return false; if (arkts.isETSFunctionType(typeAnnotation)) { - return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation) + return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation); } else if (arkts.isETSUnionType(typeAnnotation)) { - return typeAnnotation.types.some((type) => ( - arkts.isETSFunctionType(type) - && (hasMemoAnnotation(type) || hasMemoIntrinsicAnnotation(type)) - )); + return typeAnnotation.types.some( + (type) => arkts.isETSFunctionType(type) && (hasMemoAnnotation(type) || hasMemoIntrinsicAnnotation(type)) + ); } return false; } @@ -120,15 +118,15 @@ function updateMemoTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): ar } return it; }) - ) + ); } return typeAnnotation; } type ScopeInfo = { - name?: string, - isMemo: boolean -} + name?: string; + isMemo: boolean; +}; export interface FunctionTransformerOptions extends VisitorOptions { positionalIdTracker: PositionalIdTracker; @@ -144,15 +142,15 @@ export class FunctionTransformer extends AbstractVisitor { private readonly signatureTransformer: SignatureTransformer; constructor(options: FunctionTransformerOptions) { - super(options) - this.positionalIdTracker = options.positionalIdTracker - this.parameterTransformer = options.parameterTransformer - this.returnTransformer = options.returnTransformer - this.signatureTransformer = options.signatureTransformer + super(options); + this.positionalIdTracker = options.positionalIdTracker; + this.parameterTransformer = options.parameterTransformer; + this.returnTransformer = options.returnTransformer; + this.signatureTransformer = options.signatureTransformer; } - private scopes: ScopeInfo[] = [] - private stable: number = 0 + private scopes: ScopeInfo[] = []; + private stable: number = 0; reset() { super.reset(); @@ -165,111 +163,109 @@ export class FunctionTransformer extends AbstractVisitor { enter(node: arkts.AstNode) { if (arkts.isMethodDefinition(node)) { - const name = node.name.name - const isMemo = hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction) - this.scopes.push({ name , isMemo }) + const name = node.name.name; + const isMemo = hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction); + this.scopes.push({ name, isMemo }); } if ( - arkts.isClassProperty(node) - && !!node.key - && arkts.isIdentifier(node.key) - && !!node.value - && arkts.isArrowFunctionExpression(node.value) + arkts.isClassProperty(node) && + !!node.key && + arkts.isIdentifier(node.key) && + !!node.value && + arkts.isArrowFunctionExpression(node.value) ) { const name = node.key.name; let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); isMemo ||= hasMemoAnnotation(node.value) || hasMemoIntrinsicAnnotation(node.value); isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); - this.scopes.push({ name , isMemo }); + this.scopes.push({ name, isMemo }); } if (isStandaloneArrowFunction(node)) { const name = undefined; const isMemo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); - this.scopes.push({ name , isMemo }); + this.scopes.push({ name, isMemo }); } - if ( - arkts.isTSTypeAliasDeclaration(node) - && !!node.id - && !!node.typeAnnotation - ) { + if (arkts.isTSTypeAliasDeclaration(node) && !!node.id && !!node.typeAnnotation) { const name = node.id.name; let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); - this.scopes.push({ name , isMemo }); + this.scopes.push({ name, isMemo }); } if (arkts.isClassDefinition(node)) { if (hasMemoStableAnnotation(node)) { - this.stable++ + this.stable++; } } - return this + return this; } exit(node: arkts.AstNode) { if (arkts.isMethodDefinition(node)) { - this.scopes.pop() + this.scopes.pop(); } if (arkts.isClassDefinition(node)) { if (hasMemoStableAnnotation(node)) { - this.stable-- + this.stable--; } } - return this + return this; } enterAnonymousScope(node: arkts.ScriptFunction) { - const name = undefined - const isMemo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) - this.scopes.push({ name, isMemo }) - return this + const name = undefined; + const isMemo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + this.scopes.push({ name, isMemo }); + return this; } exitAnonymousScope() { - this.scopes.pop() - return this + this.scopes.pop(); + return this; } checkMemoCallInMethod(decl: arkts.MethodDefinition) { if (this.scopes[this.scopes.length - 1].isMemo == false) { if (this.scopes[this.scopes.length - 1].name) { - console.error(`Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${this.scopes[this.scopes.length - 1].name}`) - throw "Invalid @memo usage" + console.error( + `Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${this.scopes[this.scopes.length - 1].name}` + ); + throw 'Invalid @memo usage'; } else { - console.error(`Attempt to call @memo-method ${decl.name.name} from anonymous non-@memo-method`) - throw "Invalid @memo usage" + console.error(`Attempt to call @memo-method ${decl.name.name} from anonymous non-@memo-method`); + throw 'Invalid @memo usage'; } } - return this + return this; } checkMemoCallInFunction() { if (this.scopes[this.scopes.length - 1]?.isMemo == false) { - console.error(`Attempt to call @memo-function`) - throw "Invalid @memo usage" + console.error(`Attempt to call @memo-function`); + throw 'Invalid @memo usage'; } - return this + return this; } - updateScriptFunction( - scriptFunction: arkts.ScriptFunction, - name: string = "", - ): arkts.ScriptFunction { - const isStableThis = this.stable > 0 && scriptFunction.returnTypeAnnotation !== undefined && arkts.isTSThisType(scriptFunction.returnTypeAnnotation) + updateScriptFunction(scriptFunction: arkts.ScriptFunction, name: string = ''): arkts.ScriptFunction { + const isStableThis = + this.stable > 0 && + scriptFunction.returnTypeAnnotation !== undefined && + arkts.isTSThisType(scriptFunction.returnTypeAnnotation); const [body, memoParametersDeclaration, syntheticReturnStatement] = updateFunctionBody( scriptFunction.body as arkts.BlockStatement, castParameters(scriptFunction.params), scriptFunction.returnTypeAnnotation, isStableThis, - this.positionalIdTracker.id(name), - ) + this.positionalIdTracker.id(name) + ); const afterParameterTransformer = this.parameterTransformer .withParameters(scriptFunction.params as arkts.ETSParameterExpression[]) .skip(memoParametersDeclaration) - .visitor(body) + .visitor(body); const afterReturnTransformer = this.returnTransformer .skip(syntheticReturnStatement) .rewriteThis(this.stable > 0) - .visitor(afterParameterTransformer) + .visitor(afterParameterTransformer); const updateScriptFunction = arkts.factory.updateScriptFunction( scriptFunction, afterReturnTransformer, @@ -277,25 +273,25 @@ export class FunctionTransformer extends AbstractVisitor { scriptFunction.typeParams, [ ...factory.createHiddenParameters(), - ...scriptFunction.params // we handle function params with signature-transformer + ...scriptFunction.params, // we handle function params with signature-transformer ], scriptFunction.returnTypeAnnotation, scriptFunction.hasReceiver ), scriptFunction.flags, scriptFunction.modifiers - ) + ); return updateScriptFunction; } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - this.enter(beforeChildren) - const node = this.visitEachChild(beforeChildren) - this.exit(beforeChildren) + this.enter(beforeChildren); + const node = this.visitEachChild(beforeChildren); + this.exit(beforeChildren); if (arkts.isMethodDefinition(node)) { if ( - node.scriptFunction.body - && (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) + node.scriptFunction.body && + (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) ) { return arkts.factory.updateMethodDefinition( node, @@ -303,10 +299,7 @@ export class FunctionTransformer extends AbstractVisitor { node.name, arkts.factory.createFunctionExpression( this.signatureTransformer.visitor( - removeMemoAnnotation( - this.updateScriptFunction(node.scriptFunction, node.name.name) - ) - + removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)) ) ), node.modifiers, @@ -318,42 +311,44 @@ export class FunctionTransformer extends AbstractVisitor { node, node.kind, node.name, - arkts.factory.createFunctionExpression( - this.signatureTransformer.visitor(node.scriptFunction), - ), + arkts.factory.createFunctionExpression(this.signatureTransformer.visitor(node.scriptFunction)), node.modifiers, false ); } if (arkts.isCallExpression(node)) { - const expr = node.expression - const decl = arkts.getDecl(expr) - if (decl && arkts.isMethodDefinition(decl) && (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction))) { - this.checkMemoCallInMethod(decl) + const expr = node.expression; + const decl = arkts.getDecl(expr); + if ( + decl && + arkts.isMethodDefinition(decl) && + (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction)) + ) { + this.checkMemoCallInMethod(decl); const updatedArguments = node.arguments.map((it, index) => { - const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type + const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type; if (type && arkts.isETSFunctionType(type)) { if ( - !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) - && !hasMemoIntrinsicAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) + !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) && + !hasMemoIntrinsicAnnotation( + decl.scriptFunction.params[index] as arkts.ETSParameterExpression + ) ) { - return it //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) + return it; //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) } if (arkts.isArrowFunctionExpression(it)) { - this.enterAnonymousScope(it.scriptFunction) - const res = this.updateScriptFunction(it.scriptFunction) - this.exitAnonymousScope() - return arkts.factory.updateArrowFunction(it, res) + this.enterAnonymousScope(it.scriptFunction); + const res = this.updateScriptFunction(it.scriptFunction); + this.exitAnonymousScope(); + return arkts.factory.updateArrowFunction(it, res); } } - return it - }) - return arkts.factory.updateCallExpression( - node, - node.expression, - undefined, - [...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), ...updatedArguments] - ) + return it; + }); + return arkts.factory.updateCallExpression(node, node.expression, undefined, [ + ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), + ...updatedArguments, + ]); } if (isStandaloneArrowFunction(node.expression)) { const scope = this.scopes[this.scopes.length - 1]; @@ -362,7 +357,10 @@ export class FunctionTransformer extends AbstractVisitor { this.checkMemoCallInFunction(); this.enterAnonymousScope(node.expression.scriptFunction); - const res = this.updateScriptFunction(node.expression.scriptFunction, node.expression.scriptFunction.id?.name); + const res = this.updateScriptFunction( + node.expression.scriptFunction, + node.expression.scriptFunction.id?.name + ); this.exitAnonymousScope(); return arkts.factory.updateCallExpression( @@ -370,15 +368,15 @@ export class FunctionTransformer extends AbstractVisitor { arkts.factory.updateArrowFunction(node.expression, res), node.typeArguments, [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...node.arguments] - ) + ); } } - if( - arkts.isClassProperty(node) - && !!node.key - && arkts.isIdentifier(node.key) - && !!node.value - && arkts.isArrowFunctionExpression(node.value) + if ( + arkts.isClassProperty(node) && + !!node.key && + arkts.isIdentifier(node.key) && + !!node.value && + arkts.isArrowFunctionExpression(node.value) ) { const scope = this.scopes[this.scopes.length - 1]; if (!scope || !scope.isMemo || scope.name !== node.key?.name) return node; @@ -389,12 +387,9 @@ export class FunctionTransformer extends AbstractVisitor { this.exitAnonymousScope(); let typeAnnotation: arkts.TypeNode | undefined; - if ( - !!node.typeAnnotation - && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation)) - ) { + if (!!node.typeAnnotation && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { console.error(`ETSFunctionType or ETSUnionType expected for @memo-property ${node.key.name}`); - throw "Invalid @memo usage"; + throw 'Invalid @memo usage'; } return arkts.factory.updateClassProperty( @@ -414,15 +409,10 @@ export class FunctionTransformer extends AbstractVisitor { let typeAnnotation: arkts.TypeNode | undefined; if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { console.error(`ETSFunctionType or ETSUnionType expected for @memo-type ${node.id!.name}`); - throw "Invalid @memo usage"; + throw 'Invalid @memo usage'; } - return arkts.factory.updateTSTypeAliasDeclaration( - node, - node.id, - node.typeParams, - typeAnnotation - ); + return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation); } if (isStandaloneArrowFunction(node)) { const scope = this.scopes[this.scopes.length - 1]; @@ -433,11 +423,8 @@ export class FunctionTransformer extends AbstractVisitor { const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); this.exitAnonymousScope(); - return arkts.factory.updateArrowFunction( - node, - res - ); + return arkts.factory.updateArrowFunction(node, res); } - return node + return node; } -} \ No newline at end of file +} diff --git a/arkui-plugins/memo-plugins/import-transformer.ts b/arkui-plugins/memo-plugins/import-transformer.ts index 65e6adc4c..ac8adfaf0 100644 --- a/arkui-plugins/memo-plugins/import-transformer.ts +++ b/arkui-plugins/memo-plugins/import-transformer.ts @@ -13,19 +13,16 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { AbstractVisitor } from "../common/abstract-visitor" -import { factory } from "./memo-factory" +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor } from '../common/abstract-visitor'; +import { factory } from './memo-factory'; export class ImportTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { if (node instanceof arkts.EtsScript) { factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext?.program); - return arkts.factory.updateEtsScript( - node, - node.statements - ) + return arkts.factory.updateEtsScript(node, node.statements); } - return node + return node; } } diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index 369d12990..58f785dbd 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -13,42 +13,50 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { Plugins, PluginContext } from "../common/plugin-context"; -import { FunctionTransformer } from "./function-transformer"; -import { PositionalIdTracker } from "./utils"; -import { ReturnTransformer } from "./return-transformer"; -import { ParameterTransformer } from "./parameter-transformer"; -import { ProgramVisitor } from "../common/program-visitor"; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from "../common/predefines"; -import { debugDump, debugLog, getDumpFileName } from "../common/debug" -import { SignatureTransformer } from "./signature-transformer"; +import * as arkts from '@koalaui/libarkts'; +import { Plugins, PluginContext } from '../common/plugin-context'; +import { FunctionTransformer } from './function-transformer'; +import { PositionalIdTracker } from './utils'; +import { ReturnTransformer } from './return-transformer'; +import { ParameterTransformer } from './parameter-transformer'; +import { ProgramVisitor } from '../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; +import { debugDump, debugLog, getDumpFileName } from '../common/debug'; +import { SignatureTransformer } from './signature-transformer'; export function unmemoizeTransform(): Plugins { return { name: 'memo-plugin', checked(this: PluginContext) { - console.log("[MEMO PLUGIN] AFTER CHECKED ENTER"); + console.log('[MEMO PLUGIN] AFTER CHECKED ENTER'); const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; let script = program.astNode; - debugLog("[BEFORE MEMO SCRIPT] script: ", script.dumpSrc()); + debugLog('[BEFORE MEMO SCRIPT] script: ', script.dumpSrc()); const cachePath: string | undefined = this.getProjectConfig()?.cachePath; - debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 5, "MEMO_AfterCheck_Begin"), true, cachePath, program.programFileNameWithExtension); + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 5, 'MEMO_AfterCheck_Begin'), + true, + cachePath, + program.programFileNameWithExtension + ); - arkts.Performance.getInstance().createEvent("memo-checked"); + arkts.Performance.getInstance().createEvent('memo-checked'); const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); - const parameterTransformer = new ParameterTransformer({ positionalIdTracker }); + const parameterTransformer = new ParameterTransformer({ + positionalIdTracker, + }); const returnTransformer = new ReturnTransformer(); const signatureTransformer = new SignatureTransformer(); const functionTransformer = new FunctionTransformer({ - positionalIdTracker, - parameterTransformer, + positionalIdTracker, + parameterTransformer, returnTransformer, - signatureTransformer + signatureTransformer, }); const programVisitor = new ProgramVisitor({ @@ -62,25 +70,31 @@ export function unmemoizeTransform(): Plugins { program = programVisitor.programVisitor(program); script = program.astNode; - arkts.Performance.getInstance().stopEvent("memo-checked", true); + arkts.Performance.getInstance().stopEvent('memo-checked', true); debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); - debugDump(script.dumpSrc(), getDumpFileName(0, "SRC", 6, "MEMO_AfterCheck_End"), true, cachePath, program.programFileNameWithExtension); + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 6, 'MEMO_AfterCheck_End'), + true, + cachePath, + program.programFileNameWithExtension + ); - arkts.Performance.getInstance().createEvent("memo-recheck"); + arkts.Performance.getInstance().createEvent('memo-recheck'); arkts.recheckSubtree(script); - arkts.Performance.getInstance().stopEvent("memo-recheck", true); + arkts.Performance.getInstance().stopEvent('memo-recheck', true); arkts.Performance.getInstance().clearAllEvents(); this.setArkTSAst(script); - console.log("[MEMO PLUGIN] AFTER CHECKED EXIT"); + console.log('[MEMO PLUGIN] AFTER CHECKED EXIT'); return script; } - console.log("[MEMO PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM"); + console.log('[MEMO PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); }, clean() { arkts.arktsGlobal.clearContext(); - } - } -} \ No newline at end of file + }, + }; +} diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index 135d64fdf..9cef81c70 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -13,22 +13,22 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { RuntimeNames } from "./utils" +import * as arkts from '@koalaui/libarkts'; +import { RuntimeNames } from './utils'; export class factory { // Importing static createContextTypeImportSpecifier(): arkts.ImportSpecifier { return arkts.factory.createImportSpecifier( arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE), - arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE), - ) + arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE) + ); } static createIdTypeImportSpecifier(): arkts.ImportSpecifier { return arkts.factory.createImportSpecifier( arkts.factory.createIdentifier(RuntimeNames.ID_TYPE), - arkts.factory.createIdentifier(RuntimeNames.ID_TYPE), - ) + arkts.factory.createIdentifier(RuntimeNames.ID_TYPE) + ); } // TODO: Currently, import declaration can only be inserted at after-parsed stage. static createContextTypesImportDeclaration(program?: arkts.Program): void { @@ -38,15 +38,12 @@ export class factory { // ); const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, - [ - factory.createContextTypeImportSpecifier(), - factory.createIdTypeImportSpecifier() - ], + [factory.createContextTypeImportSpecifier(), factory.createIdTypeImportSpecifier()], arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE - ) + ); // Insert this import at the top of the script's statements. if (!program) { - throw Error("Failed to insert import: Transformer has no program"); + throw Error('Failed to insert import: Transformer has no program'); } arkts.importDeclarationInsert(importDecl, program); return; @@ -58,28 +55,25 @@ export class factory { arkts.factory.createIdentifier( RuntimeNames.CONTEXT, arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE) - ) + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE)) ) ), undefined - ) + ); } static createIdParameter(): arkts.ETSParameterExpression { return arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(RuntimeNames.ID, + arkts.factory.createIdentifier( + RuntimeNames.ID, arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(RuntimeNames.ID_TYPE) - ) + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.ID_TYPE)) ) ), undefined - ) + ); } static createHiddenParameters(): arkts.ETSParameterExpression[] { - return [factory.createContextParameter(), factory.createIdParameter()] + return [factory.createContextParameter(), factory.createIdParameter()]; } static updateFunctionTypeWithMemoParameters(type: arkts.ETSFunctionType): arkts.ETSFunctionType { return arkts.factory.updateFunctionType( @@ -88,30 +82,30 @@ export class factory { undefined, [...factory.createHiddenParameters(), ...type.params], type.returnType, - false, + false ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - ) + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + ); } // Arguments static createContextArgument(): arkts.AstNode { - return arkts.factory.createIdentifier(RuntimeNames.CONTEXT) + return arkts.factory.createIdentifier(RuntimeNames.CONTEXT); } static createIdArgument(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.AstNode { return arkts.factory.createBinaryExpression( arkts.factory.createIdentifier(RuntimeNames.ID), hash, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS, - ) + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS + ); } static createHiddenArguments(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.AstNode[] { - return [factory.createContextArgument(), factory.createIdArgument(hash)] + return [factory.createContextArgument(), factory.createIdArgument(hash)]; } // Memo parameters static createMemoParameterIdentifier(name: string): arkts.Identifier { - return arkts.factory.createIdentifier(`${RuntimeNames.PARAMETER}_${name}`) + return arkts.factory.createIdentifier(`${RuntimeNames.PARAMETER}_${name}`); } static createMemoParameterDeclarator(id: number, name: string): arkts.VariableDeclarator { return arkts.factory.createVariableDeclarator( @@ -126,12 +120,9 @@ export class factory { false ), undefined, - [ - arkts.factory.createNumericLiteral(id), - arkts.factory.createIdentifier(name), - ], + [arkts.factory.createNumericLiteral(id), arkts.factory.createIdentifier(name)] ) - ) + ); } static createMemoParameterAccess(name: string): arkts.MemberExpression { return arkts.factory.createMemberExpression( @@ -139,48 +130,63 @@ export class factory { arkts.factory.createIdentifier(RuntimeNames.VALUE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_GETTER, false, - false, - ) + false + ); } - static createMemoParameterAccessMemoWithScope(name: string, hash: arkts.NumberLiteral | arkts.StringLiteral, passArgs?: arkts.AstNode[]): arkts.CallExpression { - const updatedArgs = passArgs ? passArgs : [] + static createMemoParameterAccessMemoWithScope( + name: string, + hash: arkts.NumberLiteral | arkts.StringLiteral, + passArgs?: arkts.AstNode[] + ): arkts.CallExpression { + const updatedArgs = passArgs ? passArgs : []; return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( factory.createMemoParameterIdentifier(name), arkts.factory.createIdentifier(RuntimeNames.VALUE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_GETTER, false, - false, + false ), undefined, - [...factory.createHiddenArguments(hash), ...updatedArgs], - ) + [...factory.createHiddenArguments(hash), ...updatedArgs] + ); } - static createMemoParameterAccessMemoWithoutScope(name: string, hash: arkts.NumberLiteral | arkts.StringLiteral, passArgs?: arkts.AstNode[]): arkts.CallExpression { - const updatedArgs = passArgs ? passArgs : [] - return arkts.factory.createCallExpression( - arkts.factory.createIdentifier(name), - undefined, - [...factory.createHiddenArguments(hash), ...updatedArgs], - ) + static createMemoParameterAccessMemoWithoutScope( + name: string, + hash: arkts.NumberLiteral | arkts.StringLiteral, + passArgs?: arkts.AstNode[] + ): arkts.CallExpression { + const updatedArgs = passArgs ? passArgs : []; + return arkts.factory.createCallExpression(arkts.factory.createIdentifier(name), undefined, [ + ...factory.createHiddenArguments(hash), + ...updatedArgs, + ]); } - static createMemoParameterAccessCall(name: string, hash: arkts.NumberLiteral | arkts.StringLiteral, passArgs?: arkts.AstNode[]): arkts.CallExpression { - const updatedArgs = passArgs ? passArgs : [] + static createMemoParameterAccessCall( + name: string, + hash: arkts.NumberLiteral | arkts.StringLiteral, + passArgs?: arkts.AstNode[] + ): arkts.CallExpression { + const updatedArgs = passArgs ? passArgs : []; return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( factory.createMemoParameterIdentifier(name), arkts.factory.createIdentifier(RuntimeNames.VALUE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_GETTER, false, - false, + false ), undefined, - [...updatedArgs], - ) + [...updatedArgs] + ); } // Recache - static createScopeDeclaration(returnTypeAnnotation: arkts.TypeNode | undefined, hash: arkts.NumberLiteral | arkts.StringLiteral, cnt: number): arkts.VariableDeclaration { + static createScopeDeclaration( + returnTypeAnnotation: arkts.TypeNode | undefined, + hash: arkts.NumberLiteral | arkts.StringLiteral, + cnt: number + ): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( 0, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, @@ -196,15 +202,14 @@ export class factory { false, false ), - returnTypeAnnotation ? [returnTypeAnnotation] : [arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID)], - [ - factory.createIdArgument(hash), - arkts.factory.createNumericLiteral(cnt) - ], + returnTypeAnnotation + ? [returnTypeAnnotation] + : [arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID)], + [factory.createIdArgument(hash), arkts.factory.createNumericLiteral(cnt)] ) - ) + ), ] - ) + ); } static createRecacheCall(arg?: arkts.AstNode): arkts.CallExpression { return arkts.factory.createCallExpression( @@ -216,18 +221,14 @@ export class factory { false ), undefined, - arg ? [arg] : undefined, - ) + arg ? [arg] : undefined + ); } static createReturnThis(): arkts.BlockStatement { return arkts.factory.createBlock([ - arkts.factory.createExpressionStatement( - factory.createRecacheCall() - ), - arkts.factory.createReturnStatement( - arkts.factory.createThisExpression() - ) - ]) + arkts.factory.createExpressionStatement(factory.createRecacheCall()), + arkts.factory.createReturnStatement(arkts.factory.createThisExpression()), + ]); } static createSyntheticReturnStatement(stableThis: boolean): arkts.ReturnStatement | arkts.BlockStatement { if (!stableThis) { @@ -237,9 +238,9 @@ export class factory { arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, false, - false, - ), - ) + false + ) + ); } return arkts.factory.createBlock([ arkts.factory.createMemberExpression( @@ -247,12 +248,10 @@ export class factory { arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, false, - false, + false ), - arkts.factory.createReturnStatement( - arkts.factory.createThisExpression() - ) - ]) + arkts.factory.createReturnStatement(arkts.factory.createThisExpression()), + ]); } static createIfStatementWithSyntheticReturnStatement( syntheticReturnStatement: arkts.ReturnStatement | arkts.BlockStatement, @@ -261,11 +260,9 @@ export class factory { let returnStatement = syntheticReturnStatement; if (isVoidValue && arkts.isReturnStatement(syntheticReturnStatement)) { returnStatement = arkts.factory.createBlock([ - arkts.factory.createExpressionStatement( - syntheticReturnStatement.argument! - ), - arkts.factory.createReturnStatement() - ]) + arkts.factory.createExpressionStatement(syntheticReturnStatement.argument!), + arkts.factory.createReturnStatement(), + ]); } return arkts.factory.createIfStatement( arkts.factory.createMemberExpression( @@ -273,31 +270,27 @@ export class factory { arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE_OK), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, false, - false, + false ), - returnStatement, - ) + returnStatement + ); } // Compute static createLambdaWrapper(node: arkts.Expression): arkts.ArrowFunctionExpression { return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( - arkts.factory.createBlock([ - arkts.factory.createReturnStatement(node) - ]), - arkts.factory.createFunctionSignature( - undefined, - [], - undefined, - false, - ), + arkts.factory.createBlock([arkts.factory.createReturnStatement(node)]), + arkts.factory.createFunctionSignature(undefined, [], undefined, false), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE ) - ) + ); } - static createComputeExpression(hash: arkts.NumberLiteral | arkts.StringLiteral, node: arkts.Expression): arkts.CallExpression { + static createComputeExpression( + hash: arkts.NumberLiteral | arkts.StringLiteral, + node: arkts.Expression + ): arkts.CallExpression { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier(RuntimeNames.CONTEXT), @@ -308,6 +301,6 @@ export class factory { ), undefined, [factory.createIdArgument(hash), factory.createLambdaWrapper(node)] - ) + ); } } diff --git a/arkui-plugins/memo-plugins/memo-transformer.ts b/arkui-plugins/memo-plugins/memo-transformer.ts index a0c0191e9..430148fc2 100644 --- a/arkui-plugins/memo-plugins/memo-transformer.ts +++ b/arkui-plugins/memo-plugins/memo-transformer.ts @@ -13,39 +13,38 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { FunctionTransformer } from "./function-transformer" -import { PositionalIdTracker } from "./utils" -import { factory } from "./memo-factory" -import { ReturnTransformer } from "./return-transformer" -import { ParameterTransformer } from "./parameter-transformer" -import { EtsglobalRemover } from "../common/etsglobal-remover" -import { SignatureTransformer } from "./signature-transformer" +import * as arkts from '@koalaui/libarkts'; +import { FunctionTransformer } from './function-transformer'; +import { PositionalIdTracker } from './utils'; +import { factory } from './memo-factory'; +import { ReturnTransformer } from './return-transformer'; +import { ParameterTransformer } from './parameter-transformer'; +import { EtsglobalRemover } from '../common/etsglobal-remover'; +import { SignatureTransformer } from './signature-transformer'; export interface TransformerOptions { - trace?: boolean, - removeEtsglobal?: boolean + trace?: boolean; + removeEtsglobal?: boolean; } -export default function memoTransformer( - userPluginOptions?: TransformerOptions -) { +export default function memoTransformer(userPluginOptions?: TransformerOptions) { return (node0: arkts.EtsScript) => { - const node = (userPluginOptions?.removeEtsglobal ? new EtsglobalRemover().visitor(node0) : node0) as arkts.EtsScript - const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false) + const node = ( + userPluginOptions?.removeEtsglobal ? new EtsglobalRemover().visitor(node0) : node0 + ) as arkts.EtsScript; + const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); const parameterTransformer = new ParameterTransformer({ - positionalIdTracker - }) - const returnTransformer = new ReturnTransformer() - const signatureTransformer = new SignatureTransformer() - const functionTransformer = new FunctionTransformer({ positionalIdTracker, parameterTransformer, returnTransformer, signatureTransformer }) + positionalIdTracker, + }); + const returnTransformer = new ReturnTransformer(); + const signatureTransformer = new SignatureTransformer(); + const functionTransformer = new FunctionTransformer({ + positionalIdTracker, + parameterTransformer, + returnTransformer, + signatureTransformer, + }); factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext?.program); - return functionTransformer.visitor( - arkts.factory.updateEtsScript( - node, - node.statements - ) - ) - } + return functionTransformer.visitor(arkts.factory.updateEtsScript(node, node.statements)); + }; } - diff --git a/arkui-plugins/memo-plugins/parameter-transformer.ts b/arkui-plugins/memo-plugins/parameter-transformer.ts index a734ca525..757e45f77 100644 --- a/arkui-plugins/memo-plugins/parameter-transformer.ts +++ b/arkui-plugins/memo-plugins/parameter-transformer.ts @@ -12,30 +12,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { factory } from "./memo-factory" -import { AbstractVisitor, VisitorOptions } from "../common/abstract-visitor" -import { - hasMemoAnnotation, - hasMemoIntrinsicAnnotation, - isMemoParametersDeclaration, - PositionalIdTracker -} from "./utils" +import { factory } from './memo-factory'; +import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; +import { + hasMemoAnnotation, + hasMemoIntrinsicAnnotation, + isMemoParametersDeclaration, + PositionalIdTracker, +} from './utils'; export interface ParameterTransformerOptions extends VisitorOptions { - positionalIdTracker: PositionalIdTracker + positionalIdTracker: PositionalIdTracker; } export class ParameterTransformer extends AbstractVisitor { - private rewriteIdentifiers?: Map arkts.MemberExpression | arkts.Identifier> - private rewriteCalls?: Map arkts.CallExpression> - private skipNode?: arkts.VariableDeclaration - private readonly positionalIdTracker: PositionalIdTracker + private rewriteIdentifiers?: Map arkts.MemberExpression | arkts.Identifier>; + private rewriteCalls?: Map arkts.CallExpression>; + private skipNode?: arkts.VariableDeclaration; + private readonly positionalIdTracker: PositionalIdTracker; constructor(options: ParameterTransformerOptions) { - super(options) - this.positionalIdTracker = options.positionalIdTracker + super(options); + this.positionalIdTracker = options.positionalIdTracker; } reset(): void { @@ -46,32 +46,56 @@ export class ParameterTransformer extends AbstractVisitor { } withParameters(parameters: arkts.ETSParameterExpression[]): ParameterTransformer { - this.rewriteCalls = new Map(parameters.filter(it => it.type && (arkts.isETSFunctionType(it.type) || arkts.isETSUnionType(it.type))).map((it) => { - return [it.peer, (passArgs: arkts.AstNode[]) => { - if (hasMemoAnnotation(it) || hasMemoIntrinsicAnnotation(it)) { - if (it.type && arkts.isETSFunctionType(it.type) && !it.optional) { - return factory.createMemoParameterAccessMemoWithScope(it.identifier.name, this.positionalIdTracker?.id(), passArgs) - } else { - return factory.createMemoParameterAccessMemoWithoutScope(it.identifier.name, this.positionalIdTracker?.id(), passArgs) - } - } - return factory.createMemoParameterAccessCall(it.identifier.name, this.positionalIdTracker?.id(), passArgs) - }] - })) - this.rewriteIdentifiers = new Map(parameters.map((it) => { - return [it.peer, () => { - if ((it.type && arkts.isETSFunctionType(it.type)) || it.optional) { - return arkts.factory.createIdentifier(it.identifier.name) - } - return factory.createMemoParameterAccess(it.identifier.name) - }] - })) - return this + this.rewriteCalls = new Map( + parameters + .filter((it) => it.type && (arkts.isETSFunctionType(it.type) || arkts.isETSUnionType(it.type))) + .map((it) => { + return [ + it.peer, + (passArgs: arkts.AstNode[]) => { + if (hasMemoAnnotation(it) || hasMemoIntrinsicAnnotation(it)) { + if (it.type && arkts.isETSFunctionType(it.type) && !it.optional) { + return factory.createMemoParameterAccessMemoWithScope( + it.identifier.name, + this.positionalIdTracker?.id(), + passArgs + ); + } else { + return factory.createMemoParameterAccessMemoWithoutScope( + it.identifier.name, + this.positionalIdTracker?.id(), + passArgs + ); + } + } + return factory.createMemoParameterAccessCall( + it.identifier.name, + this.positionalIdTracker?.id(), + passArgs + ); + }, + ]; + }) + ); + this.rewriteIdentifiers = new Map( + parameters.map((it) => { + return [ + it.peer, + () => { + if ((it.type && arkts.isETSFunctionType(it.type)) || it.optional) { + return arkts.factory.createIdentifier(it.identifier.name); + } + return factory.createMemoParameterAccess(it.identifier.name); + }, + ]; + }) + ); + return this; } skip(memoParametersDeclaration?: arkts.VariableDeclaration): ParameterTransformer { - this.skipNode = memoParametersDeclaration - return this + this.skipNode = memoParametersDeclaration; + return this; } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { @@ -81,28 +105,26 @@ export class ParameterTransformer extends AbstractVisitor { return beforeChildren; } if (/* beforeChildren === this.skipNode */ isMemoParametersDeclaration(beforeChildren)) { - return beforeChildren + return beforeChildren; } if (arkts.isCallExpression(beforeChildren)) { if (arkts.isIdentifier(beforeChildren.expression)) { - const decl = arkts.getDecl(beforeChildren.expression) + const decl = arkts.getDecl(beforeChildren.expression); if (decl && arkts.isEtsParameterExpression(decl) && this.rewriteCalls?.has(decl.peer)) { - return this.rewriteCalls.get(decl.peer)!( - beforeChildren.arguments.map((it) => this.visitor(it)) - ) + return this.rewriteCalls.get(decl.peer)!(beforeChildren.arguments.map((it) => this.visitor(it))); } } } - const node = this.visitEachChild(beforeChildren) + const node = this.visitEachChild(beforeChildren); if (arkts.isIdentifier(node)) { - const decl = arkts.getDecl(node) - if ((decl && arkts.isEtsParameterExpression(decl)) && this.rewriteIdentifiers?.has(decl.peer)) { - const res = this.rewriteIdentifiers.get(decl.peer)!() + const decl = arkts.getDecl(node); + if (decl && arkts.isEtsParameterExpression(decl) && this.rewriteIdentifiers?.has(decl.peer)) { + const res = this.rewriteIdentifiers.get(decl.peer)!(); if (arkts.isMemberExpression(res)) { - return res + return res; } } } - return node + return node; } } diff --git a/arkui-plugins/memo-plugins/return-transformer.ts b/arkui-plugins/memo-plugins/return-transformer.ts index 01998194f..9714d7eb0 100644 --- a/arkui-plugins/memo-plugins/return-transformer.ts +++ b/arkui-plugins/memo-plugins/return-transformer.ts @@ -13,14 +13,14 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { factory } from "./memo-factory" -import { AbstractVisitor } from "../common/abstract-visitor" -import { isSyntheticReturnStatement } from "./utils" +import * as arkts from '@koalaui/libarkts'; +import { factory } from './memo-factory'; +import { AbstractVisitor } from '../common/abstract-visitor'; +import { isSyntheticReturnStatement } from './utils'; export class ReturnTransformer extends AbstractVisitor { - private skipNode?: arkts.ReturnStatement | arkts.BlockStatement - private stableThis: boolean = false + private skipNode?: arkts.ReturnStatement | arkts.BlockStatement; + private stableThis: boolean = false; reset() { super.reset(); @@ -29,13 +29,13 @@ export class ReturnTransformer extends AbstractVisitor { } skip(syntheticReturnStatement?: arkts.ReturnStatement | arkts.BlockStatement): ReturnTransformer { - this.skipNode = syntheticReturnStatement - return this + this.skipNode = syntheticReturnStatement; + return this; } rewriteThis(stableThis: boolean): ReturnTransformer { - this.stableThis = stableThis - return this + this.stableThis = stableThis; + return this; } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { @@ -45,20 +45,18 @@ export class ReturnTransformer extends AbstractVisitor { return beforeChildren; } if (arkts.isScriptFunction(beforeChildren)) { - return beforeChildren + return beforeChildren; } - const node = this.visitEachChild(beforeChildren) + const node = this.visitEachChild(beforeChildren); if (arkts.isReturnStatement(node)) { if (this.stableThis && node.argument && arkts.isThisExpression(node.argument)) { - return factory.createReturnThis() + return factory.createReturnThis(); } return arkts.factory.createBlock([ - arkts.factory.createExpressionStatement( - factory.createRecacheCall(node.argument) - ), - node + arkts.factory.createExpressionStatement(factory.createRecacheCall(node.argument)), + node, ]); } - return node + return node; } -} \ No newline at end of file +} diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index 258f28f11..985d57d5c 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -13,13 +13,13 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { factory } from "./memo-factory" -import { hasMemoAnnotation, hasMemoIntrinsicAnnotation } from "./utils" -import { AbstractVisitor } from "../common/abstract-visitor" +import * as arkts from '@koalaui/libarkts'; +import { factory } from './memo-factory'; +import { hasMemoAnnotation, hasMemoIntrinsicAnnotation } from './utils'; +import { AbstractVisitor } from '../common/abstract-visitor'; export class SignatureTransformer extends AbstractVisitor { - public modified = false + public modified = false; reset(): void { super.reset(); @@ -28,65 +28,67 @@ export class SignatureTransformer extends AbstractVisitor { visitor(node: T, applyMemo: boolean = false): T { if (arkts.isScriptFunction(node)) { - const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo + const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo; if (memo) { - this.modified = true + this.modified = true; } return arkts.factory.updateScriptFunction( node, node.body, arkts.factory.createFunctionSignature( node.typeParams, - [...(memo ? factory.createHiddenParameters() : []), ...node.params.map(it => this.visitor(it))], + [...(memo ? factory.createHiddenParameters() : []), ...node.params.map((it) => this.visitor(it))], node.returnTypeAnnotation ? this.visitor(node.returnTypeAnnotation) - : memo ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) : undefined, - node.hasReceiver, + : memo + ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + : undefined, + node.hasReceiver ), node.flags, node.modifiers - ) as any as T + ) as any as T; } if (arkts.isEtsParameterExpression(node)) { - const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) + const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); if (!node.type) { if (memo) { - console.error(`@memo parameter ${node.identifier.name} without type annotatation`) - throw "Invalid @memo usage" + console.error(`@memo parameter ${node.identifier.name} without type annotatation`); + throw 'Invalid @memo usage'; } - return node + return node; } - node.type = this.visitor(node.type, memo) - return node as any as T + node.type = this.visitor(node.type, memo); + return node as any as T; } if (arkts.isETSFunctionType(node)) { - const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo + const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo; if (memo) { - this.modified = true + this.modified = true; } return arkts.factory.updateFunctionType( node, arkts.factory.createFunctionSignature( undefined, - [...(memo ? factory.createHiddenParameters() : []), ...node.params.map(it => this.visitor(it))], + [...(memo ? factory.createHiddenParameters() : []), ...node.params.map((it) => this.visitor(it))], this.visitor(node.returnType!), - false, + false ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - ) as any as T + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + ) as any as T; } if (arkts.isETSUnionType(node)) { return arkts.factory.updateUnionType( node, - node.types.map(it => this.visitor(it, applyMemo)) - ) as any as T + node.types.map((it) => this.visitor(it, applyMemo)) + ) as any as T; } if (arkts.isETSUndefinedType(node)) { - return node as any as T + return node as any as T; } if (applyMemo) { - throw "Invalid @memo usage" + throw 'Invalid @memo usage'; } - return node + return node; } -} \ No newline at end of file +} diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index 91fd89356..ae4541254 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -12,83 +12,81 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { getCommonPath } from "../path" -const common = require(getCommonPath()) -const UniqueId = common.UniqueId +import * as arkts from '@koalaui/libarkts'; +import { getCommonPath } from '../path'; +const common = require(getCommonPath()); +const UniqueId = common.UniqueId; export enum RuntimeNames { - __CONTEXT = "__context", - __ID = "__id", - ANNOTATION = "memo", - ANNOTATION_INTRINSIC = "memo_intrinsic", - ANNOTATION_STABLE = "memo_stable", - COMPUTE = "compute", - CONTEXT = "__memo_context", - CONTEXT_TYPE = "__memo_context_type", - CONTEXT_TYPE_DEFAULT_IMPORT = "@ohos.arkui.StateManagement.runtime", - ID = "__memo_id", - ID_TYPE = "__memo_id_type", - INTERNAL_PARAMETER_STATE = "param", - INTERNAL_SCOPE = "scope", - INTERNAL_VALUE = "cached", - INTERNAL_VALUE_NEW = "recache", - INTERNAL_VALUE_OK = "unchanged", - PARAMETER = "__memo_parameter", - SCOPE = "__memo_scope", - VALUE = "value", + __CONTEXT = '__context', + __ID = '__id', + ANNOTATION = 'memo', + ANNOTATION_INTRINSIC = 'memo_intrinsic', + ANNOTATION_STABLE = 'memo_stable', + COMPUTE = 'compute', + CONTEXT = '__memo_context', + CONTEXT_TYPE = '__memo_context_type', + CONTEXT_TYPE_DEFAULT_IMPORT = '@ohos.arkui.StateManagement.runtime', + ID = '__memo_id', + ID_TYPE = '__memo_id_type', + INTERNAL_PARAMETER_STATE = 'param', + INTERNAL_SCOPE = 'scope', + INTERNAL_VALUE = 'cached', + INTERNAL_VALUE_NEW = 'recache', + INTERNAL_VALUE_OK = 'unchanged', + PARAMETER = '__memo_parameter', + SCOPE = '__memo_scope', + VALUE = 'value', } function baseName(path: string): string { - return path.replace(/^.*\/(.*)$/, "$1") + return path.replace(/^.*\/(.*)$/, '$1'); } export class PositionalIdTracker { // Global for the whole program. - static callCount: number = 0 + static callCount: number = 0; // Set `stable` to true if you want to have more predictable values. // For example for tests. // Don't use it in production! - constructor(public filename: string, public stableForTests: boolean = false) { - if (stableForTests) PositionalIdTracker.callCount = 0 + constructor( + public filename: string, + public stableForTests: boolean = false + ) { + if (stableForTests) PositionalIdTracker.callCount = 0; } sha1Id(callName: string, fileName: string): string { - const uniqId = new UniqueId() - uniqId.addString("memo call uniqid") - uniqId.addString(fileName) - uniqId.addString(callName) - uniqId.addI32(PositionalIdTracker.callCount++) - return uniqId.compute().substring(0, 7) + const uniqId = new UniqueId(); + uniqId.addString('memo call uniqid'); + uniqId.addString(fileName); + uniqId.addString(callName); + uniqId.addI32(PositionalIdTracker.callCount++); + return uniqId.compute().substring(0, 7); } stringId(callName: string, fileName: string): string { - return `${PositionalIdTracker.callCount++}_${callName}_id_DIRNAME/${fileName}` + return `${PositionalIdTracker.callCount++}_${callName}_id_DIRNAME/${fileName}`; } - id(callName: string = ""): arkts.NumberLiteral | arkts.StringLiteral { - - const fileName = this.stableForTests ? - baseName(this.filename) : - this.filename - - const positionId = (this.stableForTests) ? - this.stringId(callName, fileName) : - this.sha1Id(callName, fileName) + id(callName: string = ''): arkts.NumberLiteral | arkts.StringLiteral { + const fileName = this.stableForTests ? baseName(this.filename) : this.filename; + const positionId = this.stableForTests ? this.stringId(callName, fileName) : this.sha1Id(callName, fileName); return this.stableForTests ? arkts.factory.createStringLiteral(positionId) - : arkts.factory.createNumericLiteral(parseInt(positionId, 16)) + : arkts.factory.createNumericLiteral(parseInt(positionId, 16)); } } export function isMemoAnnotation(node: arkts.AnnotationUsage, memoName: RuntimeNames) { - return node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === memoName + return node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === memoName; } -export type MemoAstNode = arkts.ScriptFunction +export type MemoAstNode = + | arkts.ScriptFunction | arkts.ETSParameterExpression | arkts.ClassProperty | arkts.TSTypeAliasDeclaration @@ -96,26 +94,25 @@ export type MemoAstNode = arkts.ScriptFunction | arkts.ArrowFunctionExpression; export function hasMemoAnnotation(node: T): boolean { - return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION)) + return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION)); } export function hasMemoIntrinsicAnnotation(node: T): boolean { - return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC)) + return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC)); } export function hasMemoStableAnnotation(node: arkts.ClassDefinition) { - return node.annotations.some((it) => - it.expr !== undefined && arkts.isIdentifier(it.expr) && it.expr.name === RuntimeNames.ANNOTATION_STABLE - ) + return node.annotations.some( + (it) => it.expr !== undefined && arkts.isIdentifier(it.expr) && it.expr.name === RuntimeNames.ANNOTATION_STABLE + ); } export function removeMemoAnnotation(node: T): T { const newAnnotations: arkts.AnnotationUsage[] = node.annotations.filter( - (it) => ( - !isMemoAnnotation(it, RuntimeNames.ANNOTATION) - && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC) - && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) - ) + (it) => + !isMemoAnnotation(it, RuntimeNames.ANNOTATION) && + !isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC) && + !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) ); if (arkts.isEtsParameterExpression(node)) { node.annotations = newAnnotations; @@ -130,13 +127,15 @@ export function removeMemoAnnotation(node: T): T { */ export function isSyntheticReturnStatement(node: arkts.AstNode) { return ( - arkts.isReturnStatement(node) && - node.argument && arkts.isMemberExpression(node.argument) && - arkts.isIdentifier(node.argument.object) && - node.argument.object.name === RuntimeNames.SCOPE && - arkts.isIdentifier(node.argument.property) && - node.argument.property.name === RuntimeNames.INTERNAL_VALUE - ) || arkts.isBlockStatement(node) + (arkts.isReturnStatement(node) && + node.argument && + arkts.isMemberExpression(node.argument) && + arkts.isIdentifier(node.argument.object) && + node.argument.object.name === RuntimeNames.SCOPE && + arkts.isIdentifier(node.argument.property) && + node.argument.property.name === RuntimeNames.INTERNAL_VALUE) || + arkts.isBlockStatement(node) + ); } /** @@ -144,33 +143,35 @@ export function isSyntheticReturnStatement(node: arkts.AstNode) { * @deprecated */ export function isMemoParametersDeclaration(node: arkts.AstNode) { - return arkts.isVariableDeclaration(node) && + return ( + arkts.isVariableDeclaration(node) && node.declarators.every((it) => it.name.name.startsWith(RuntimeNames.PARAMETER)) + ); } /** * TODO: change this to TypeNodeGetType to check void type */ export function isVoidType(typeNode: arkts.TypeNode | undefined) { - return typeNode?.dumpSrc() === "void" + return typeNode?.dumpSrc() === 'void'; } /** * es2panda API is weird here - * + * * @deprecated */ export function castParameters(params: readonly arkts.Expression[]): arkts.ETSParameterExpression[] { - return params as arkts.ETSParameterExpression[] + return params as arkts.ETSParameterExpression[]; } /** * es2panda API is weird here - * + * * @deprecated */ export function castFunctionExpression(value: arkts.Expression | undefined): arkts.FunctionExpression { - return value as unknown as arkts.FunctionExpression + return value as unknown as arkts.FunctionExpression; } export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.ArrowFunctionExpression { @@ -179,8 +180,5 @@ export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.Ar // handling anonymous arrow function call if (arkts.isCallExpression(node.parent) && node.parent.expression.peer === node.peer) return true; - return ( - !arkts.isClassProperty(node.parent) - && !(arkts.isCallExpression(node.parent) && node.parent.expression) - ) -} \ No newline at end of file + return !arkts.isClassProperty(node.parent) && !(arkts.isCallExpression(node.parent) && node.parent.expression); +} diff --git a/arkui-plugins/path.ts b/arkui-plugins/path.ts index 6b8a714e8..a8646fcbf 100644 --- a/arkui-plugins/path.ts +++ b/arkui-plugins/path.ts @@ -33,29 +33,29 @@ function findMatchingFile(currentPath: string, targetFileName1: string, targetFi } current = parentPath; } - throw new Error("ui-plugins not found.") + throw new Error('ui-plugins not found.'); } function findRootDir() { - const plugins = findMatchingFile(__dirname, UI_PLUGINS, ARKUI_PLUGINS); + const plugins = findMatchingFile(__dirname, UI_PLUGINS, ARKUI_PLUGINS); if (plugins === null) { - throw ("error") + throw 'error'; } - return plugins + return plugins; } export function getArktsPath() { - return path.join(findRootDir(), 'koala-wrapper','./build/lib/arkts-api/index.js') + return path.join(findRootDir(), 'koala-wrapper', './build/lib/arkts-api/index.js'); } export function getInteropPath() { - return path.join(findRootDir(), 'koala-wrapper/koalaui/interop', "./dist/lib/src/interop/index.js") + return path.join(findRootDir(), 'koala-wrapper/koalaui/interop', './dist/lib/src/interop/index.js'); } export function getCommonPath() { - return path.join(findRootDir(), 'koala-wrapper/koalaui/common', "./dist/lib/src/index.js") + return path.join(findRootDir(), 'koala-wrapper/koalaui/common', './dist/lib/src/index.js'); } export function getCompatPath() { - return path.join(findRootDir(), 'koala-wrapper/koalaui/compat', "./dist/src/index.js") + return path.join(findRootDir(), 'koala-wrapper/koalaui/compat', './dist/src/index.js'); } diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index 55babf966..7091e7d52 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -13,34 +13,38 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { PluginTestContext, PluginTester } from "../../utils/plugin-tester"; -import { annotation } from "../../../common/arkts-utils"; +import * as arkts from '@koalaui/libarkts'; +import { PluginTestContext, PluginTester } from '../../utils/plugin-tester'; +import { annotation } from '../../../common/arkts-utils'; -const pluginTester = new PluginTester("test arkts-utils"); +const pluginTester = new PluginTester('test arkts-utils'); function testAnnotation(this: PluginTestContext): void { - const anno: arkts.AnnotationUsage = annotation("State"); + const anno: arkts.AnnotationUsage = annotation('State'); expect(arkts.isAnnotationUsage(anno)).toBeTruthy(); - expect(anno.dumpSrc()).toBe("@State()"); + expect(anno.dumpSrc()).toBe('@State()'); } pluginTester.run( - "annotation", + 'annotation', [], { parsed: [testAnnotation], - checked: [testAnnotation] + checked: [testAnnotation], }, { - stopAfter: "checked" + stopAfter: 'checked', }, { - beforeEach: [() => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }], - afterEach: [() => { - jest.spyOn(console, 'warn').mockRestore(); - }] + beforeEach: [ + () => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }, + ], + afterEach: [ + () => { + jest.spyOn(console, 'warn').mockRestore(); + }, + ], } ); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts index ba73b8157..0b4e71c2d 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts @@ -13,17 +13,17 @@ * limitations under the License. */ -import * as path from "path"; -import * as arkts from "@koalaui/libarkts"; -import { PluginTestContext, PluginTester } from "../../../utils/plugin-tester"; -import { mockBuildConfig } from "../../../utils/artkts-config"; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; -import { parseDumpSrc } from "../../../utils/parse-string"; -import { PluginContext, Plugins } from "../../../../common/plugin-context"; -import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; -import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer"; +import * as path from 'path'; +import * as arkts from '@koalaui/libarkts'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { PluginContext, Plugins } from '../../../../common/plugin-context'; +import { ComponentTransformer } from '../../../../ui-plugins/component-transformer'; +import { BuilderLambdaTransformer } from '../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer'; -const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda"); +const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda'); const instantiateTransform: Plugins = { name: 'instantiate', @@ -32,9 +32,9 @@ const instantiateTransform: Plugins = { if (program) { let script: arkts.EtsScript = program.astNode; - const componentTransformer = new ComponentTransformer( - { arkui: "@koalaui.arkts-arkui.StructBase" } - ); + const componentTransformer = new ComponentTransformer({ + arkui: '@koalaui.arkts-arkui.StructBase', + }); script = componentTransformer.visitor(script) as arkts.EtsScript; arkts.setAllParents(script); return script; @@ -50,10 +50,10 @@ const instantiateTransform: Plugins = { arkts.setAllParents(script); return script; } - } + }, }; -const pluginTester = new PluginTester("test build-lambda transformer"); +const pluginTester = new PluginTester('test build-lambda transformer'); // Test single-content instantiateImpl transformation function testSingleContent(this: PluginTestContext): void { @@ -100,35 +100,34 @@ interface __Options_MyStateSample { `; expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); -}; +} pluginTester.run( - "transform $_instantiate for single component content", + 'transform $_instantiate for single component content', [instantiateTransform], { 'checked:instantiate': [testSingleContent], }, { - stopAfter: "checked", + stopAfter: 'checked', buildConfig: { ...mockBuildConfig(), compileFiles: [ - path.resolve( - getRootPath(), - MOCK_ENTRY_DIR_PATH, - "builder-lambda", - "instantiate-content.ets" - ) + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda', 'instantiate-content.ets'), ], - moduleRootPath - } + moduleRootPath, + }, }, { - beforeEach: [() => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }], - afterEach: [() => { - jest.spyOn(console, 'warn').mockRestore(); - }] + beforeEach: [ + () => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }, + ], + afterEach: [ + () => { + jest.spyOn(console, 'warn').mockRestore(); + }, + ], } ); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts index 1279685ab..34c169437 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts @@ -13,17 +13,17 @@ * limitations under the License. */ -import * as path from "path"; -import * as arkts from "@koalaui/libarkts"; -import { PluginTestContext, PluginTester } from "../../../utils/plugin-tester"; -import { mockBuildConfig } from "../../../utils/artkts-config"; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; -import { parseDumpSrc } from "../../../utils/parse-string"; -import { PluginContext, Plugins } from "../../../../common/plugin-context"; -import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; -import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer"; - -const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda"); +import * as path from 'path'; +import * as arkts from '@koalaui/libarkts'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { PluginContext, Plugins } from '../../../../common/plugin-context'; +import { ComponentTransformer } from '../../../../ui-plugins/component-transformer'; +import { BuilderLambdaTransformer } from '../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer'; + +const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda'); const instantiateTransform: Plugins = { name: 'instantiate', @@ -32,9 +32,9 @@ const instantiateTransform: Plugins = { if (program) { let script: arkts.EtsScript = program.astNode; - const componentTransformer = new ComponentTransformer( - { arkui: "@koalaui.arkts-arkui.StructBase" } - ); + const componentTransformer = new ComponentTransformer({ + arkui: '@koalaui.arkts-arkui.StructBase', + }); script = componentTransformer.visitor(script) as arkts.EtsScript; arkts.setAllParents(script); return script; @@ -50,10 +50,10 @@ const instantiateTransform: Plugins = { arkts.setAllParents(script); return script; } - } + }, }; -const pluginTester = new PluginTester("test build-lambda transformer"); +const pluginTester = new PluginTester('test build-lambda transformer'); // Test multi-content instantiateImpl transformation function testMultiContent(this: PluginTestContext): void { @@ -107,36 +107,34 @@ interface __Options_MyStateSample { `; expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); -}; +} pluginTester.run( - "transform $_instantiate for multiple component contents", + 'transform $_instantiate for multiple component contents', [instantiateTransform], { 'checked:instantiate': [testMultiContent], }, { - stopAfter: "checked", + stopAfter: 'checked', buildConfig: { ...mockBuildConfig(), compileFiles: [ - path.resolve( - getRootPath(), - MOCK_ENTRY_DIR_PATH, - "builder-lambda", - "instantiate-multi-content.ets" - ) + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda', 'instantiate-multi-content.ets'), ], - moduleRootPath - } + moduleRootPath, + }, }, { - beforeEach: [() => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }], - afterEach: [() => { - jest.spyOn(console, 'warn').mockRestore(); - }] + beforeEach: [ + () => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }, + ], + afterEach: [ + () => { + jest.spyOn(console, 'warn').mockRestore(); + }, + ], } ); - diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts index af9f56b59..3a54f332b 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts @@ -13,21 +13,19 @@ * limitations under the License. */ -import * as path from "path"; -import * as arkts from "@koalaui/libarkts"; -import { PluginTestContext, PluginTester } from "../../../utils/plugin-tester"; -import { BuildConfig, mockBuildConfig } from "../../../utils/artkts-config"; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../../utils/path-config"; -import { parseDumpSrc } from "../../../utils/parse-string"; -import { PluginContext, Plugins } from "../../../../common/plugin-context"; -import { ComponentTransformer } from "../../../../ui-plugins/component-transformer"; -import { BuilderLambdaTransformer } from "../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer"; +import * as path from 'path'; +import * as arkts from '@koalaui/libarkts'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { PluginContext, Plugins } from '../../../../common/plugin-context'; +import { ComponentTransformer } from '../../../../ui-plugins/component-transformer'; +import { BuilderLambdaTransformer } from '../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer'; const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda", "instantiate.ets") -]; -buildConfig.moduleRootPath = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "builder-lambda"); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda', 'instantiate.ets')]; +buildConfig.moduleRootPath = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda'); const instantiateTransform: Plugins = { name: 'instantiate', @@ -36,9 +34,9 @@ const instantiateTransform: Plugins = { if (program) { let script: arkts.EtsScript = program.astNode; - const componentTransformer = new ComponentTransformer( - { arkui: "@koalaui.arkts-arkui.StructBase" } - ); + const componentTransformer = new ComponentTransformer({ + arkui: '@koalaui.arkts-arkui.StructBase', + }); script = componentTransformer.visitor(script) as arkts.EtsScript; arkts.setAllParents(script); return script; @@ -55,10 +53,10 @@ const instantiateTransform: Plugins = { arkts.setAllParents(script); return script; } - } + }, }; -const pluginTester = new PluginTester("test build-lambda transformer", buildConfig); +const pluginTester = new PluginTester('test build-lambda transformer', buildConfig); function testInstantiateImpl(this: PluginTestContext): void { const script: arkts.EtsScript = this.script as arkts.EtsScript; @@ -99,20 +97,24 @@ interface __Options_MyStateSample { } pluginTester.run( - "transform $_instantiate for a single component", + 'transform $_instantiate for a single component', [instantiateTransform], { 'checked:instantiate': [testInstantiateImpl], }, { - stopAfter: "checked" + stopAfter: 'checked', }, { - beforeEach: [() => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }], - afterEach: [() => { - jest.spyOn(console, 'warn').mockRestore(); - }] + beforeEach: [ + () => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }, + ], + afterEach: [ + () => { + jest.spyOn(console, 'warn').mockRestore(); + }, + ], } ); diff --git a/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts b/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts index 8074a2c50..8cac48c6f 100644 --- a/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts @@ -13,19 +13,17 @@ * limitations under the License. */ -import * as path from "path"; -import * as arkts from "@koalaui/libarkts"; -import { PluginTestContext, PluginTester } from "../../utils/plugin-tester"; -import { BuildConfig, mockBuildConfig } from "../../utils/artkts-config"; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from "../../utils/path-config"; -import { parseDumpSrc } from "../../utils/parse-string"; -import { PluginContext, Plugins } from "../../../common/plugin-context"; -import { ComponentTransformer } from "../../../ui-plugins/component-transformer"; +import * as path from 'path'; +import * as arkts from '@koalaui/libarkts'; +import { PluginTestContext, PluginTester } from '../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../utils/path-config'; +import { parseDumpSrc } from '../../utils/parse-string'; +import { PluginContext, Plugins } from '../../../common/plugin-context'; +import { ComponentTransformer } from '../../../ui-plugins/component-transformer'; const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, "struct-to-class.ets") -]; +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'struct-to-class.ets')]; const componentTransform: Plugins = { name: 'component', @@ -34,17 +32,17 @@ const componentTransform: Plugins = { if (program) { let script: arkts.EtsScript = program.astNode; - const componentTransformer = new ComponentTransformer( - { arkui: "@koalaui.arkts-arkui.StructBase" } - ); + const componentTransformer = new ComponentTransformer({ + arkui: '@koalaui.arkts-arkui.StructBase', + }); script = componentTransformer.visitor(script) as arkts.EtsScript; arkts.setAllParents(script); return script; } - } -} + }, +}; -const pluginTester = new PluginTester("test component transformer", buildConfig); +const pluginTester = new PluginTester('test component transformer', buildConfig); function testComponentTransformer(this: PluginTestContext): void { const script: arkts.EtsScript = this.script as arkts.EtsScript; @@ -67,23 +65,27 @@ interface __Options_MyStateSample { `; expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); -}; +} pluginTester.run( - "transform struct to class", + 'transform struct to class', [componentTransform], { 'parsed:component': [testComponentTransformer], }, { - stopAfter: "parsed" + stopAfter: 'parsed', }, { - beforeEach: [() => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }], - afterEach: [() => { - jest.spyOn(console, 'warn').mockRestore(); - }] + beforeEach: [ + () => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }, + ], + afterEach: [ + () => { + jest.spyOn(console, 'warn').mockRestore(); + }, + ], } ); diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index 66f346cfb..db63f0e4b 100644 --- a/arkui-plugins/test/utils/artkts-config.ts +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -13,69 +13,69 @@ * limitations under the License. */ -import * as fs from "fs"; -import * as path from "path"; -import { +import * as fs from 'fs'; +import * as path from 'path'; +import { ABC_SUFFIX, ARKTS_CONFIG_FILE_PATH, changeFileExtension, ensurePathExists, getFileName, getPandaSDKPath, - getRootPath, - MOCK_ENTRY_DIR_PATH, - MOCK_ENTRY_FILE_NAME, - MOCK_LOCAL_SDK_DIR_PATH, - MOCK_OUTPUT_CACHE_PATH, + getRootPath, + MOCK_ENTRY_DIR_PATH, + MOCK_ENTRY_FILE_NAME, + MOCK_LOCAL_SDK_DIR_PATH, + MOCK_OUTPUT_CACHE_PATH, MOCK_OUTPUT_DIR_PATH, MOCK_OUTPUT_FILE_NAME, PANDA_SDK_STDLIB_PATH, RUNTIME_API_PATH, STDLIB_ESCOMPAT_PATH, STDLIB_PATH, - STDLIB_STD_PATH -} from "./path-config"; + STDLIB_STD_PATH, +} from './path-config'; export interface ArkTSConfigObject { compilerOptions: { - package: string, - baseUrl: string, + package: string; + baseUrl: string; paths: Record; dependencies: string[] | undefined; entry: string; - } + }; } export interface CompileFileInfo { - fileName: string, - filePath: string, - dependentFiles: string[], - abcFilePath: string, - arktsConfigFile: string, - stdLibPath: string + fileName: string; + filePath: string; + dependentFiles: string[]; + abcFilePath: string; + arktsConfigFile: string; + stdLibPath: string; } export interface ModuleInfo { - isMainModule: boolean, - packageName: string, - moduleRootPath: string, - sourceRoots: string[], - entryFile: string, - arktsConfigFile: string, - compileFileInfos: CompileFileInfo[], - dependencies?: string[] + isMainModule: boolean; + packageName: string; + moduleRootPath: string; + sourceRoots: string[]; + entryFile: string; + arktsConfigFile: string; + compileFileInfos: CompileFileInfo[]; + dependencies?: string[]; } export interface DependentModule { - packageName: string, - moduleName: string, - moduleType: string, - modulePath: string, - sourceRoots: string[], - entryFile: string + packageName: string; + moduleName: string; + moduleType: string; + modulePath: string; + sourceRoots: string[]; + entryFile: string; } -export type ModuleType = "har" | string; // TODO: module type unclear +export type ModuleType = 'har' | string; // TODO: module type unclear export interface DependentModule { packageName: string; @@ -116,12 +116,12 @@ export interface ArktsConfigBuilder { } function writeArkTSConfigFile( - moduleInfo: ModuleInfo, - pathSection: Record, + moduleInfo: ModuleInfo, + pathSection: Record, dependenciesSection: string[] ): void { if (!moduleInfo.sourceRoots || moduleInfo.sourceRoots.length == 0) { - throw new Error("Write Arkts config: does not have sourceRoots."); + throw new Error('Write Arkts config: does not have sourceRoots.'); } const baseUrl: string = path.resolve(moduleInfo.moduleRootPath, moduleInfo.sourceRoots[0]); @@ -132,18 +132,15 @@ function writeArkTSConfigFile( baseUrl: baseUrl, paths: pathSection, dependencies: dependenciesSection.length === 0 ? undefined : dependenciesSection, - entry: moduleInfo.entryFile - } + entry: moduleInfo.entryFile, + }, }; ensurePathExists(moduleInfo.arktsConfigFile); fs.writeFileSync(moduleInfo.arktsConfigFile, JSON.stringify(arktsConfig, null, 2), 'utf-8'); } -function getDependentModules( - moduleInfo: ModuleInfo, - moduleInfoMap: Map -): Map { +function getDependentModules(moduleInfo: ModuleInfo, moduleInfoMap: Map): Map { if (moduleInfo.isMainModule) { return moduleInfoMap; } @@ -179,10 +176,8 @@ function traverse(currentDir: string, pathSection: Record) { function mockBuildConfig(): BuildConfig { return { - packageName: "mock", - compileFiles: [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MOCK_ENTRY_FILE_NAME) - ], + packageName: 'mock', + compileFiles: [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MOCK_ENTRY_FILE_NAME)], loaderOutPath: path.resolve(getRootPath(), MOCK_OUTPUT_DIR_PATH), cachePath: path.resolve(getRootPath(), MOCK_OUTPUT_CACHE_PATH), pandaSdkPath: getPandaSDKPath(), @@ -191,14 +186,14 @@ function mockBuildConfig(): BuildConfig { moduleRootPath: path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH), dependentModuleList: [ { - packageName: "@koalaui/runtime", - moduleName: "@koalaui/runtime", - moduleType: "har", + packageName: '@koalaui/runtime', + moduleName: '@koalaui/runtime', + moduleType: 'har', modulePath: path.resolve(getRootPath(), RUNTIME_API_PATH), - sourceRoots: ["./"], - entryFile: "index.sts" - } - ] + sourceRoots: ['./'], + entryFile: 'index.sts', + }, + ], }; } @@ -240,7 +235,7 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { private generateModuleInfos(): void { if (!this.packageName || !this.moduleRootPath || !this.sourceRoots) { - throw new Error("Main module: packageName, moduleRootPath, and sourceRoots are required"); + throw new Error('Main module: packageName, moduleRootPath, and sourceRoots are required'); } const mainModuleInfo: ModuleInfo = { isMainModule: true, @@ -249,14 +244,12 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { sourceRoots: this.sourceRoots, entryFile: '', arktsConfigFile: path.resolve(this.cacheDir, this.packageName, ARKTS_CONFIG_FILE_PATH), - compileFileInfos: [] - } + compileFileInfos: [], + }; this.moduleInfos.set(this.moduleRootPath, mainModuleInfo); this.dependentModuleList.forEach((module: DependentModule) => { if (!module.packageName || !module.modulePath || !module.sourceRoots || !module.entryFile) { - throw new Error( - "Dependent module: packageName, modulePath, sourceRoots, and entryFile are required" - ); + throw new Error('Dependent module: packageName, modulePath, sourceRoots, and entryFile are required'); } const moduleInfo: ModuleInfo = { isMainModule: false, @@ -265,52 +258,49 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { sourceRoots: module.sourceRoots, entryFile: module.entryFile, arktsConfigFile: path.resolve(this.cacheDir, module.packageName, ARKTS_CONFIG_FILE_PATH), - compileFileInfos: [] - } + compileFileInfos: [], + }; this.moduleInfos.set(module.modulePath, moduleInfo); }); this.entryFiles.forEach((file: string) => { const _file = path.resolve(file); for (const [modulePath, moduleInfo] of this.moduleInfos) { - if (_file.startsWith(modulePath)) { - const filePathFromModuleRoot: string = path.relative(modulePath, _file); - const filePathInCache: string = path.join( - this.cacheDir, moduleInfo.packageName, filePathFromModuleRoot); - const abcFilePath: string = path.resolve(changeFileExtension(filePathInCache, ABC_SUFFIX)); - - const fileInfo: CompileFileInfo = { - fileName: getFileName(_file), - filePath: _file, - dependentFiles: [], - abcFilePath: abcFilePath, - arktsConfigFile: moduleInfo.arktsConfigFile, - stdLibPath: path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_PATH) - }; - moduleInfo.compileFileInfos.push(fileInfo); - return; - } + if (_file.startsWith(modulePath)) { + const filePathFromModuleRoot: string = path.relative(modulePath, _file); + const filePathInCache: string = path.join( + this.cacheDir, + moduleInfo.packageName, + filePathFromModuleRoot + ); + const abcFilePath: string = path.resolve(changeFileExtension(filePathInCache, ABC_SUFFIX)); + + const fileInfo: CompileFileInfo = { + fileName: getFileName(_file), + filePath: _file, + dependentFiles: [], + abcFilePath: abcFilePath, + arktsConfigFile: moduleInfo.arktsConfigFile, + stdLibPath: path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_PATH), + }; + moduleInfo.compileFileInfos.push(fileInfo); + return; + } } - throw new Error("Entry File does not belong to any module in moduleInfos.") + throw new Error('Entry File does not belong to any module in moduleInfos.'); }); } private generateArkTSConfigForModules(): void { const pathSection: Record = {}; - pathSection['std'] = [ - path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_STD_PATH) - ]; - pathSection['escompat'] = [ - path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_ESCOMPAT_PATH) - ]; + pathSection['std'] = [path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_STD_PATH)]; + pathSection['escompat'] = [path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_ESCOMPAT_PATH)]; traverse(this.buildSdkPath, pathSection); this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { - pathSection[moduleInfo.packageName] = [ - path.resolve(moduleRootPath, moduleInfo.sourceRoots[0]) - ] + pathSection[moduleInfo.packageName] = [path.resolve(moduleRootPath, moduleInfo.sourceRoots[0])]; }); - this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string)=> { + this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { const dependenciesSection: string[] = []; this.generateDependenciesSection(moduleInfo, dependenciesSection); writeArkTSConfigFile(moduleInfo, pathSection, dependenciesSection); @@ -328,7 +318,4 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { } } -export { - mockBuildConfig, - MockArktsConfigBuilder -} \ No newline at end of file +export { mockBuildConfig, MockArktsConfigBuilder }; diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index bbc55431f..7694eac9f 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -13,37 +13,25 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { - arktsGlobal -} from "@koalaui/libarkts/build/lib/es2panda"; -import { - PluginDriver -} from "./plugin-driver"; -import { - PluginContext, - PluginExecutor, -} from "../../common/plugin-context"; -import { - EtsglobalRemover -} from "../../common/etsglobal-remover"; +import * as arkts from '@koalaui/libarkts'; +import { arktsGlobal } from '@koalaui/libarkts/build/lib/es2panda'; +import { PluginDriver } from './plugin-driver'; +import { PluginContext, PluginExecutor } from '../../common/plugin-context'; +import { EtsglobalRemover } from '../../common/etsglobal-remover'; -function restartCompilerUptoState( - state: arkts.Es2pandaContextState, - restart: boolean -): boolean { +function restartCompilerUptoState(state: arkts.Es2pandaContextState, restart: boolean): boolean { try { const ast: arkts.EtsScript | undefined = arkts.EtsScript.fromContext(); if (!ast) { return false; } - + if (restart) { - const srcText = new EtsglobalRemover().visitor(ast).dumpSrc() - arktsGlobal.es2panda._DestroyContext(arktsGlobal.context) - arktsGlobal.compilerContext = arkts.Context.createFromString(srcText) + const srcText = new EtsglobalRemover().visitor(ast).dumpSrc(); + arktsGlobal.es2panda._DestroyContext(arktsGlobal.context); + arktsGlobal.compilerContext = arkts.Context.createFromString(srcText); } - + arkts.proceedToState(state); return true; } catch (e) { @@ -72,7 +60,4 @@ function insertPlugin( return true; } -export { - restartCompilerUptoState, - insertPlugin -} \ No newline at end of file +export { restartCompilerUptoState, insertPlugin }; diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index 76bfdd523..4dc3d8511 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -13,15 +13,12 @@ * limitations under the License. */ -import * as fs from "fs"; -import * as arkts from "@koalaui/libarkts"; -import { arktsGlobal } from "@koalaui/libarkts/build/lib/es2panda"; -import { CompileFileInfo } from "./artkts-config"; +import * as fs from 'fs'; +import * as arkts from '@koalaui/libarkts'; +import { arktsGlobal } from '@koalaui/libarkts/build/lib/es2panda'; +import { CompileFileInfo } from './artkts-config'; -function initGlobal( - fileInfo: CompileFileInfo, - isDebug: boolean = true -): void { +function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { const config = [ '_', '--extension', @@ -79,7 +76,7 @@ function canProceedToState(state: arkts.Es2pandaContextState): boolean { const stateToSkip: arkts.Es2pandaContextState[] = [ arkts.Es2pandaContextState.ES2PANDA_STATE_SCOPE_INITED, arkts.Es2pandaContextState.ES2PANDA_STATE_ASM_GENERATED, - arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR + arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR, ]; if (state in stateToSkip) { @@ -90,9 +87,4 @@ function canProceedToState(state: arkts.Es2pandaContextState): boolean { return currState < state; } -export { - initGlobal, - resetContext, - resetConfig, - canProceedToState -}; \ No newline at end of file +export { initGlobal, resetContext, resetConfig, canProceedToState }; diff --git a/arkui-plugins/test/utils/parse-string.ts b/arkui-plugins/test/utils/parse-string.ts index 7bfce8533..58430ca1d 100644 --- a/arkui-plugins/test/utils/parse-string.ts +++ b/arkui-plugins/test/utils/parse-string.ts @@ -22,12 +22,9 @@ function parseDumpSrc(str: string): string { } function filterSource(text: string): string { - const filtered: string = text - .replaceAll(/%/g, "_") - .replaceAll(/#/g, "_") - .replaceAll("", "_cctor_") + const filtered: string = text.replaceAll(/%/g, '_').replaceAll(/#/g, '_').replaceAll('', '_cctor_'); - return filtered + return filtered; } function cleanCopyRight(str: string): string { @@ -42,9 +39,4 @@ function removeSpaceAndReturn(str: string): string { return str.replace(spaceAndReturnRegex, ''); } -export { - parseDumpSrc, - filterSource, - cleanCopyRight, - removeSpaceAndReturn -} \ No newline at end of file +export { parseDumpSrc, filterSource, cleanCopyRight, removeSpaceAndReturn }; diff --git a/arkui-plugins/test/utils/path-config.ts b/arkui-plugins/test/utils/path-config.ts index 1ba8e511d..e322f28c8 100644 --- a/arkui-plugins/test/utils/path-config.ts +++ b/arkui-plugins/test/utils/path-config.ts @@ -13,8 +13,8 @@ * limitations under the License. */ -import * as fs from "fs"; -import * as path from "path"; +import * as fs from 'fs'; +import * as path from 'path'; export const ARKTS_CONFIG_FILE_PATH: string = 'arktsconfig.json'; export const PANDA_SDK_PATH: string = 'node_modules/@panda/sdk'; @@ -33,12 +33,12 @@ export const ETS_SUFFIX: string = '.ets'; export const ABC_SUFFIX: string = '.abc'; function getRootPath(): string { - return path.resolve(__dirname, ".."); + return path.resolve(__dirname, '..'); } function getPandaSDKPath(): string { if (!process.env.ETS2PANDA_PATH) { - throw new Error("Environment Error: ets2panda path is not defined"); + throw new Error('Environment Error: ets2panda path is not defined'); } return path.resolve(process.env.ETS2PANDA_PATH); @@ -69,10 +69,4 @@ function ensurePathExists(filePath: string): void { } } -export { - getRootPath, - getPandaSDKPath, - changeFileExtension, - getFileName, - ensurePathExists -}; \ No newline at end of file +export { getRootPath, getPandaSDKPath, changeFileExtension, getFileName, ensurePathExists }; diff --git a/arkui-plugins/test/utils/plugin-driver.ts b/arkui-plugins/test/utils/plugin-driver.ts index 62de8d96a..74e60a414 100644 --- a/arkui-plugins/test/utils/plugin-driver.ts +++ b/arkui-plugins/test/utils/plugin-driver.ts @@ -13,17 +13,9 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { - isNumber -} from "./safe-types"; -import { - Plugins, - PluginContext, - PluginHandler, - PluginState , - PluginExecutor -} from "../../common/plugin-context"; +import * as arkts from '@koalaui/libarkts'; +import { isNumber } from './safe-types'; +import { Plugins, PluginContext, PluginHandler, PluginState, PluginExecutor } from '../../common/plugin-context'; export interface PluginDriver { initPlugins(plugins: Plugins[]): void; @@ -45,9 +37,7 @@ function toCamelCase(str: string): string { function stateName(value: arkts.Es2pandaContextState): PluginState { return toCamelCase( - arkts.Es2pandaContextState[value] - .substring("ES2PANDA_STATE_".length) - .toLowerCase() + arkts.Es2pandaContextState[value].substring('ES2PANDA_STATE_'.length).toLowerCase() ) as PluginState; } @@ -57,16 +47,16 @@ function selectPlugins(plugins: Plugins[], stage: PluginState): PluginExecutor[] const post: PluginExecutor[] = []; plugins - .filter(it => (stage in it)) - .forEach(it => { + .filter((it) => stage in it) + .forEach((it) => { const pluginName: string = it.name; const handler: PluginHandler = it[stage]!; const order: string | undefined = typeof handler === 'object' ? handler.order : undefined; const rawPluginHook: PluginExecutor = { name: pluginName, - handler: typeof handler === 'object' ? handler.handler : handler + handler: typeof handler === 'object' ? handler.handler : handler, }; - + if (order === 'pre') { pre.push(rawPluginHook); } else if (order === 'post') { @@ -93,7 +83,7 @@ class MockPluginDriver implements PluginDriver { Object.values(arkts.Es2pandaContextState) .filter(isNumber) - .forEach(it => { + .forEach((it) => { const selected = selectPlugins(plugins, stateName(it)); if (selected.length > 0) { pluginsByState.set(it, selected); @@ -114,7 +104,4 @@ class MockPluginDriver implements PluginDriver { } } -export { - stateName, - MockPluginDriver -} \ No newline at end of file +export { stateName, MockPluginDriver }; diff --git a/arkui-plugins/test/utils/plugin-tester.ts b/arkui-plugins/test/utils/plugin-tester.ts index 56c0c2065..c6b36d33d 100644 --- a/arkui-plugins/test/utils/plugin-tester.ts +++ b/arkui-plugins/test/utils/plugin-tester.ts @@ -13,35 +13,13 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { - ArktsConfigBuilder, - BuildConfig, - CompileFileInfo, - MockArktsConfigBuilder, - ModuleInfo -} from "./artkts-config"; -import { - MockPluginDriver, - PluginDriver, - stateName -} from "./plugin-driver"; -import { - isNumber -} from "./safe-types"; -import { - canProceedToState, - initGlobal -} from "./global"; -import { - insertPlugin, - restartCompilerUptoState -} from "./compile"; -import { - PluginExecutor, - Plugins, - PluginState -} from "../../common/plugin-context"; +import * as arkts from '@koalaui/libarkts'; +import { ArktsConfigBuilder, BuildConfig, CompileFileInfo, MockArktsConfigBuilder, ModuleInfo } from './artkts-config'; +import { MockPluginDriver, PluginDriver, stateName } from './plugin-driver'; +import { isNumber } from './safe-types'; +import { canProceedToState, initGlobal } from './global'; +import { insertPlugin, restartCompilerUptoState } from './compile'; +import { PluginExecutor, Plugins, PluginState } from '../../common/plugin-context'; type TestParams = Parameters; @@ -49,24 +27,24 @@ type SkipFirstParam = T extends [unknown, ...infer Rest] ? type PluginTestHooks = { [K in PluginState | `${PluginState}:${string}`]?: SkipFirstParam; -} +}; type TestHooks = { beforeAll?: Parameters; afterAll?: Parameters; beforeEach?: Parameters; afterEach?: Parameters; -} +}; export interface PluginTestContext { - script?: arkts.AstNode, - errors?: string[], - warnings?: string[] + script?: arkts.AstNode; + errors?: string[]; + warnings?: string[]; } export interface PluginTesterOptions { - stopAfter: PluginState, - buildConfig?: BuildConfig + stopAfter: PluginState; + buildConfig?: BuildConfig; } class PluginTester { @@ -123,18 +101,18 @@ class PluginTester { pluginHooks: PluginTestHooks, plugins?: PluginExecutor[] ): void { - if (plugins && plugins.length > 0){ + if (plugins && plugins.length > 0) { plugins.forEach((plugin) => { const pluginName: string = plugin.name; const key: `${PluginState}:${string}` = `${state}:${pluginName}`; this.test(key, index, `[${key}] ${testName}`, pluginHooks, plugin); - }) + }); } this.test(state, index, `[${state}] ${testName}`, pluginHooks); } private singleFileCompile( - fileInfo: CompileFileInfo, + fileInfo: CompileFileInfo, moduleInfo: ModuleInfo, testName: string, pluginHooks: PluginTestHooks, @@ -146,26 +124,22 @@ class PluginTester { Object.values(arkts.Es2pandaContextState) .filter(isNumber) - .forEach(it => { + .forEach((it) => { if (shouldStop) return; const state: PluginState = stateName(it); const plugins: PluginExecutor[] | undefined = this.pluginDriver.getSortedPlugins(it); this.proceedToState( - state, - it, + state, + it, `${moduleInfo.packageName} - ${fileInfo.fileName}: ${testName}`, pluginHooks, plugins - ) + ); shouldStop = state === stopAfter; }); } - private traverseFile( - testName: string, - pluginHooks: PluginTestHooks, - stopAfter: PluginState - ): void { + private traverseFile(testName: string, pluginHooks: PluginTestHooks, stopAfter: PluginState): void { this.configBuilder.moduleInfos.forEach((moduleInfo) => { moduleInfo.compileFileInfos.forEach((fileInfo) => { this.singleFileCompile(fileInfo, moduleInfo, testName, pluginHooks, stopAfter); @@ -174,8 +148,8 @@ class PluginTester { } run( - testName: string, - plugins: Plugins[], + testName: string, + plugins: Plugins[], pluginHooks: PluginTestHooks, options: PluginTesterOptions, testHooks?: TestHooks @@ -204,6 +178,4 @@ class PluginTester { } } -export { - PluginTester -} +export { PluginTester }; diff --git a/arkui-plugins/test/utils/safe-types.ts b/arkui-plugins/test/utils/safe-types.ts index 5802b5b2e..728c06501 100644 --- a/arkui-plugins/test/utils/safe-types.ts +++ b/arkui-plugins/test/utils/safe-types.ts @@ -17,6 +17,4 @@ function isNumber(value: any): value is number { return typeof value === `number`; } -export { - isNumber -} \ No newline at end of file +export { isNumber }; diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index c2946d51a..e544623b2 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -220,7 +220,7 @@ function tranformPropertyMembers( if (!scope?.hasUpdateStruct) { collections.push(structFactory.createUpdateStruct(currentStructInfo, optionsTypeName, isDecl)); } - if ( currentStructInfo.isReusable ) { + if (currentStructInfo.isReusable) { collections.push(structFactory.toRecord(optionsTypeName, currentStructInfo.toRecordBody)); } return collect(...collections, ...propertyMembers); diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index c7f5b2372..5208f9995 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -13,57 +13,41 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { getInteropPath } from "../path"; -const interop = require(getInteropPath()) -const nullptr = interop.nullptr -import { - AbstractVisitor, - VisitorOptions -} from "../common/abstract-visitor"; +import * as arkts from '@koalaui/libarkts'; +import { getInteropPath } from '../path'; +const interop = require(getInteropPath()); +const nullptr = interop.nullptr; +import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { CustomComponentNames, getCustomComponentOptionsName, createOptionalClassProperty, - findLocalImport -} from "./utils"; -import { - isAnnotation, - updateStructMetadata, - backingField, - expectName, - annotation -} from "../common/arkts-utils"; -import { - EntryWrapperNames, - findEntryWithStorageInClassAnnotations -} from "./entry-translators/utils"; -import { - factory as entryFactory -} from "./entry-translators/factory"; + findLocalImport, +} from './utils'; +import { isAnnotation, updateStructMetadata, backingField, expectName, annotation } from '../common/arkts-utils'; +import { EntryWrapperNames, findEntryWithStorageInClassAnnotations } from './entry-translators/utils'; +import { factory as entryFactory } from './entry-translators/factory'; import { hasDecorator, DecoratorNames, getStateManagementType, - collectPropertyDecorators -} from "./property-translators/utils"; -import { - factory -} from "./ui-factory"; + collectPropertyDecorators, +} from './property-translators/utils'; +import { factory } from './ui-factory'; export interface ComponentTransformerOptions extends VisitorOptions { - arkui?: string + arkui?: string; } type ScopeInfo = { - name: string, - isEntry?: boolean, - isComponent?: boolean, - isReusable?: boolean -} + name: string; + isEntry?: boolean; + isComponent?: boolean; + isReusable?: boolean; +}; interface ComponentContext { - structMembers: Map, + structMembers: Map; } export class ComponentTransformer extends AbstractVisitor { diff --git a/arkui-plugins/ui-plugins/entry-translators/entry-transformer.ts b/arkui-plugins/ui-plugins/entry-translators/entry-transformer.ts index bb936a3e3..49d46e67b 100644 --- a/arkui-plugins/ui-plugins/entry-translators/entry-transformer.ts +++ b/arkui-plugins/ui-plugins/entry-translators/entry-transformer.ts @@ -13,11 +13,11 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { AbstractVisitor } from "../../common/abstract-visitor"; -import { isEntryWrapperClass } from "./utils"; -import { factory } from "./factory"; +import { AbstractVisitor } from '../../common/abstract-visitor'; +import { isEntryWrapperClass } from './utils'; +import { factory } from './factory'; export class EntryTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { @@ -27,4 +27,4 @@ export class EntryTransformer extends AbstractVisitor { } return newNode; } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/entry-translators/utils.ts b/arkui-plugins/ui-plugins/entry-translators/utils.ts index 9f523345b..c3b1dfbef 100644 --- a/arkui-plugins/ui-plugins/entry-translators/utils.ts +++ b/arkui-plugins/ui-plugins/entry-translators/utils.ts @@ -13,10 +13,10 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { factory } from "./factory"; -import { isAnnotation } from "../../common/arkts-utils"; -import { CustomComponentNames } from "../utils"; +import * as arkts from '@koalaui/libarkts'; +import { factory } from './factory'; +import { isAnnotation } from '../../common/arkts-utils'; +import { CustomComponentNames } from '../utils'; export enum EntryWrapperNames { ENTRY_FUNC = 'entry', @@ -24,7 +24,7 @@ export enum EntryWrapperNames { ENTRY_STORAGE_ANNOTATION_KEY = 'storage', ENTRY_STORAGE_LOCAL_STORAGE_PROPERTY_NAME = '_entry_local_storage_', ENTRY_DEFAULT_IMPORT = '@ohos.arkui.component', - ENTRY_POINT_CLASS_NAME = 'EntryPoint' + ENTRY_POINT_CLASS_NAME = 'EntryPoint', } /** @@ -52,8 +52,8 @@ export class EntryHandler { public createEntryWrapper(): arkts.ClassDeclaration[] { let result: arkts.ClassDeclaration[] = []; - this.entryDefClassName.forEach(classname => { - result.push(factory.generateEntryWrapper(classname)) + this.entryDefClassName.forEach((classname) => { + result.push(factory.generateEntryWrapper(classname)); }); return result; } @@ -68,21 +68,17 @@ export function isEntryWrapperClass(node: arkts.AstNode): node is arkts.ClassDec /** * find `{storage: ""}` in `@Entry({storage: ""})` (i.e. annotation's properties). - * + * * @param node class definition node */ -export function findEntryWithStorageInClassAnnotations( - node: arkts.ClassDefinition -): arkts.ClassProperty | undefined { - const annotation = node.annotations.find( - (anno) => { - if (!isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION_NAME)) return false; - const property = anno.properties?.at(0); - if (!property || !arkts.isClassProperty(property)) return false; - if (!property.key || !arkts.isIdentifier(property.key)) return false; - if (!property.value || !arkts.isStringLiteral(property.value)) return false; - return property.key.name === EntryWrapperNames.ENTRY_STORAGE_ANNOTATION_KEY; - } - ); +export function findEntryWithStorageInClassAnnotations(node: arkts.ClassDefinition): arkts.ClassProperty | undefined { + const annotation = node.annotations.find((anno) => { + if (!isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION_NAME)) return false; + const property = anno.properties?.at(0); + if (!property || !arkts.isClassProperty(property)) return false; + if (!property.key || !arkts.isIdentifier(property.key)) return false; + if (!property.value || !arkts.isStringLiteral(property.value)) return false; + return property.key.name === EntryWrapperNames.ENTRY_STORAGE_ANNOTATION_KEY; + }); return annotation?.properties?.at(0) as arkts.ClassProperty | undefined; -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/name-collector.ts b/arkui-plugins/ui-plugins/name-collector.ts index 52611d21a..60d29a3e0 100644 --- a/arkui-plugins/ui-plugins/name-collector.ts +++ b/arkui-plugins/ui-plugins/name-collector.ts @@ -13,15 +13,15 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { AbstractVisitor } from "../common/abstract-visitor"; -import { hasBuilderLambdaAnnotation } from "./builder-lambda-translators/utils"; +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor } from '../common/abstract-visitor'; +import { hasBuilderLambdaAnnotation } from './builder-lambda-translators/utils'; interface ComponentInfo { argsNum: number; } -type ComponentCollection = Map +type ComponentCollection = Map; export class NameCollector extends AbstractVisitor { private components: ComponentCollection; @@ -62,10 +62,9 @@ export class NameCollector extends AbstractVisitor { findComponentFunction(node: arkts.FunctionDeclaration): arkts.ScriptFunction | undefined { const isDeclareAndExport: boolean = arkts.hasModifierFlag( - node, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE - | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT - ) + node, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT + ); if (!isDeclareAndExport) return undefined; const isComponentBuilder = hasBuilderLambdaAnnotation(node); @@ -75,7 +74,7 @@ export class NameCollector extends AbstractVisitor { return node.scriptFunction; } - visitor(node: arkts.AstNode): arkts.AstNode { + visitor(node: arkts.AstNode): arkts.AstNode { const newNode = this.visitEachChild(node); if (arkts.isFunctionDeclaration(newNode)) { const component = this.findComponentFunction(newNode); @@ -85,4 +84,4 @@ export class NameCollector extends AbstractVisitor { } return newNode; } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 627502e52..394b2327b 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -13,25 +13,12 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { - AbstractVisitor, - VisitorOptions -} from "../common/abstract-visitor"; -import { - CustomComponentNames -} from "./utils"; -import { - factory -} from "./ui-factory"; -import { - ARKUI_COMPONENT_IMPORT_NAME, - IMPORT_SOURCE_MAP, - OUTPUT_DEPENDENCY_MAP -} from "../common/predefines"; -import { - NameCollector -} from "./name-collector"; +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; +import { CustomComponentNames } from './utils'; +import { factory } from './ui-factory'; +import { ARKUI_COMPONENT_IMPORT_NAME, IMPORT_SOURCE_MAP, OUTPUT_DEPENDENCY_MAP } from '../common/predefines'; +import { NameCollector } from './name-collector'; interface MemoImportCollection { memo: boolean; @@ -65,8 +52,7 @@ export class PreprocessorTransformer extends AbstractVisitor { } isCustomConponentDecl(node: arkts.CallExpression): boolean { - const structCollection: Set = - arkts.GlobalInfo.getInfoInstance().getStructCollection(); + const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); const nodeName: string = node.expression.dumpSrc(); if (structCollection.has(nodeName)) { return true; @@ -81,23 +67,17 @@ export class PreprocessorTransformer extends AbstractVisitor { transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { if (arkts.isObjectExpression(node.arguments[0])) { - const componentName: string = - `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${node.expression.dumpSrc()}`; + const componentName: string = `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${node.expression.dumpSrc()}`; const newArg = arkts.factory.createTSAsExpression( node.arguments[0].clone(), arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(componentName) - ) + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(componentName)) ), true ); - return arkts.factory.updateCallExpression( - node, - node.expression, - node.typeArguments, - [newArg, ...node.arguments.slice(1)] - ).setTralingBlock(node.trailingBlock); + return arkts.factory + .updateCallExpression(node, node.expression, node.typeArguments, [newArg, ...node.arguments.slice(1)]) + .setTralingBlock(node.trailingBlock); } else { return node; } @@ -115,14 +95,12 @@ export class PreprocessorTransformer extends AbstractVisitor { let count = 0; while (count < componentInfo.argsNum - node.arguments.length - 1) { defaultArgs.push(arkts.factory.createUndefinedLiteral()); - count ++; + count++; } - return arkts.factory.updateCallExpression( - node, - node.expression, - node.typeArguments, - [...node.arguments, ...defaultArgs] - ); + return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ + ...node.arguments, + ...defaultArgs, + ]); } addDependencesImport(node: arkts.ETSImportDeclaration): void { @@ -130,43 +108,38 @@ export class PreprocessorTransformer extends AbstractVisitor { const isFromCompImport: boolean = node.source.str === ARKUI_COMPONENT_IMPORT_NAME; const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); - node.specifiers.forEach( - (item: arkts.AstNode) => { - if (!arkts.isImportSpecifier(item) || !item.imported?.name) return; + node.specifiers.forEach((item: arkts.AstNode) => { + if (!arkts.isImportSpecifier(item) || !item.imported?.name) return; - const importName: string = item.imported.name; - this.memoImportCollection.memo ||= importName === "memo"; - this.memoImportCollection.memoContextType ||= importName === "__memo_context_type"; - this.memoImportCollection.memoIdType ||= importName === "__memo_id_type"; - if (isFromCompImport && this.nameCollector.getComponents().includes(importName)) { - this.localComponentNames.push(item.local?.name ?? importName) - } + const importName: string = item.imported.name; + this.memoImportCollection.memo ||= importName === 'memo'; + this.memoImportCollection.memoContextType ||= importName === '__memo_context_type'; + this.memoImportCollection.memoIdType ||= importName === '__memo_id_type'; + if (isFromCompImport && this.nameCollector.getComponents().includes(importName)) { + this.localComponentNames.push(item.local?.name ?? importName); + } - if ( - structCollection.has(importName) && - this.isExternal === false - ) { - const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + importName; - const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( - node.source?.clone(), - [factory.createAdditionalImportSpecifier(interfaceName, interfaceName)], - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE - ); - this.structInterfaceImport.push(newImport); - } else { - this.addImportWithSpecifier(item, node.source!); - } + if (structCollection.has(importName) && this.isExternal === false) { + const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + importName; + const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + node.source?.clone(), + [factory.createAdditionalImportSpecifier(interfaceName, interfaceName)], + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE + ); + this.structInterfaceImport.push(newImport); + } else { + this.addImportWithSpecifier(item, node.source!); } - ); + }); } getSourceDependency(sourceName: string): string { - let dependencyName: string = ""; + let dependencyName: string = ''; IMPORT_SOURCE_MAP.forEach((value: Set, key: string) => { if (value.has(sourceName)) { dependencyName = key; } - }) + }); return dependencyName; } @@ -183,7 +156,7 @@ export class PreprocessorTransformer extends AbstractVisitor { if (OUTPUT_DEPENDENCY_MAP.has(inputName)) { OUTPUT_DEPENDENCY_MAP.get(inputName)!.forEach((item: string) => { sourceName.push(item); - }) + }); } return sourceName; } @@ -206,10 +179,7 @@ export class PreprocessorTransformer extends AbstractVisitor { // Handling component imports const importName: string = node.imported.name; const sourceName: string = source.str; - if ( - this.nameCollector.getComponents().includes(importName) - && sourceName === ARKUI_COMPONENT_IMPORT_NAME - ) { + if (this.nameCollector.getComponents().includes(importName) && sourceName === ARKUI_COMPONENT_IMPORT_NAME) { const newDependencies = [`${importName}Attribute`]; this.updateOutDependencyMap(importName, newDependencies); this.updateSourceDependencyMap(sourceName, newDependencies); @@ -219,13 +189,13 @@ export class PreprocessorTransformer extends AbstractVisitor { prepareMemoImports(): void { const newDependencies = []; if (!this.memoImportCollection.memo) { - newDependencies.push("memo"); + newDependencies.push('memo'); } if (!this.memoImportCollection.memoContextType) { - newDependencies.push("__memo_context_type"); + newDependencies.push('__memo_context_type'); } if (!this.memoImportCollection.memoIdType) { - newDependencies.push("__memo_id_type"); + newDependencies.push('__memo_id_type'); } if (newDependencies.length > 0) { this.memoNameArr.push(...newDependencies); @@ -243,7 +213,7 @@ export class PreprocessorTransformer extends AbstractVisitor { updateScriptWithImport(): void { if (!this.program) { - throw Error("Failed to insert import: Transformer has no program"); + throw Error('Failed to insert import: Transformer has no program'); } const outNames = new Set([...this.outNameArr, ...this.memoNameArr]); @@ -270,12 +240,13 @@ export class PreprocessorTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); - const newNode = this.visitEachChild(node) + const newNode = this.visitEachChild(node); if (arkts.isCallExpression(newNode) && this.isCustomConponentDecl(newNode)) { return this.transformComponentCall(newNode); } else if (arkts.isCallExpression(newNode) && this.isComponentFunctionCall(newNode)) { return this.transformComponentFunctionCall(newNode); - } if (arkts.isETSImportDeclaration(node)) { + } + if (arkts.isETSImportDeclaration(node)) { this.addDependencesImport(node); } else if (arkts.isEtsScript(node)) { if (!this.isMemoImportOnce) this.prepareMemoImports(); diff --git a/arkui-plugins/ui-plugins/printer-transformer.ts b/arkui-plugins/ui-plugins/printer-transformer.ts index 8f40aace0..2ccab0b0e 100644 --- a/arkui-plugins/ui-plugins/printer-transformer.ts +++ b/arkui-plugins/ui-plugins/printer-transformer.ts @@ -13,17 +13,15 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" -import { PrintVisitor } from '../common/print-visitor' +import * as arkts from '@koalaui/libarkts'; +import { PrintVisitor } from '../common/print-visitor'; export interface TransformerOptions { - trace?: boolean, + trace?: boolean; } -export default function printerTransformer( - userPluginOptions?: TransformerOptions -) { +export default function printerTransformer(userPluginOptions?: TransformerOptions) { return (node: arkts.EtsScript) => { - return new PrintVisitor().visitor(node) - } + return new PrintVisitor().visitor(node); + }; } diff --git a/arkui-plugins/ui-plugins/property-translators/base.ts b/arkui-plugins/ui-plugins/property-translators/base.ts index bcc469225..4be00d1c8 100644 --- a/arkui-plugins/ui-plugins/property-translators/base.ts +++ b/arkui-plugins/ui-plugins/property-translators/base.ts @@ -20,7 +20,7 @@ import { createOptionalClassProperty } from '../utils'; export abstract class PropertyTranslator { constructor( protected property: arkts.ClassProperty, - protected structName: string, + protected structName: string ) {} abstract translateMember(): arkts.AstNode[]; @@ -30,7 +30,7 @@ export abstract class PropertyTranslator { newName, this.property, getStageManagementIdent(this.property), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const member = arkts.factory.createTSNonNullExpression( @@ -39,26 +39,26 @@ export abstract class PropertyTranslator { arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, - ), + false + ) ); const thisValue: arkts.MemberExpression = arkts.factory.createMemberExpression( member, arkts.factory.createIdentifier('value'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, this.property.typeAnnotation, - thisValue, + thisValue ); const setter: arkts.MethodDefinition = this.translateSetter( originalName, this.property.typeAnnotation, - thisValue, + thisValue ); return [field, getter, setter]; } @@ -66,7 +66,7 @@ export abstract class PropertyTranslator { translateGetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - returnValue: arkts.MemberExpression, + returnValue: arkts.MemberExpression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } @@ -74,12 +74,12 @@ export abstract class PropertyTranslator { translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - left: arkts.MemberExpression, + left: arkts.MemberExpression ): arkts.MethodDefinition { const right: arkts.CallExpression = arkts.factory.createCallExpression( arkts.factory.createIdentifier('observableProxy'), undefined, - [arkts.factory.createIdentifier('value')], + [arkts.factory.createIdentifier('value')] ); return createSetter(originalName, typeAnnotation, left, right); } diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts index eb164a03d..f6b08b836 100644 --- a/arkui-plugins/ui-plugins/property-translators/builderParam.ts +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -13,27 +13,21 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { - createGetter, +import { + createGetter, createSetter, generateThisBackingValue, generateThisBacking, getValueInAnnotation, - DecoratorNames -} from "./utils"; -import { PropertyTranslator } from "./base"; -import { - GetterSetter, - InitializerConstructor -} from "./types"; -import { - backingField, - expectName -} from "../../common/arkts-utils"; -import { createOptionalClassProperty } from "../utils"; -import { factory } from "./factory"; + DecoratorNames, +} from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { createOptionalClassProperty } from '../utils'; +import { factory } from './factory'; export class BuilderParamTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -54,48 +48,57 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, '', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const field: arkts.ClassProperty = createOptionalClassProperty( + newName, + this.property, + '', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); const thisGetValue: arkts.Expression = generateThisBacking(newName, false, true); const thisSetValue: arkts.Expression = generateThisBacking(newName, false, false); - const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisGetValue); - const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisSetValue); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisGetValue + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisSetValue + ); return [field, getter, setter]; } translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } translateSetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, left: arkts.Expression ): arkts.MethodDefinition { const right: arkts.Identifier = arkts.factory.createIdentifier('value'); return createSetter(originalName, typeAnnotation, left, right, true); } - generateInitializeStruct( - mutableThis: arkts.Expression, - originalName: string - ): arkts.AstNode { + generateInitializeStruct(mutableThis: arkts.Expression, originalName: string): arkts.AstNode { return arkts.factory.createAssignmentExpression( mutableThis, arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier("initializers"), originalName)); + arkts.factory.createIdentifier('initializers'), + originalName + ) + ); } - generateUpdateStruct( - mutableThis: arkts.Expression, - originalName: string - ): arkts.AstNode { + generateUpdateStruct(mutableThis: arkts.Expression, originalName: string): arkts.AstNode { const right: arkts.MemberExpression = arkts.factory.createMemberExpression( arkts.factory.createIdentifier('initializers'), arkts.factory.createIdentifier(originalName), @@ -109,5 +112,4 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia right ); } - -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/consume.ts b/arkui-plugins/ui-plugins/property-translators/consume.ts index 7f10bc8ac..ac7491b70 100644 --- a/arkui-plugins/ui-plugins/property-translators/consume.ts +++ b/arkui-plugins/ui-plugins/property-translators/consume.ts @@ -13,26 +13,20 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { - createGetter, +import { + createGetter, createSetter, generateThisBackingValue, generateThisBacking, getValueInAnnotation, - DecoratorNames -} from "./utils"; -import { PropertyTranslator } from "./base"; -import { - GetterSetter, - InitializerConstructor -} from "./types"; -import { - backingField, - expectName -} from "../../common/arkts-utils"; -import { createOptionalClassProperty } from "../utils"; + DecoratorNames, +} from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { createOptionalClassProperty } from '../utils'; export class ConsumeTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -50,26 +44,38 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, 'MutableState', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const field: arkts.ClassProperty = createOptionalClassProperty( + newName, + this.property, + 'MutableState', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); const thisValue: arkts.MemberExpression = generateThisBackingValue(newName, false, true); - const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisValue); - const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisValue); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisValue + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisValue + ); return [field, getter, setter]; } translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.MemberExpression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } translateSetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, left: arkts.MemberExpression ): arkts.MethodDefinition { const right: arkts.CallExpression = arkts.factory.createCallExpression( @@ -81,10 +87,7 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer return createSetter(originalName, typeAnnotation, left, right); } - generateInitializeStruct( - newName: string, - originalName: string - ): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { let consumeValueStr: string | undefined = getValueInAnnotation(this.property, DecoratorNames.CONSUME); if (!consumeValueStr) { consumeValueStr = originalName; @@ -106,5 +109,4 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer right ); } - -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts index 047c6baa3..7125b11c7 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -13,57 +13,64 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts"; -import { getInteropPath } from "../../path"; -import { GenSymGenerator } from "../../common/gensym-generator"; -import { factory as UIFactory } from "../ui-factory"; -const interop = require(getInteropPath()) -const nullptr = interop.nullptr +import * as arkts from '@koalaui/libarkts'; +import { getInteropPath } from '../../path'; +import { GenSymGenerator } from '../../common/gensym-generator'; +import { factory as UIFactory } from '../ui-factory'; +const interop = require(getInteropPath()); +const nullptr = interop.nullptr; export class factory { /** * generate an substitution for optional expression ?., e.g. `{let _tmp = xxx; _tmp == null ? undefined : xxx}`. - * + * * @param object item before ?.. * @param key item after ?.. */ - static createBlockStatementForOptionalExpression(object: arkts.AstNode, key: string, isCall: boolean = false): arkts.Expression { + static createBlockStatementForOptionalExpression( + object: arkts.AstNode, + key: string, + isCall: boolean = false + ): arkts.Expression { let id = GenSymGenerator.getInstance().id(key); const statements: arkts.Statement[] = [ - factory.generateLetVariableDecl( - arkts.factory.createIdentifier(id), - object - ), - factory.generateTernaryExpression(id, key, isCall) + factory.generateLetVariableDecl(arkts.factory.createIdentifier(id), object), + factory.generateTernaryExpression(id, key, isCall), ]; return arkts.factory.createBlockExpression(statements); } /** * generate a variable declaration, e.g. `let = `; - * + * * @param left left expression. * @param right right expression. */ - static generateLetVariableDecl(left: arkts.Identifier , right: arkts.AstNode): arkts.VariableDeclaration { + static generateLetVariableDecl(left: arkts.Identifier, right: arkts.AstNode): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - left, - right - )] + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + left, + right + ), + ] ); } /** * generate a ternary expression, e.g. ` ? : `; - * + * * @param testLeft the left hand of the test condition. * @param key item after ?. */ - static generateTernaryExpression(testLeft: string, key: string, isCall: boolean = false): arkts.ExpressionStatement { + static generateTernaryExpression( + testLeft: string, + key: string, + isCall: boolean = false + ): arkts.ExpressionStatement { const test = arkts.factory.createBinaryExpression( arkts.factory.createIdentifier(testLeft), arkts.factory.createNullLiteral(), @@ -78,13 +85,17 @@ export class factory { false ); return arkts.factory.createExpressionStatement( - arkts.factory.createConditionalExpression(test, consequent, isCall? arkts.factory.createCallExpression(alternate, undefined, undefined) : alternate) + arkts.factory.createConditionalExpression( + test, + consequent, + isCall ? arkts.factory.createCallExpression(alternate, undefined, undefined) : alternate + ) ); } /** * generate an substitution for two optional expression ?., e.g. a?.b?.c. - * + * * @param node entry wrapper class declaration node. */ static createDoubleBlockStatementForOptionalExpression( @@ -93,20 +104,17 @@ export class factory { key2: string ): arkts.Expression { let id = GenSymGenerator.getInstance().id(key1); - let initial: arkts.Expression = factory.createBlockStatementForOptionalExpression(object, key1) + let initial: arkts.Expression = factory.createBlockStatementForOptionalExpression(object, key1); const statements: arkts.Statement[] = [ - factory.generateLetVariableDecl( - arkts.factory.createIdentifier(id), - initial - ), - factory.generateTernaryExpression(id, key2) + factory.generateLetVariableDecl(arkts.factory.createIdentifier(id), initial), + factory.generateTernaryExpression(id, key2), ]; return arkts.factory.createBlockExpression(statements); } /** * generate an memberExpression with nonNull or optional, e.g. object.property, object?.property or object!.property - * + * * @param object item before point. * @param property item after point. */ @@ -127,8 +135,8 @@ export class factory { } /* - * create `(): => { }`. - */ + * create `(): => { }`. + */ static createArrowFunctionWithParamsAndBody( typeParams: arkts.TSTypeParameterDeclaration | undefined, params: arkts.Expression[] | undefined, @@ -139,67 +147,54 @@ export class factory { return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( arkts.BlockStatement.createBlockStatement(bodyStatementsList), - arkts.factory.createFunctionSignature( - typeParams, - params ? params : [], - returnType, - hasReceiver, - ), + arkts.factory.createFunctionSignature(typeParams, params ? params : [], returnType, hasReceiver), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE ) ); } /* - * create @Watch callback, e.g. (propertyName: string): void => {this.(propertyName)}. - */ - static createWatchCallback( - callbackName: string, - ): arkts.ArrowFunctionExpression { + * create @Watch callback, e.g. (propertyName: string): void => {this.(propertyName)}. + */ + static createWatchCallback(callbackName: string): arkts.ArrowFunctionExpression { return factory.createArrowFunctionWithParamsAndBody( undefined, [ arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier('_', UIFactory.createTypeReferenceFromString('string')), undefined - ) + ), ], arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), false, [ arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - factory.generateThisCall(callbackName), - undefined, - [arkts.factory.createIdentifier('_')] - ) - ) + arkts.factory.createCallExpression(factory.generateThisCall(callbackName), undefined, [ + arkts.factory.createIdentifier('_'), + ]) + ), ] ); } /* - * create this. with optional or nonNullable. - */ - static generateThisCall( - name: string, - optional: boolean = false, - nonNull: boolean = false, - ): arkts.Expression { + * create this. with optional or nonNullable. + */ + static generateThisCall(name: string, optional: boolean = false, nonNull: boolean = false): arkts.Expression { const member: arkts.Expression = arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), arkts.factory.createIdentifier(`${name}`), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - optional, + optional ); return nonNull ? arkts.factory.createTSNonNullExpression(member) : member; } /* - * create `initializers!.!.()`. - */ + * create `initializers!.!.()`. + */ static createBackingGetOrSetCall( newName: string, getOrSet: string, @@ -208,21 +203,21 @@ export class factory { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true), + factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true) ), arkts.factory.createIdentifier(getOrSet), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), undefined, - args, + args ); } /* - * create `new ()`. - */ + * create `new ()`. + */ static createNewDecoratedInstantiate( className: string, typeAnnotation: arkts.TypeNode | undefined, @@ -232,12 +227,10 @@ export class factory { arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier(className), - arkts.factory.createTSTypeParameterInstantiation( - typeAnnotation ? [typeAnnotation.clone()] : [], - ), - ), + arkts.factory.createTSTypeParameterInstantiation(typeAnnotation ? [typeAnnotation.clone()] : []) + ) ), - args?.length ? args : [], + args?.length ? args : [] ); } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/index.ts b/arkui-plugins/ui-plugins/property-translators/index.ts index 697ff38e3..c30ace4fc 100644 --- a/arkui-plugins/ui-plugins/property-translators/index.ts +++ b/arkui-plugins/ui-plugins/property-translators/index.ts @@ -34,10 +34,7 @@ import { BuilderParamTranslator } from './builderParam'; export { PropertyTranslator }; -export function classifyProperty( - member: arkts.AstNode, - structName: string -): PropertyTranslator | undefined { +export function classifyProperty(member: arkts.AstNode, structName: string): PropertyTranslator | undefined { if (!arkts.isClassProperty(member)) return undefined; if (isStatic(member)) return new staticPropertyTranslator(member, structName); diff --git a/arkui-plugins/ui-plugins/property-translators/link.ts b/arkui-plugins/ui-plugins/property-translators/link.ts index fb3740f74..eafd90c95 100644 --- a/arkui-plugins/ui-plugins/property-translators/link.ts +++ b/arkui-plugins/ui-plugins/property-translators/link.ts @@ -15,13 +15,13 @@ import * as arkts from '@koalaui/libarkts'; -import { +import { generateToRecord, createGetter, createSetter2, generateThisBacking, generateGetOrSetCall, - judgeIfAddWatchFunc + judgeIfAddWatchFunc, } from './utils'; import { PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; @@ -52,14 +52,14 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon generateInitializeStruct(newName: string, originalName: string) { const test = factory.createBlockStatementForOptionalExpression( arkts.factory.createIdentifier('initializers'), - newName, + newName ); const args: arkts.Expression[] = [ arkts.factory.create1StringLiteral(originalName), arkts.factory.createTSNonNullExpression( factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true) - ) + ), ]; judgeIfAddWatchFunc(args, this.property); const consequent = arkts.BlockStatement.createBlockStatement([ @@ -67,12 +67,8 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon arkts.factory.createAssignmentExpression( generateThisBacking(newName, false, false), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.createNewDecoratedInstantiate( - 'LinkDecoratedVariable', - this.property.typeAnnotation, - args - ) - ), + factory.createNewDecoratedInstantiate('LinkDecoratedVariable', this.property.typeAnnotation, args) + ) ), ]); @@ -84,22 +80,22 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon newName, this.property, 'LinkDecoratedVariable', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set'), + generateGetOrSetCall(thisValue, 'set') ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, this.property.typeAnnotation, - thisGet, + thisGet ); const setter: arkts.MethodDefinition = this.translateSetter( originalName, this.property.typeAnnotation, - thisSet, + thisSet ); return [field, getter, setter]; @@ -108,7 +104,7 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon translateGetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - returnValue: arkts.Expression, + returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } @@ -116,7 +112,7 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - statement: arkts.AstNode, + statement: arkts.AstNode ): arkts.MethodDefinition { return createSetter2(originalName, typeAnnotation, statement); } diff --git a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts index cadc63e5d..9d43765eb 100755 --- a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts @@ -86,11 +86,11 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In arkts.factory.createIdentifier('_entry_local_storage_'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), arkts.factory.createStringLiteral(localStorageLinkValueStr), this.property.value ?? arkts.factory.createIdentifier('undefined'), - ], + ] ); return arkts.factory.createAssignmentExpression( @@ -99,10 +99,10 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - call, + call ); } } diff --git a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts index bddb14555..965e5fb2b 100644 --- a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts @@ -83,7 +83,7 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In arkts.factory.createIdentifier('_entry_local_storage_'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ); const binaryItem = arkts.factory.createCallExpression( arkts.factory.createIdentifier('StorageLinkState'), @@ -92,7 +92,7 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In insideMember, arkts.factory.createStringLiteral(localStorageporpValueStr), this.property.value ?? arkts.factory.createIdentifier('undefined'), - ], + ] ); const call = arkts.factory.createCallExpression( arkts.factory.createIdentifier('propState'), @@ -103,9 +103,9 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In arkts.factory.createIdentifier('value'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), - ], + ] ); return arkts.factory.createAssignmentExpression( arkts.factory.createMemberExpression( @@ -113,10 +113,10 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - call, + call ); } @@ -136,16 +136,16 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In arkts.factory.createIdentifier('_entry_local_storage_'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), arkts.factory.createStringLiteral(localStorageporpValueStr), this.property.value ?? arkts.factory.createIdentifier('undefined'), - ], + ] ), arkts.factory.createIdentifier('value'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ); const test = arkts.factory.createMemberExpression( @@ -153,7 +153,7 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ); const consequent = arkts.BlockStatement.createBlockStatement([ @@ -164,11 +164,11 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In arkts.factory.createIdentifier('update'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), undefined, - [StorageLinkStateValue], - ), + [StorageLinkStateValue] + ) ), ]); diff --git a/arkui-plugins/ui-plugins/property-translators/objectlink.ts b/arkui-plugins/ui-plugins/property-translators/objectlink.ts index 2a21e8200..49b177d4f 100644 --- a/arkui-plugins/ui-plugins/property-translators/objectlink.ts +++ b/arkui-plugins/ui-plugins/property-translators/objectlink.ts @@ -49,7 +49,7 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali const call = arkts.factory.createCallExpression( arkts.factory.createIdentifier('objectLinkState'), this.property.typeAnnotation ? [this.property.typeAnnotation] : [], - [], + [] ); return arkts.factory.createAssignmentExpression( arkts.factory.createMemberExpression( @@ -57,10 +57,10 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - call, + call ); } @@ -70,7 +70,7 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ); const consequent = arkts.BlockStatement.createBlockStatement([ @@ -81,16 +81,16 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali arkts.factory.createIdentifier('update'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), undefined, [ factory.createBlockStatementForOptionalExpression( arkts.factory.createIdentifier('initializers'), - originalName, + originalName ), - ], - ), + ] + ) ), ]); return arkts.factory.createExpressionStatement(arkts.factory.createIfStatement(test, consequent)); diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts index 356863eda..5874336e0 100644 --- a/arkui-plugins/ui-plugins/property-translators/prop.ts +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -13,27 +13,21 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { +import { generateToRecord, - createGetter, + createGetter, createSetter2, generateGetOrSetCall, generateThisBacking, - judgeIfAddWatchFunc -} from "./utils"; -import { PropertyTranslator } from "./base"; -import { - GetterSetter, - InitializerConstructor -} from "./types"; -import { - backingField, - expectName -} from "../../common/arkts-utils"; -import { createOptionalClassProperty } from "../utils"; -import { factory } from "./factory"; + judgeIfAddWatchFunc, +} from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { createOptionalClassProperty } from '../utils'; +import { factory } from './factory'; export class PropTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -59,38 +53,48 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, "PropDecoratedVariable", - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const field: arkts.ClassProperty = createOptionalClassProperty( + newName, + this.property, + 'PropDecoratedVariable', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, "get"); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, "set")); - const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisGet); - const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisSet); - + generateGetOrSetCall(thisValue, 'set') + ); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisGet + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisSet + ); + return [field, getter, setter]; } translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } translateSetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, statement: arkts.AstNode ): arkts.MethodDefinition { return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct( - newName: string, - originalName: string - ): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const binaryItem = arkts.factory.createBinaryExpression( factory.createBlockStatementForOptionalExpression( arkts.factory.createIdentifier('initializers'), @@ -99,14 +103,18 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon this.property.value ?? arkts.factory.createIdentifier('undefined'), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ); - const nonNullItem =arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true)); - const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), this.property.value ? binaryItem : nonNullItem]; + const nonNullItem = arkts.factory.createTSNonNullExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true) + ); + const args: arkts.Expression[] = [ + arkts.factory.create1StringLiteral(originalName), + this.property.value ? binaryItem : nonNullItem, + ]; judgeIfAddWatchFunc(args, this.property); const right = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier("PropDecoratedVariable"), + arkts.factory.createIdentifier('PropDecoratedVariable'), arkts.factory.createTSTypeParameterInstantiation( this.property.typeAnnotation ? [this.property.typeAnnotation] : [] ) @@ -122,10 +130,7 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon return arkts.factory.createExpressionStatement(assign); } - generateUpdateStruct( - mutableThis: arkts.Expression, - originalName: string - ): arkts.AstNode { + generateUpdateStruct(mutableThis: arkts.Expression, originalName: string): arkts.AstNode { const binaryItem = arkts.factory.createBinaryExpression( factory.createBlockStatementForOptionalExpression( arkts.factory.createIdentifier('initializers'), @@ -141,14 +146,16 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon false, false ); - const nonNullItem =arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true)); + const nonNullItem = arkts.factory.createTSNonNullExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true) + ); return arkts.factory.createIfStatement( binaryItem, - arkts.factory.createBlock( - [arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(member, undefined, [nonNullItem]))] - ) + arkts.factory.createBlock([ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression(member, undefined, [nonNullItem]) + ), + ]) ); } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/provide.ts b/arkui-plugins/ui-plugins/property-translators/provide.ts index 83cd56990..ced49cefa 100644 --- a/arkui-plugins/ui-plugins/property-translators/provide.ts +++ b/arkui-plugins/ui-plugins/property-translators/provide.ts @@ -13,26 +13,14 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { - createGetter, - createSetter, - generateThisBackingValue, - getValueInAnnotation, - DecoratorNames -} from "./utils"; -import { PropertyTranslator } from "./base"; -import { - GetterSetter, - InitializerConstructor -} from "./types"; -import { - backingField, - expectName -} from "../../common/arkts-utils"; -import { createOptionalClassProperty } from "../utils"; -import { factory } from "./factory"; +import { createGetter, createSetter, generateThisBackingValue, getValueInAnnotation, DecoratorNames } from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { createOptionalClassProperty } from '../utils'; +import { factory } from './factory'; export class ProvideTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -50,26 +38,38 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, 'MutableState', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const field: arkts.ClassProperty = createOptionalClassProperty( + newName, + this.property, + 'MutableState', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); const thisValue: arkts.MemberExpression = generateThisBackingValue(newName, false, true); - const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisValue); - const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisValue); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisValue + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisValue + ); return [field, getter, setter]; } translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.MemberExpression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } translateSetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, left: arkts.MemberExpression ): arkts.MethodDefinition { const right: arkts.CallExpression = arkts.factory.createCallExpression( @@ -81,46 +81,35 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer return createSetter(originalName, typeAnnotation, left, right); } - generateInitializeStruct( - newName: string, - originName: string - ): arkts.AstNode { + generateInitializeStruct(newName: string, originName: string): arkts.AstNode { let provideValueStr: string | undefined = getValueInAnnotation(this.property, DecoratorNames.PROVIDE); if (!provideValueStr) { provideValueStr = originName; } - const memExp: arkts.Expression = - factory.createDoubleBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), newName, 'value'); - const body: arkts.BlockStatement = arkts.factory.createBlock( - [ - arkts.factory.createReturnStatement( - arkts.factory.createBinaryExpression( - memExp, - this.property.value, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING - ) - ) - ] + const memExp: arkts.Expression = factory.createDoubleBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + newName, + 'value' ); + const body: arkts.BlockStatement = arkts.factory.createBlock([ + arkts.factory.createReturnStatement( + arkts.factory.createBinaryExpression( + memExp, + this.property.value, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ) + ), + ]); const script = arkts.factory.createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [], - this.property.typeAnnotation, - false - ), + arkts.FunctionSignature.createFunctionSignature(undefined, [], this.property.typeAnnotation, false), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); const right: arkts.CallExpression = arkts.factory.createCallExpression( arkts.factory.createIdentifier('contextLocalStateOf'), this.property.typeAnnotation ? [this.property.typeAnnotation] : undefined, - [ - arkts.factory.create1StringLiteral(provideValueStr), - arkts.factory.createArrowFunction(script) - ] + [arkts.factory.create1StringLiteral(provideValueStr), arkts.factory.createArrowFunction(script)] ); return arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( @@ -136,5 +125,4 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer ) ); } - -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts index 3e569b3f1..875f14d35 100644 --- a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts +++ b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts @@ -13,21 +13,12 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { - createGetter, - createSetter, -} from "./utils"; -import { PropertyTranslator } from "./base"; -import { - GetterSetter, - InitializerConstructor -} from "./types"; -import { - backingField, - expectName -} from "../../common/arkts-utils"; +import { createGetter, createSetter } from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; export class regularPropertyTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -44,26 +35,23 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini } translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } translateSetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, left: arkts.MemberExpression ): arkts.MethodDefinition { const right: arkts.Identifier = arkts.factory.createIdentifier('value'); return createSetter(originalName, typeAnnotation, left, right); } - generateInitializeStruct( - newName: string, - originalName: string - ): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { return arkts.factory.createAssignmentExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier('this'), @@ -76,4 +64,4 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini this.property.value ?? arkts.factory.createIdentifier('undefined') ); } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts index d612a128f..5a528df4c 100644 --- a/arkui-plugins/ui-plugins/property-translators/state.ts +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -13,27 +13,21 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { +import { generateToRecord, - createGetter, + createGetter, createSetter2, generateThisBacking, generateGetOrSetCall, - judgeIfAddWatchFunc -} from "./utils"; -import { PropertyTranslator } from "./base"; -import { - GetterSetter, - InitializerConstructor -} from "./types"; -import { - backingField, - expectName -} from "../../common/arkts-utils"; -import { createOptionalClassProperty } from "../utils"; -import { factory } from "./factory"; + judgeIfAddWatchFunc, +} from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { createOptionalClassProperty } from '../utils'; +import { factory } from './factory'; export class StateTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -55,40 +49,53 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, "StateDecoratedVariable", - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE); + const field: arkts.ClassProperty = createOptionalClassProperty( + newName, + this.property, + 'StateDecoratedVariable', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, "get"); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, "set")); - const getter: arkts.MethodDefinition = this.translateGetter(originalName, this.property.typeAnnotation, thisGet); - const setter: arkts.MethodDefinition = this.translateSetter(originalName, this.property.typeAnnotation, thisSet); - + generateGetOrSetCall(thisValue, 'set') + ); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisGet + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisSet + ); + return [field, getter, setter]; } translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } translateSetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, statement: arkts.AstNode ): arkts.MethodDefinition { return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct( - newName: string, - originalName: string - ): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const binaryItem = arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression(arkts.factory.createIdentifier('initializers'), originalName), + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName + ), this.property.value ?? arkts.factory.createIdentifier('undefined'), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ); @@ -97,7 +104,7 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo const right = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier("StateDecoratedVariable"), + arkts.factory.createIdentifier('StateDecoratedVariable'), arkts.factory.createTSTypeParameterInstantiation( this.property.typeAnnotation ? [this.property.typeAnnotation] : [] ) @@ -112,4 +119,4 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo ); return arkts.factory.createExpressionStatement(assign); } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/staticProperty.ts b/arkui-plugins/ui-plugins/property-translators/staticProperty.ts index 283fc8812..12e9535c5 100644 --- a/arkui-plugins/ui-plugins/property-translators/staticProperty.ts +++ b/arkui-plugins/ui-plugins/property-translators/staticProperty.ts @@ -13,21 +13,12 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; -import { - createGetter, - createSetter, -} from "./utils"; -import { PropertyTranslator } from "./base"; -import { - GetterSetter, - InitializerConstructor -} from "./types"; -import { - backingField, - expectName -} from "../../common/arkts-utils"; +import { createGetter, createSetter } from './utils'; +import { PropertyTranslator } from './base'; +import { GetterSetter, InitializerConstructor } from './types'; +import { backingField, expectName } from '../../common/arkts-utils'; export class staticPropertyTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -43,19 +34,19 @@ export class staticPropertyTranslator extends PropertyTranslator implements Init } translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } translateSetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, left: arkts.MemberExpression ): arkts.MethodDefinition { const right: arkts.Identifier = arkts.factory.createIdentifier('value'); return createSetter(originalName, typeAnnotation, left, right); } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/storageProp.ts b/arkui-plugins/ui-plugins/property-translators/storageProp.ts index c3f17c276..cea565a8b 100644 --- a/arkui-plugins/ui-plugins/property-translators/storageProp.ts +++ b/arkui-plugins/ui-plugins/property-translators/storageProp.ts @@ -25,7 +25,7 @@ import { createSetter2, generateThisBacking, generateGetOrSetCall, - judgeIfAddWatchFunc + judgeIfAddWatchFunc, } from './utils'; import { createOptionalClassProperty } from '../utils'; @@ -98,9 +98,9 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier('StoragePropDecoratedVariable'), arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [], - ), - ), + this.property.typeAnnotation ? [this.property.typeAnnotation] : [] + ) + ) ), args ); @@ -111,10 +111,10 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - newClass, + newClass ); } @@ -123,22 +123,22 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial newName, this.property, 'StoragePropDecoratedVariable', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set'), + generateGetOrSetCall(thisValue, 'set') ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, this.property.typeAnnotation, - thisGet, + thisGet ); const setter: arkts.MethodDefinition = this.translateSetter( originalName, this.property.typeAnnotation, - thisSet, + thisSet ); return [field, getter, setter]; } @@ -146,7 +146,7 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial translateGetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - returnValue: arkts.Expression, + returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } @@ -154,7 +154,7 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - statement: arkts.AstNode, + statement: arkts.AstNode ): arkts.MethodDefinition { return createSetter2(originalName, typeAnnotation, statement); } diff --git a/arkui-plugins/ui-plugins/property-translators/storagelink.ts b/arkui-plugins/ui-plugins/property-translators/storagelink.ts index a2f69a239..bde1a2adf 100644 --- a/arkui-plugins/ui-plugins/property-translators/storagelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/storagelink.ts @@ -25,7 +25,7 @@ import { createSetter2, generateThisBacking, generateGetOrSetCall, - judgeIfAddWatchFunc + judgeIfAddWatchFunc, } from './utils'; import { createOptionalClassProperty } from '../utils'; @@ -98,9 +98,9 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier('StorageLinkDecoratedVariable'), arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [], - ), - ), + this.property.typeAnnotation ? [this.property.typeAnnotation] : [] + ) + ) ), args ); @@ -111,10 +111,10 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - newClass, + newClass ); } @@ -123,22 +123,22 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial newName, this.property, 'StorageLinkDecoratedVariable', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set'), + generateGetOrSetCall(thisValue, 'set') ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, this.property.typeAnnotation, - thisGet, + thisGet ); const setter: arkts.MethodDefinition = this.translateSetter( originalName, this.property.typeAnnotation, - thisSet, + thisSet ); return [field, getter, setter]; } @@ -146,7 +146,7 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial translateGetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - returnValue: arkts.Expression, + returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } @@ -154,7 +154,7 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - statement: arkts.AstNode, + statement: arkts.AstNode ): arkts.MethodDefinition { return createSetter2(originalName, typeAnnotation, statement); } diff --git a/arkui-plugins/ui-plugins/property-translators/types.ts b/arkui-plugins/ui-plugins/property-translators/types.ts index 24fc02bb3..b791a7da1 100644 --- a/arkui-plugins/ui-plugins/property-translators/types.ts +++ b/arkui-plugins/ui-plugins/property-translators/types.ts @@ -13,28 +13,22 @@ * limitations under the License. */ -import * as arkts from "@koalaui/libarkts" +import * as arkts from '@koalaui/libarkts'; export interface GetterSetter { translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.Expression ): arkts.MethodDefinition; translateSetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, + originalName: string, + typeAnnotation: arkts.TypeNode | undefined, left: arkts.MemberExpression ): arkts.MethodDefinition; } export interface InitializerConstructor { - cacheTranslatedInitializer( - newName: string, - originalName: string - ): void; - translateWithoutInitializer( - newName: string, - originalName: string - ): arkts.AstNode[]; -} \ No newline at end of file + cacheTranslatedInitializer(newName: string, originalName: string): void; + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[]; +} diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index df3f93414..595aced52 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -52,7 +52,7 @@ export function isDecoratorAnnotation(anno: arkts.AnnotationUsage, decoratorName export function hasDecorator( property: arkts.ClassProperty | arkts.ClassDefinition | arkts.MethodDefinition, - decoratorName: DecoratorNames, + decoratorName: DecoratorNames ): boolean { if (arkts.isMethodDefinition(property)) { return property.scriptFunction.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName)); @@ -66,12 +66,15 @@ export function getStateManagementType(node: arkts.ClassProperty): string { } else if (hasDecorator(node, DecoratorNames.LINK)) { return 'DecoratedV1VariableBase'; } else if (hasDecorator(node, DecoratorNames.PROP)) { - return "PropDecoratedVariable"; + return 'PropDecoratedVariable'; } else if (hasDecorator(node, DecoratorNames.STORAGE_LINK)) { - return "StorageLinkDecoratedVariable" + return 'StorageLinkDecoratedVariable'; } else if (hasDecorator(node, DecoratorNames.STORAGE_PROP)) { - return "StoragePropDecoratedVariable" - } else if (hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP) || hasDecorator(node, DecoratorNames.OBJECT_LINK)) { + return 'StoragePropDecoratedVariable'; + } else if ( + hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP) || + hasDecorator(node, DecoratorNames.OBJECT_LINK) + ) { return 'SyncedProperty'; } return 'MutableState'; @@ -80,7 +83,7 @@ export function getStateManagementType(node: arkts.ClassProperty): string { export function createGetter( name: string, type: arkts.TypeNode | undefined, - returns: arkts.Expression, + returns: arkts.Expression ): arkts.MethodDefinition { const body = arkts.factory.createBlock([arkts.factory.createReturnStatement(returns)]); @@ -88,14 +91,14 @@ export function createGetter( body, arkts.FunctionSignature.createFunctionSignature(undefined, [], type?.clone(), false), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_GETTER, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, arkts.factory.createIdentifier(name), arkts.factory.createFunctionExpression(scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false, + false ); } @@ -104,20 +107,20 @@ export function createSetter( type: arkts.TypeNode | undefined, left: arkts.Expression, right: arkts.AstNode, - needMemo: boolean = false, + needMemo: boolean = false ): arkts.MethodDefinition { const body = arkts.factory.createBlock([ arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( left, arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - right, - ), + right + ) ), ]); const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier('value', type?.clone()), - undefined, + undefined ); if (needMemo) { param.annotations = [annotation('memo')]; @@ -126,7 +129,7 @@ export function createSetter( body, arkts.FunctionSignature.createFunctionSignature(undefined, [param], undefined, false), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_SETTER, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); return arkts.factory.createMethodDefinition( @@ -134,25 +137,25 @@ export function createSetter( arkts.factory.createIdentifier(name), arkts.factory.createFunctionExpression(scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false, + false ); } export function createSetter2( name: string, type: arkts.TypeNode | undefined, - statement: arkts.AstNode, + statement: arkts.AstNode ): arkts.MethodDefinition { const body = arkts.factory.createBlock([statement]); const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier('value', type?.clone()), - undefined, + undefined ); const scriptFunction = arkts.factory.createScriptFunction( body, arkts.FunctionSignature.createFunctionSignature(undefined, [param], undefined, false), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_SETTER, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); return arkts.factory.createMethodDefinition( @@ -160,14 +163,14 @@ export function createSetter2( arkts.factory.createIdentifier(name), arkts.factory.createFunctionExpression(scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false, + false ); } export function generateThisBackingValue( name: string, optional: boolean = false, - nonNull: boolean = false, + nonNull: boolean = false ): arkts.MemberExpression { const member: arkts.Expression = generateThisBacking(name, optional, nonNull); return arkts.factory.createMemberExpression( @@ -175,21 +178,21 @@ export function generateThisBackingValue( arkts.factory.createIdentifier('value'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ); } export function generateThisBacking( name: string, optional: boolean = false, - nonNull: boolean = false, + nonNull: boolean = false ): arkts.Expression { const member: arkts.Expression = arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), arkts.factory.createIdentifier(`${name}`), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - optional, + optional ); return nonNull ? arkts.factory.createTSNonNullExpression(member) : member; } @@ -267,11 +270,11 @@ export function generateGetOrSetCall(beforCall: arkts.AstNode, type: string) { arkts.factory.createIdentifier(type), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), undefined, type === 'set' ? [arkts.factory.createIdentifier('value')] : undefined, - undefined, + undefined ); } @@ -285,19 +288,19 @@ export function generateToRecord(newName: string, originalName: string): arkts.P arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, - false, + false ), 'get', true ), arkts.ETSNewClassInstanceExpression.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('Object')), + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('Object')) ), - [], + [] ), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING, - ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ) ); } diff --git a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts index 25dc8c97e..b280b0ad5 100644 --- a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts +++ b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts @@ -48,7 +48,7 @@ function tranformPropertyMembers( if (!scope?.hasUpdateStruct) { collections.push(factory.createUpdateStruct(currentStructInfo, optionsTypeName, isDecl)); } - if ( currentStructInfo.isReusable ) { + if (currentStructInfo.isReusable) { collections.push(factory.toRecord(optionsTypeName, currentStructInfo.toRecordBody)); } return collect(...collections, ...propertyMembers); diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts index 18e9e51a1..502917ecf 100644 --- a/arkui-plugins/ui-plugins/struct-translators/utils.ts +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -32,7 +32,7 @@ export type ScopeInfo = { export function isCustomComponentClass(node: arkts.ClassDeclaration): boolean { if (!node.definition?.ident?.name) { return false; - }; + } const name: string = node.definition.ident.name; const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); return name === CustomComponentNames.COMPONENT_CLASS_NAME || structCollection.has(name); @@ -47,7 +47,7 @@ export function isCustomComponentClass(node: arkts.ClassDeclaration): boolean { export function isKnownMethodDefinition(method: arkts.MethodDefinition, name: string): boolean { if (!method || !arkts.isMethodDefinition(method)) { return false; - }; + } // For now, we only considered matched method name. const isNameMatched: boolean = method.name?.name === name; diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index 6408164b1..c73d54b14 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -30,7 +30,7 @@ export enum CustomComponentNames { REUSABLE_COMPONENT_REBIND_STATE = '__rebindStates', COMPONENT_INITIALIZERS_NAME = 'initializers', BUILDCOMPATIBLENODE = '_buildCompatibleNode', - OPTIONS = 'options' + OPTIONS = 'options', } export enum BuilderLambdaNames { @@ -53,17 +53,12 @@ export function findLocalImport( sourceName: string, importedName: string ): arkts.Identifier | undefined { - const isFromSource = ( - !!node.source - && node.source.str === sourceName - ); + const isFromSource = !!node.source && node.source.str === sourceName; if (!isFromSource) return undefined; - const importSpecifier = node.specifiers.find((spec) => ( - arkts.isImportSpecifier(spec) - && !!spec.imported - && spec.imported.name === importedName - )) as arkts.ImportSpecifier | undefined; + const importSpecifier = node.specifiers.find( + (spec) => arkts.isImportSpecifier(spec) && !!spec.imported && spec.imported.name === importedName + ) as arkts.ImportSpecifier | undefined; return importSpecifier?.local ?? importSpecifier?.imported; } @@ -95,7 +90,7 @@ export function createOptionalClassProperty( name: string, property: arkts.ClassProperty, stageManagementIdent: string, - modifiers: arkts.Es2pandaModifierFlags, + modifiers: arkts.Es2pandaModifierFlags ): arkts.ClassProperty { const newProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier(name), @@ -104,21 +99,21 @@ export function createOptionalClassProperty( ? createStageManagementType(stageManagementIdent, property) : property.typeAnnotation?.clone(), modifiers, - false, + false ); return arkts.classPropertySetOptional(newProperty, true); } export function createStageManagementType( stageManagementIdent: string, - property: arkts.ClassProperty, + property: arkts.ClassProperty ): arkts.ETSTypeReference { return arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier(stageManagementIdent), arkts.factory.createTSTypeParameterInstantiation([ property.typeAnnotation ? property.typeAnnotation.clone() : arkts.factory.createETSUndefinedType(), - ]), - ), + ]) + ) ); } -- Gitee From a472bde41e744efd73b4d815dd5a1b2af18b5bf7 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Tue, 8 Apr 2025 17:31:12 +0800 Subject: [PATCH 033/123] fix memo recache missing Signed-off-by: Jiakai Shi Change-Id: I3ed3e36f94c8015412f1a42abeffbe33d24d6770 --- .../memo-plugins/return-transformer.ts | 11 +-- arkui-plugins/memo-plugins/utils.ts | 67 ++++++++++++++----- 2 files changed, 57 insertions(+), 21 deletions(-) diff --git a/arkui-plugins/memo-plugins/return-transformer.ts b/arkui-plugins/memo-plugins/return-transformer.ts index 9714d7eb0..563d55621 100644 --- a/arkui-plugins/memo-plugins/return-transformer.ts +++ b/arkui-plugins/memo-plugins/return-transformer.ts @@ -52,10 +52,13 @@ export class ReturnTransformer extends AbstractVisitor { if (this.stableThis && node.argument && arkts.isThisExpression(node.argument)) { return factory.createReturnThis(); } - return arkts.factory.createBlock([ - arkts.factory.createExpressionStatement(factory.createRecacheCall(node.argument)), - node, - ]); + if (node.argument === undefined) { + return arkts.factory.createBlock([ + arkts.factory.createExpressionStatement(factory.createRecacheCall()), + node, + ]); + } + return arkts.factory.updateReturnStatement(node, factory.createRecacheCall(node.argument)); } return node; } diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index ae4541254..44553ed5c 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -50,10 +50,7 @@ export class PositionalIdTracker { // Set `stable` to true if you want to have more predictable values. // For example for tests. // Don't use it in production! - constructor( - public filename: string, - public stableForTests: boolean = false - ) { + constructor(public filename: string, public stableForTests: boolean = false) { if (stableForTests) PositionalIdTracker.callCount = 0; } @@ -81,7 +78,7 @@ export class PositionalIdTracker { } } -export function isMemoAnnotation(node: arkts.AnnotationUsage, memoName: RuntimeNames) { +export function isMemoAnnotation(node: arkts.AnnotationUsage, memoName: RuntimeNames): boolean { return node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === memoName; } @@ -101,7 +98,7 @@ export function hasMemoIntrinsicAnnotation(node: T): bool return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC)); } -export function hasMemoStableAnnotation(node: arkts.ClassDefinition) { +export function hasMemoStableAnnotation(node: arkts.ClassDefinition): boolean { return node.annotations.some( (it) => it.expr !== undefined && arkts.isIdentifier(it.expr) && it.expr.name === RuntimeNames.ANNOTATION_STABLE ); @@ -125,16 +122,52 @@ export function removeMemoAnnotation(node: T): T { * TODO: * @deprecated */ -export function isSyntheticReturnStatement(node: arkts.AstNode) { +export function isSyntheticReturnStatement(node: arkts.AstNode): boolean { + return isIfStatementWithSyntheticReturn(node) || isSimpleSyntheticReturn(node) || isSyntheticReturnInBlock(node); +} + +function isIfStatementWithSyntheticReturn(node: arkts.AstNode): boolean { + return ( + arkts.isIfStatement(node) && + !!node.test && + arkts.isMemberExpression(node.test) && + arkts.isIdentifier(node.test.object) && + node.test.object.name === RuntimeNames.SCOPE && + arkts.isIdentifier(node.test.property) && + node.test.property.name === RuntimeNames.INTERNAL_VALUE_OK && + (arkts.isBlockStatement(node.consequent) || arkts.isReturnStatement(node.consequent)) + ); +} + +function isSimpleSyntheticReturn(node: arkts.AstNode): boolean { + return ( + arkts.isReturnStatement(node) && + !!node.argument && + arkts.isMemberExpression(node.argument) && + arkts.isIdentifier(node.argument.object) && + node.argument.object.name === RuntimeNames.SCOPE && + arkts.isIdentifier(node.argument.property) && + node.argument.property.name === RuntimeNames.INTERNAL_VALUE + ); +} + +function isSyntheticReturnInBlock(node: arkts.AstNode): boolean { + if (!arkts.isBlockStatement(node) || node.statements.length !== 2) { + return false; + } + if (!arkts.isReturnStatement(node.statements[1])) { + return false; + } + const isReturnThis: boolean = !!node.statements[1].argument && arkts.isThisExpression(node.statements[1].argument); + const isReturnVoid: boolean = node.statements[1].argument === undefined; + return ( - (arkts.isReturnStatement(node) && - node.argument && - arkts.isMemberExpression(node.argument) && - arkts.isIdentifier(node.argument.object) && - node.argument.object.name === RuntimeNames.SCOPE && - arkts.isIdentifier(node.argument.property) && - node.argument.property.name === RuntimeNames.INTERNAL_VALUE) || - arkts.isBlockStatement(node) + arkts.isMemberExpression(node.statements[0]) && + arkts.isIdentifier(node.statements[0].object) && + node.statements[0].object.name === RuntimeNames.SCOPE && + arkts.isIdentifier(node.statements[0].property) && + node.statements[0].property.name === RuntimeNames.INTERNAL_VALUE && + (isReturnThis || isReturnVoid) ); } @@ -142,7 +175,7 @@ export function isSyntheticReturnStatement(node: arkts.AstNode) { * TODO: * @deprecated */ -export function isMemoParametersDeclaration(node: arkts.AstNode) { +export function isMemoParametersDeclaration(node: arkts.AstNode): boolean { return ( arkts.isVariableDeclaration(node) && node.declarators.every((it) => it.name.name.startsWith(RuntimeNames.PARAMETER)) @@ -152,7 +185,7 @@ export function isMemoParametersDeclaration(node: arkts.AstNode) { /** * TODO: change this to TypeNodeGetType to check void type */ -export function isVoidType(typeNode: arkts.TypeNode | undefined) { +export function isVoidType(typeNode: arkts.TypeNode | undefined): boolean { return typeNode?.dumpSrc() === 'void'; } -- Gitee From 05319ff1c8b04175ede4517c3db725e17dc8776a Mon Sep 17 00:00:00 2001 From: wangcaoyu Date: Wed, 9 Apr 2025 20:55:45 +0800 Subject: [PATCH 034/123] reset ets1.2 Signed-off-by: wangcaoyu --- BUILD.gn | 46 +++++++++++++--------------------------------- 1 file changed, 13 insertions(+), 33 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index fb218f48d..4accb34f4 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -16,11 +16,7 @@ import("//build/ohos/ace/ace.gni") import("//build/ohos_var.gni") import("//build/templates/bpf/ohos_bpf_config.gni") import("//foundation/arkui/ace_engine/ace_config.gni") -if (sdk_build_public) { - import("//out/sdk-public/public_interface/sdk-js/interface_config.gni") -} else { - import("//interface/sdk-js/interface_config.gni") -} +import("//interface/sdk-js/interface_config.gni") ets_loader_lib_dir = get_label_info(":build_ets_loader_library", "target_out_dir") + "/lib" @@ -39,6 +35,8 @@ ets_sysResource = get_label_info(":build_ets_sysResource", "target_out_dir") + "/sysResource.js" ets_loader_kit_configs_dir = get_label_info(":build_ets_loader_library", "target_out_dir") + "/kit_configs" +ets_component_dep = "//interface/sdk-js:ets_component" +ets_component_out_dir = get_label_info(ets_component_dep, "target_out_dir") action("build_ets_loader_library") { deps = [ @@ -46,12 +44,11 @@ action("build_ets_loader_library") { ":form_components", ":install_arkguard_tsc_declgen", ":server", + "//interface/sdk-js:ets_component", + "//interface/sdk-js:bundle_kits", + "//interface/sdk-js:bundle_arkts", + "//interface/sdk-js:ets_internal_api", ] - if (sdk_build_public) { - deps += [ "//out/sdk-public/public_interface/sdk-js:ets_component" ] - } else { - deps += [ "//interface/sdk-js:ets_component" ] - } script = "build_ets_loader_library.py" depfile = "$target_gen_dir/$target_name.d" outputs = [ @@ -69,22 +66,10 @@ action("build_ets_loader_library") { } else { _ace_config_dir = "//prebuilts/ace-toolkit/ets-loader/compiler" } - input_project_dir = "//interface/sdk-js" - if (sdk_build_public || product_name == "ohos-sdk") { - input_project_dir = "//out/sdk-public/public_interface/sdk-js" - } - _declarations_file_dir = - input_project_dir + "/ets/${bpf_inc_out_dir}/ets_component" - _kit_configs_file_dir = "//interface/sdk-js/kits" - _kit_apis_file_dir = "//interface/sdk-js/api" - _arkts_apis_file_dir = "//interface/sdk-js/arkts" - isPublic = "false" - if (sdk_build_public) { - _kit_configs_file_dir = "//out/sdk-public/public_interface/sdk-js/kits" - _kit_apis_file_dir = "//out/sdk-public/public_interface/sdk-js/api" - _arkts_apis_file_dir = "//out/sdk-public/public_interface/sdk-js/arkts" - isPublic = "true" - } + _declarations_file_dir = ets_component_out_dir + "/${sdk_type}/ets_component" + _kit_configs_file_dir = ets_component_out_dir + "/${sdk_type}/bundle_kits" + _kit_apis_file_dir = root_out_dir + "/ohos_declaration/${sdk_type}/ohos_declaration_ets" + _arkts_apis_file_dir = ets_component_out_dir + "/${sdk_type}/bundle_arkts" _babel_js = _ace_config_dir + "/node_modules/@babel/cli/bin/babel.js" _babel_config_js = _ace_config_dir + "/babel.config.js" @@ -148,7 +133,7 @@ action("build_ets_loader_library") { "--arkts-apis-file-dir", rebase_path(_arkts_apis_file_dir, root_build_dir), "--build-public-sdk", - isPublic, + "${sdk_build_public}", ] } @@ -338,12 +323,7 @@ ohos_copy("ets_loader_ark_codegen") { } ohos_copy("ohos_declaration_ets_ark") { - deps = [] - if (sdk_build_public) { - deps += [ "//out/sdk-public/public_interface/sdk-js:ohos_declaration_ets" ] - } else { - deps += [ "//interface/sdk-js:ohos_declaration_ets" ] - } + deps = [ "//interface/sdk-js:ohos_declaration_ets" ] sources = [ root_out_dir + "/ohos_declaration/${sdk_type}/ohos_declaration_ets" ] -- Gitee From 6334b88cedf8b28943b38d8936a888863043bfa4 Mon Sep 17 00:00:00 2001 From: longruoluo Date: Thu, 10 Apr 2025 15:11:39 +0800 Subject: [PATCH 035/123] update UI import by declgen Signed-off-by: longruoluo Change-Id: I3723c769b6561bc419e99b111744221e407b3f48 --- .../interop-plugins/arkuiImportList.ts | 176 ++++++++++++++++++ .../interop-plugins/decl_transformer.ts | 71 +++++-- arkui-plugins/interop-plugins/index.ts | 86 ++++++++- .../interop-plugins/interop_plugin.ts | 86 --------- koala-wrapper/native/src/bridges.cc | 16 ++ koala-wrapper/src/Es2pandaNativeModule.ts | 8 + .../src/arkts-api/utilities/public.ts | 11 +- 7 files changed, 351 insertions(+), 103 deletions(-) create mode 100644 arkui-plugins/interop-plugins/arkuiImportList.ts delete mode 100644 arkui-plugins/interop-plugins/interop_plugin.ts diff --git a/arkui-plugins/interop-plugins/arkuiImportList.ts b/arkui-plugins/interop-plugins/arkuiImportList.ts new file mode 100644 index 000000000..ddc19b2bd --- /dev/null +++ b/arkui-plugins/interop-plugins/arkuiImportList.ts @@ -0,0 +1,176 @@ +/* + * 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. + */ + +export const ARKUI_DECLARE_LIST: Set = new Set([ + 'AbilityComponent', + 'AlphabetIndexer', + 'AnalogClock', + 'Animator', + 'Badge', + 'Blank', + 'Button', + 'Calendar', + 'CalendarPicker', + 'Camera', + 'Canvas', + 'Checkbox', + 'CheckboxGroup', + 'Circle', + 'ColorPicker', + 'ColorPickerDialog', + 'Column', + 'ColumnSplit', + 'ContentSlot', + 'Counter', + 'DataPanel', + 'DatePicker', + 'Divider', + 'EffectComponent', + 'Ellipse', + 'EmbeddedComponent', + 'Flex', + 'FolderStack', + 'FormComponent', + 'FormLink', + 'Gauge', + 'GeometryView', + 'Grid', + 'GridItem', + 'GridContainer', + 'Hyperlink', + 'Image', + 'ImageAnimator', + 'Line', + 'LinearIndicator', + 'List', + 'ListItem', + 'ListItemGroup', + 'LoadingProgress', + 'Marquee', + 'MediaCachedImage', + 'Menu', + 'MenuItem', + 'MenuItemGroup', + 'MovingPhotoView', + 'NavDestination', + 'NavRouter', + 'Navigation', + 'Navigator', + 'NodeContainer', + 'Option', + 'PageTransitionEnter', + 'PageTransitionExit', + 'Panel', + 'Particle', + 'Path', + 'PatternLock', + 'Piece', + 'PlatformView', + 'PluginComponent', + 'Polygon', + 'Polyline', + 'Progress', + 'QRCode', + 'Radio', + 'Rating', + 'Rect', + 'Refresh', + 'RelativeContainer', + 'RemoteWindow', + 'RootScene', + 'Row', + 'RowSplit', + 'RichText', + 'Screen', + 'Scroll', + 'ScrollBar', + 'Search', + 'Section', + 'Select', + 'Shape', + 'Sheet', + 'SideBarContainer', + 'Slider', + 'Span', + 'Stack', + 'Stepper', + 'StepperItem', + 'Swiper', + 'SymbolGlyph', + 'SymbolSpan', + 'TabContent', + 'Tabs', + 'Text', + 'TextPicker', + 'TextClock', + 'TextArea', + 'TextInput', + 'TextTimer', + 'TimePicker', + 'Toggle', + 'Video', + 'Web', + 'WindowScene', + 'WithTheme', + 'XComponent', + 'GridRow', + 'GridCol', + 'WaterFlow', + 'FlowItem', + 'ImageSpan', + 'LocationButton', + 'PasteButton', + 'SaveButton', + 'UIExtensionComponent', + 'IsolatedComponent', + 'RichEditor', + 'Component3D', + 'ContainerSpan', + 'Require', + 'BuilderParam', + 'Local', + 'Param', + 'Once', + 'Event', + 'State', + 'Track', + 'Trace', + 'Prop', + 'Link', + 'ObjectLink', + 'Provide', + 'Provider', + 'Consume', + 'Consumer', + 'StorageProp', + 'StorageLink', + 'Watch', + 'LocalStorageLink', + 'LocalStorageProp', + 'Component', + 'ComponentV2', + 'Entry', + 'Observed', + 'ObservedV2', + 'Preview', + 'CustomDialog', + 'Reusable', + 'Computed', + 'Builder', + 'LocalBuilder', + 'Styles', + 'Extend', + 'AnimatableExtend' +]); \ No newline at end of file diff --git a/arkui-plugins/interop-plugins/decl_transformer.ts b/arkui-plugins/interop-plugins/decl_transformer.ts index 57cf9906d..3aee2f8f8 100644 --- a/arkui-plugins/interop-plugins/decl_transformer.ts +++ b/arkui-plugins/interop-plugins/decl_transformer.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../common/abstract-visitor'; - +import { ARKUI_DECLARE_LIST } from './arkuiImportList'; import { debugLog } from '../common/debug'; export class DeclTransformer extends AbstractVisitor { @@ -55,7 +55,6 @@ export class DeclTransformer extends AbstractVisitor { if (arkts.isEtsScript(astNode)) { astNode = this.transformImportDecl(astNode); } - const node = this.visitEachChild(astNode); if (arkts.isStructDeclaration(node)) { debugLog(`DeclTransformer:before:flag:${arkts.classDefinitionIsFromStructConst(node.definition!)}`); @@ -63,27 +62,73 @@ export class DeclTransformer extends AbstractVisitor { let newnode = this.processComponent(node); debugLog(`DeclTransformer:after:flag:${arkts.classDefinitionIsFromStructConst(newnode.definition!)}`); return newnode; + } else if (arkts.isETSImportDeclaration(astNode)) { + return this.updateImportDeclaration(astNode); + } else if (arkts.isMethodDefinition(astNode)) { + if (astNode.name?.name === 'build' ) { + return this.transformMethodDefinition(astNode); + } + return astNode; } return node; } - transformImportDecl(estNode: arkts.AstNode): arkts.AstNode { - if (!arkts.isEtsScript(estNode)) { - return estNode; + transformImportDecl(astNode: arkts.AstNode):arkts.AstNode { + if (!arkts.isEtsScript(astNode)) { + return astNode; } + let statements = astNode.statements.filter(node => this.isImportDeclarationNeedFilter(node)); + return arkts.factory.updateEtsScript(astNode, statements); + } - let statements = estNode.statements - .filter((node) => this.isImportDeclarationNeedFilter(node)) - .map((node) => this.updateImportDeclaration(node)); + transformMethodDefinition(node: arkts.MethodDefinition): arkts.AstNode { + const func: arkts.ScriptFunction = node.scriptFunction; + const isFunctionCall: boolean = false; + const typeNode: arkts.TypeNode | undefined = node.scriptFunction?.returnTypeAnnotation; + const updateFunc = arkts.factory.updateScriptFunction( + func, + !!func.body && arkts.isBlockStatement(func.body) + ? arkts.factory.updateBlock( + func.body, + func.body.statements.filter((st) => false) + ) + : undefined, + arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), + func?.flags, + func?.modifiers + ); - return arkts.factory.updateEtsScript(estNode, statements); + return arkts.factory.updateMethodDefinition( + node, + node.kind, + arkts.factory.updateIdentifier( + node.name, + node.name?.name + ), + arkts.factory.createFunctionExpression(updateFunc), + node.modifiers, + false + ); } - - isImportDeclarationNeedFilter(astNode: arkts.AstNode): boolean { - return !arkts.isETSImportDeclaration(astNode); + + isImportDeclarationNeedFilter(astNode: arkts.AstNode):boolean { + if (!arkts.isETSImportDeclaration(astNode)) { + return true; + } + return astNode?.source?.str !== '@global.arkui'; } - updateImportDeclaration(astNode: arkts.AstNode): arkts.AstNode { + updateImportDeclaration(astNode: arkts.AstNode):arkts.AstNode { + if (!arkts.isETSImportDeclaration(astNode) || astNode?.source?.str !== '@ohos.arkui.component') { + return astNode; + } + astNode.specifiers.forEach((element) => { + if (arkts.isImportSpecifier(element)) { + if (ARKUI_DECLARE_LIST.has(element.imported?.name as string)) { + arkts.ImportSpecifierSetRemovable(element); + } + } + }); return astNode; } } diff --git a/arkui-plugins/interop-plugins/index.ts b/arkui-plugins/interop-plugins/index.ts index bac3e903b..404892c34 100644 --- a/arkui-plugins/interop-plugins/index.ts +++ b/arkui-plugins/interop-plugins/index.ts @@ -13,8 +13,88 @@ * limitations under the License. */ -import { interopPlugin } from './interop_plugin'; +import * as arkts from '@koalaui/libarkts'; -export function interopTransform() { - return interopPlugin; +import { DeclTransformer } from './decl_transformer'; +import { EmitTransformer } from './emit_transformer'; + +import { ProgramVisitor } from '../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; +import { debugLog } from '../common/debug'; +import { PluginContext, Plugins } from 'common/plugin-context'; + +export function interopTransform():Plugins { + return { + name: 'interop-plugin', + parsed: parsedTransform, + checked: checkedTransform, + clean() { + arkts.arktsGlobal.clearContext(); + }, + }; +} + +function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + debugLog('interopTransform:parsed'); + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + + if (script) { + const declTransformer = new DeclTransformer({ + arkui: '@koalaui.arkts-arkui.StructParse' as interop.TransfromerName + }); + + const programVisitor = new ProgramVisitor({ + pluginName: interopTransform().name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + visitors: [declTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this as unknown as PluginContext + }); + + program = programVisitor.programVisitor(program); + script = program.astNode; + this.setArkTSAst(script); + debugLog('interopTransform:parsed exit'); + return script; + } + } + debugLog('interopTransform: parsed exit with no transform'); + return script; +} + +function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + debugLog('interopTransform:checked'); + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + if (script) { + const emitTransformer = new EmitTransformer({ + arkui: '@koalaui.arkts-arkui.EmitBase' as interop.TransfromerName + }); + + const programVisitor = new ProgramVisitor({ + pluginName: interopTransform().name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [emitTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this as unknown as PluginContext + }); + + program = programVisitor.programVisitor(program); + script = program.astNode; + arkts.GlobalInfo.getInfoInstance()?.reset(); + arkts.recheckSubtree(script); + this.setArkTSAst(script); + debugLog('interopTransform:checked exit'); + return script; + } + } + debugLog('interopTransform:checked exit with no transform'); + return script; } diff --git a/arkui-plugins/interop-plugins/interop_plugin.ts b/arkui-plugins/interop-plugins/interop_plugin.ts deleted file mode 100644 index e0ef5ddec..000000000 --- a/arkui-plugins/interop-plugins/interop_plugin.ts +++ /dev/null @@ -1,86 +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. - */ - -import * as arkts from '@koalaui/libarkts'; - -import { DeclTransformer } from './decl_transformer'; -import { EmitTransformer } from './emit_transformer'; -import { ProgramVisitor } from '../common/program-visitor'; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; - -import { debugLog } from '../common/debug'; - -export const interopPlugin: interop.Plugin = { - name: 'interop-plugin', - parsed(this: interop.PluginContext) { - debugLog('interopTransform:parsed'); - let node = this.getArkTSAst(); - - if (node) { - debugLog('interopTransform:parsed:before:source: ', node.dumpSrc()); - debugLog('interopTransform:parsed:before:ast: ', node.dumpJson()); - - let script: arkts.EtsScript = node as arkts.EtsScript; - - const declTransformer = new DeclTransformer({ - arkui: '@koalaui.arkts-arkui.StructParse' as interop.TransfromerName, - }); - - const programVisitor = new ProgramVisitor({ - pluginName: 'decl', - state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, - visitors: [declTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - }); - - script = programVisitor.visitor(script); - - debugLog('interopTransform:parsed:after:source: ', script.dumpSrc()); - debugLog('interopTransform:parsed:after:ast: ', script.dumpJson()); - - this.setArkTSAst(script); - return script as interop.EtsScript; - } - }, - checked(this: interop.PluginContext) { - debugLog('interopTransform:checked'); - let node = this.getArkTSAst(); - if (node) { - debugLog('interopTransform:checked:before:source: ', node.dumpSrc()); - debugLog('interopTransform:parsed:before:ast: ', node.dumpJson()); - - let script: arkts.EtsScript = node as arkts.EtsScript; - - const emitTransformer = new EmitTransformer({ - arkui: '@koalaui.arkts-arkui.EmitBase' as interop.TransfromerName, - }); - - const programVisitor = new ProgramVisitor({ - pluginName: 'emit', - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [emitTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - }); - - // script = programVisitor.visitor(script); - - debugLog('interopTransform:checked:after:source: ', script.dumpSrc()); - debugLog('interopTransform:checked:after:ast: ', script.dumpJson()); - - this.setArkTSAst(script); - return script as interop.EtsScript; - } - }, -}; diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index 5c177990e..3649b2858 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -31,6 +31,22 @@ void impl_ClassDefinitionSetFromStructModifier(KNativePointer contextPtr, KNativ } KOALA_INTEROP_V2(ClassDefinitionSetFromStructModifier, KNativePointer, KNativePointer); +KBoolean impl_ImportSpecifierIsRemovableConst(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(instancePtr); + return GetImpl()->ImportSpecifierIsRemovableConst(context, node); +} +KOALA_INTEROP_2(ImportSpecifierIsRemovableConst, KBoolean, KNativePointer, KNativePointer); + +void impl_ImportSpecifierSetRemovable(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(instancePtr); + return GetImpl()->ImportSpecifierSetRemovable(context, node, true); +} +KOALA_INTEROP_V2(ImportSpecifierSetRemovable, KNativePointer, KNativePointer); + KNativePointer impl_AstNodeRecheck(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 3f271657a..8d2fdd7bb 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -794,6 +794,14 @@ export class Es2pandaNativeModule { _ETSParserGetGlobalProgramAbsName(context: KNativePointer): KNativePointer { throw new Error('Not implemented'); } + + _ImportSpecifierIsRemovableConst(context: KNativePointer, instance: KNativePointer): KBoolean { + throw new Error('Not implemented'); + } + + _ImportSpecifierSetRemovable(context: KNativePointer, instance: KNativePointer): void { + throw new Error('Not implemented'); + } } export function initEs2panda(): Es2pandaNativeModule { diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index dc96b3865..32d33dbf0 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -20,9 +20,10 @@ import { passNode, passString, unpackNodeArray, unpackNonNullableNode } from "./ import { isFunctionDeclaration, isMemberExpression } from "../factory/nodeTests" import { Es2pandaContextState, Es2pandaModifierFlags } from "../../generated/Es2pandaEnums" import type { AstNode } from "../peers/AstNode" -import { ClassDefinition, ClassProperty, ETSImportDeclaration, isClassDefinition, isScriptFunction, type AnnotationUsage } from "../../generated" +import { ClassDefinition, ClassProperty, ETSImportDeclaration, ImportSpecifier, isClassDefinition, isScriptFunction, type AnnotationUsage } from "../../generated" import { Program } from "../peers/Program" + export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { console.log("[TS WRAPPER] PROCEED TO STATE: ", getEnumName(Es2pandaContextState, state)); if (state <= global.es2panda._ContextState(global.context)) { @@ -103,6 +104,14 @@ export function classDefinitionIsFromStructConst(node: ClassDefinition): boolean return global.es2panda._ClassDefinitionIsFromStructConst(global.context, node.peer); } +export function ImportSpecifierSetRemovable(node: ImportSpecifier): void { + global.es2panda._ImportSpecifierSetRemovable(global.context, node.peer); +} + +export function ImportSpecifierIsRemovableConst(node: ImportSpecifier): boolean { + return global.es2panda._ImportSpecifierIsRemovableConst(global.context, node.peer); +} + // TODO: It seems like Definition overrides AstNode modifiers // with it's own modifiers which is completely unrelated set of flags. // Use this function if you need -- Gitee From 9f5e79a1e1412e41aaae8d408116ff09580a5166 Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Thu, 10 Apr 2025 10:59:18 +0800 Subject: [PATCH 036/123] fix createImportDeclaration Signed-off-by: fengyuxin Change-Id: I5cbba10a7605c821ef6506a8dbf1db9f1fda316b --- arkui-plugins/memo-plugins/memo-factory.ts | 4 +++- .../ui-plugins/preprocessor-transform.ts | 10 +++++++--- arkui-plugins/ui-plugins/ui-factory.ts | 4 +++- koala-wrapper/native/src/bridges.cc | 20 ++++++++++++++++++- koala-wrapper/native/src/generated/bridges.cc | 12 ----------- koala-wrapper/src/Es2pandaEnums.ts | 6 ++++++ koala-wrapper/src/Es2pandaNativeModule.ts | 12 ++++++----- .../src/generated/Es2pandaNativeModule.ts | 3 --- .../generated/peers/ETSImportDeclaration.ts | 5 +++-- 9 files changed, 48 insertions(+), 28 deletions(-) diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index 9cef81c70..35a1e92d4 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -39,7 +39,9 @@ export class factory { const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, [factory.createContextTypeImportSpecifier(), factory.createIdTypeImportSpecifier()], - arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE + arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE, + program!, + arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE ); // Insert this import at the top of the script's statements. if (!program) { diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 394b2327b..b69bca6b8 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -119,12 +119,14 @@ export class PreprocessorTransformer extends AbstractVisitor { this.localComponentNames.push(item.local?.name ?? importName); } - if (structCollection.has(importName) && this.isExternal === false) { + if (structCollection.has(importName)) { const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + importName; const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( node.source?.clone(), [factory.createAdditionalImportSpecifier(interfaceName, interfaceName)], - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, + this.program!, + arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE ); this.structInterfaceImport.push(newImport); } else { @@ -222,7 +224,9 @@ export class PreprocessorTransformer extends AbstractVisitor { const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( arkts.factory.create1StringLiteral(source), [factory.createAdditionalImportSpecifier(item, item)], - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, + this.program!, + arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE ); arkts.importDeclarationInsert(newImport, this.program!); }); diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index 3c0c59e6b..bc2ede8ea 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -156,7 +156,9 @@ export class factory { const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, [arkts.factory.createImportSpecifier(imported, local)], - importKind + importKind, + program, + arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE ); arkts.importDeclarationInsert(importDecl, program); return; diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index 5c177990e..25d477fb2 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -370,4 +370,22 @@ KNativePointer impl_ETSParserGetGlobalProgramAbsName(KNativePointer contextPtr) auto result = GetImpl()->ETSParserGetGlobalProgramAbsName(context); return new std::string(result); } -KOALA_INTEROP_1(ETSParserGetGlobalProgramAbsName, KNativePointer, KNativePointer) \ No newline at end of file +KOALA_INTEROP_1(ETSParserGetGlobalProgramAbsName, KNativePointer, KNativePointer) + +KNativePointer impl_CreateETSImportDeclaration(KNativePointer context, KNativePointer source, + KNativePointerArray specifiers, KUInt specifiersSequenceLength, + KInt importKind, KNativePointer programPtr, KInt flags) +{ + const auto _context = reinterpret_cast(context); + const auto _source = reinterpret_cast(source); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + const auto _importKind = static_cast(importKind); + const auto _program = reinterpret_cast(programPtr); + const auto _flags = static_cast(flags); + auto result = GetImpl()->ETSParserBuildImportDeclaration(_context, _importKind, _specifiers, + _specifiersSequenceLength, _source, _program, _flags); + return result; +} +KOALA_INTEROP_7(CreateETSImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, + KUInt, KInt, KNativePointer, KInt); diff --git a/koala-wrapper/native/src/generated/bridges.cc b/koala-wrapper/native/src/generated/bridges.cc index f1ca609eb..5c5f52f85 100644 --- a/koala-wrapper/native/src/generated/bridges.cc +++ b/koala-wrapper/native/src/generated/bridges.cc @@ -6731,18 +6731,6 @@ KNativePointer impl_UpdateETSPackageDeclaration(KNativePointer context, KNativeP } KOALA_INTEROP_3(UpdateETSPackageDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer); -KNativePointer impl_CreateETSImportDeclaration(KNativePointer context, KNativePointer source , KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind) -{ - const auto _context = reinterpret_cast(context); - const auto _source = reinterpret_cast(source); - const auto _specifiers = reinterpret_cast(specifiers); - const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); - const auto _importKind = static_cast(importKind); - auto result = GetImpl()->ETSParserBuildImportDeclaration(_context, _importKind, _specifiers, _specifiersSequenceLength, _source); - return result; -} -KOALA_INTEROP_5(CreateETSImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt); - KNativePointer impl_UpdateETSImportDeclaration(KNativePointer context, KNativePointer original, KNativePointer source, KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind) { const auto _context = reinterpret_cast(context); diff --git a/koala-wrapper/src/Es2pandaEnums.ts b/koala-wrapper/src/Es2pandaEnums.ts index bf820a759..cb9c7c2e6 100644 --- a/koala-wrapper/src/Es2pandaEnums.ts +++ b/koala-wrapper/src/Es2pandaEnums.ts @@ -182,3 +182,9 @@ export enum Es2pandaAstNodeType { AST_NODE_TYPE_SPREAD_ELEMENT, AST_NODE_TYPE_REST_ELEMENT, } + +export enum Es2pandaImportFlags { + IMPORT_FLAGS_NONE, + IMPORT_FLAGS_DEFAULT_IMPORT, + IMPORT_FLAGS_IMPLICIT_PACKAGE_IMPORT, +} diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 3f271657a..2b6ea4223 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -288,11 +288,13 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } _CreateETSImportDeclaration( - context: KPtr, - source: KPtr, - specifiers: KPtrArray, - specifiersLen: KInt, - importKind: KInt + context: KNativePointer, + importPath: KNativePointer, + specifiers: BigUint64Array, + specifiersSequenceLength: KInt, + importKind: KInt, + programPtr: KNativePointer, + flags: KInt ): KNativePointer { throw new Error('Not implemented'); } diff --git a/koala-wrapper/src/generated/Es2pandaNativeModule.ts b/koala-wrapper/src/generated/Es2pandaNativeModule.ts index 51040c02b..a918a0f74 100644 --- a/koala-wrapper/src/generated/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/generated/Es2pandaNativeModule.ts @@ -2143,9 +2143,6 @@ export class Es2pandaNativeModule { _UpdateETSPackageDeclaration(context: KNativePointer, original: KNativePointer, name: KNativePointer): KNativePointer { throw new Error("'UpdateETSPackageDeclaration was not overloaded by native module initialization") } - _CreateETSImportDeclaration(context: KNativePointer, importPath: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt, importKind: KInt): KNativePointer { - throw new Error("'CreateETSImportDeclaration was not overloaded by native module initialization") - } _UpdateETSImportDeclaration(context: KNativePointer, original: KNativePointer, source: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt, importKind: KInt): KNativePointer { throw new Error("'UpdateETSImportDeclaration was not overloaded by native module initialization") } diff --git a/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts b/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts index 9261c82c6..3c275809b 100644 --- a/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts @@ -33,14 +33,15 @@ import { ImportDeclaration } from "./ImportDeclaration" import { ImportSource } from "./ImportSource" import { Es2pandaImportKinds } from "./../Es2pandaEnums" import { StringLiteral } from "./StringLiteral" +import { Es2pandaImportFlags } from "./../../Es2pandaEnums" export class ETSImportDeclaration extends ImportDeclaration { constructor(pointer: KNativePointer) { assertValidPeer(pointer, 79) super(pointer) } - static createETSImportDeclaration(source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds): ETSImportDeclaration { - return new ETSImportDeclaration(global.generatedEs2panda._CreateETSImportDeclaration(global.context, passNode(source), passNodeArray(specifiers), specifiers.length, importKind)) + static createETSImportDeclaration(source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds, program: ArktsObject, flags: Es2pandaImportFlags): ETSImportDeclaration { + return new ETSImportDeclaration(global.es2panda._CreateETSImportDeclaration(global.context, passNode(source), passNodeArray(specifiers), specifiers.length, importKind, passNode(program), flags)) } static updateETSImportDeclaration(original: ETSImportDeclaration | undefined, source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds): ETSImportDeclaration { return new ETSImportDeclaration(global.generatedEs2panda._UpdateETSImportDeclaration(global.context, passNode(original), passNode(source), passNodeArray(specifiers), specifiers.length, importKind)) -- Gitee From 0f351914a80f88de57abbd347fe5925c14d5e0aa Mon Sep 17 00:00:00 2001 From: oh_ci Date: Fri, 11 Apr 2025 09:00:13 +0000 Subject: [PATCH 037/123] =?UTF-8?q?=E5=9B=9E=E9=80=80=20'Pull=20Request=20?= =?UTF-8?q?!4460=20:=20reset=20ets1.2'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BUILD.gn | 46 +++++++++++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 13 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 4accb34f4..fb218f48d 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -16,7 +16,11 @@ import("//build/ohos/ace/ace.gni") import("//build/ohos_var.gni") import("//build/templates/bpf/ohos_bpf_config.gni") import("//foundation/arkui/ace_engine/ace_config.gni") -import("//interface/sdk-js/interface_config.gni") +if (sdk_build_public) { + import("//out/sdk-public/public_interface/sdk-js/interface_config.gni") +} else { + import("//interface/sdk-js/interface_config.gni") +} ets_loader_lib_dir = get_label_info(":build_ets_loader_library", "target_out_dir") + "/lib" @@ -35,8 +39,6 @@ ets_sysResource = get_label_info(":build_ets_sysResource", "target_out_dir") + "/sysResource.js" ets_loader_kit_configs_dir = get_label_info(":build_ets_loader_library", "target_out_dir") + "/kit_configs" -ets_component_dep = "//interface/sdk-js:ets_component" -ets_component_out_dir = get_label_info(ets_component_dep, "target_out_dir") action("build_ets_loader_library") { deps = [ @@ -44,11 +46,12 @@ action("build_ets_loader_library") { ":form_components", ":install_arkguard_tsc_declgen", ":server", - "//interface/sdk-js:ets_component", - "//interface/sdk-js:bundle_kits", - "//interface/sdk-js:bundle_arkts", - "//interface/sdk-js:ets_internal_api", ] + if (sdk_build_public) { + deps += [ "//out/sdk-public/public_interface/sdk-js:ets_component" ] + } else { + deps += [ "//interface/sdk-js:ets_component" ] + } script = "build_ets_loader_library.py" depfile = "$target_gen_dir/$target_name.d" outputs = [ @@ -66,10 +69,22 @@ action("build_ets_loader_library") { } else { _ace_config_dir = "//prebuilts/ace-toolkit/ets-loader/compiler" } - _declarations_file_dir = ets_component_out_dir + "/${sdk_type}/ets_component" - _kit_configs_file_dir = ets_component_out_dir + "/${sdk_type}/bundle_kits" - _kit_apis_file_dir = root_out_dir + "/ohos_declaration/${sdk_type}/ohos_declaration_ets" - _arkts_apis_file_dir = ets_component_out_dir + "/${sdk_type}/bundle_arkts" + input_project_dir = "//interface/sdk-js" + if (sdk_build_public || product_name == "ohos-sdk") { + input_project_dir = "//out/sdk-public/public_interface/sdk-js" + } + _declarations_file_dir = + input_project_dir + "/ets/${bpf_inc_out_dir}/ets_component" + _kit_configs_file_dir = "//interface/sdk-js/kits" + _kit_apis_file_dir = "//interface/sdk-js/api" + _arkts_apis_file_dir = "//interface/sdk-js/arkts" + isPublic = "false" + if (sdk_build_public) { + _kit_configs_file_dir = "//out/sdk-public/public_interface/sdk-js/kits" + _kit_apis_file_dir = "//out/sdk-public/public_interface/sdk-js/api" + _arkts_apis_file_dir = "//out/sdk-public/public_interface/sdk-js/arkts" + isPublic = "true" + } _babel_js = _ace_config_dir + "/node_modules/@babel/cli/bin/babel.js" _babel_config_js = _ace_config_dir + "/babel.config.js" @@ -133,7 +148,7 @@ action("build_ets_loader_library") { "--arkts-apis-file-dir", rebase_path(_arkts_apis_file_dir, root_build_dir), "--build-public-sdk", - "${sdk_build_public}", + isPublic, ] } @@ -323,7 +338,12 @@ ohos_copy("ets_loader_ark_codegen") { } ohos_copy("ohos_declaration_ets_ark") { - deps = [ "//interface/sdk-js:ohos_declaration_ets" ] + deps = [] + if (sdk_build_public) { + deps += [ "//out/sdk-public/public_interface/sdk-js:ohos_declaration_ets" ] + } else { + deps += [ "//interface/sdk-js:ohos_declaration_ets" ] + } sources = [ root_out_dir + "/ohos_declaration/${sdk_type}/ohos_declaration_ets" ] -- Gitee From 8ef1303086891e9318179b692d43f636f08c7131 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Fri, 11 Apr 2025 18:08:09 +0800 Subject: [PATCH 038/123] change traversal order Signed-off-by: y00896775 Change-Id: I1351a05224fa9053355e06ee826b0abb20e2b840 --- .../ui-plugins/checked-transformer.ts | 24 ++++++------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index e544623b2..e23a7f260 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -86,19 +86,15 @@ export class CheckedTransformer extends AbstractVisitor { } } - visitEachChild(node: arkts.AstNode): arkts.AstNode { - if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { - return node; - } - if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { - return node; - } - - return super.visitEachChild(node); - } - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { this.enter(beforeChildren); + if (arkts.isCallExpression(beforeChildren) && isBuilderLambda(beforeChildren, this.isExternal)) { + const lambda = transformBuilderLambda(beforeChildren, this.isExternal); + return this.visitEachChild(lambda); + } else if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren, this.isExternal)) { + const lambda = transformBuilderLambdaMethodDecl(beforeChildren); + return this.visitEachChild(lambda); + } const node = this.visitEachChild(beforeChildren); if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { let scope: ScopeInfo | undefined; @@ -119,12 +115,6 @@ export class CheckedTransformer extends AbstractVisitor { return transformEtsGlobalClassMembers(node); } else if (arkts.isCallExpression(node) && isReourceNode(node)) { return transformResource(node, this.projectConfig); - } else if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { - const lambda = transformBuilderLambda(node, this.isExternal); - return lambda; - } else if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { - const lambda = transformBuilderLambdaMethodDecl(node); - return lambda; } return node; } -- Gitee From c30dfeb51c224d03b3275da959e149edac844a1b Mon Sep 17 00:00:00 2001 From: wangcaoyu Date: Wed, 9 Apr 2025 20:55:45 +0800 Subject: [PATCH 039/123] reset ets1.2 Signed-off-by: wangcaoyu --- BUILD.gn | 46 +++++++++++++--------------------------------- 1 file changed, 13 insertions(+), 33 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index fb218f48d..4accb34f4 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -16,11 +16,7 @@ import("//build/ohos/ace/ace.gni") import("//build/ohos_var.gni") import("//build/templates/bpf/ohos_bpf_config.gni") import("//foundation/arkui/ace_engine/ace_config.gni") -if (sdk_build_public) { - import("//out/sdk-public/public_interface/sdk-js/interface_config.gni") -} else { - import("//interface/sdk-js/interface_config.gni") -} +import("//interface/sdk-js/interface_config.gni") ets_loader_lib_dir = get_label_info(":build_ets_loader_library", "target_out_dir") + "/lib" @@ -39,6 +35,8 @@ ets_sysResource = get_label_info(":build_ets_sysResource", "target_out_dir") + "/sysResource.js" ets_loader_kit_configs_dir = get_label_info(":build_ets_loader_library", "target_out_dir") + "/kit_configs" +ets_component_dep = "//interface/sdk-js:ets_component" +ets_component_out_dir = get_label_info(ets_component_dep, "target_out_dir") action("build_ets_loader_library") { deps = [ @@ -46,12 +44,11 @@ action("build_ets_loader_library") { ":form_components", ":install_arkguard_tsc_declgen", ":server", + "//interface/sdk-js:ets_component", + "//interface/sdk-js:bundle_kits", + "//interface/sdk-js:bundle_arkts", + "//interface/sdk-js:ets_internal_api", ] - if (sdk_build_public) { - deps += [ "//out/sdk-public/public_interface/sdk-js:ets_component" ] - } else { - deps += [ "//interface/sdk-js:ets_component" ] - } script = "build_ets_loader_library.py" depfile = "$target_gen_dir/$target_name.d" outputs = [ @@ -69,22 +66,10 @@ action("build_ets_loader_library") { } else { _ace_config_dir = "//prebuilts/ace-toolkit/ets-loader/compiler" } - input_project_dir = "//interface/sdk-js" - if (sdk_build_public || product_name == "ohos-sdk") { - input_project_dir = "//out/sdk-public/public_interface/sdk-js" - } - _declarations_file_dir = - input_project_dir + "/ets/${bpf_inc_out_dir}/ets_component" - _kit_configs_file_dir = "//interface/sdk-js/kits" - _kit_apis_file_dir = "//interface/sdk-js/api" - _arkts_apis_file_dir = "//interface/sdk-js/arkts" - isPublic = "false" - if (sdk_build_public) { - _kit_configs_file_dir = "//out/sdk-public/public_interface/sdk-js/kits" - _kit_apis_file_dir = "//out/sdk-public/public_interface/sdk-js/api" - _arkts_apis_file_dir = "//out/sdk-public/public_interface/sdk-js/arkts" - isPublic = "true" - } + _declarations_file_dir = ets_component_out_dir + "/${sdk_type}/ets_component" + _kit_configs_file_dir = ets_component_out_dir + "/${sdk_type}/bundle_kits" + _kit_apis_file_dir = root_out_dir + "/ohos_declaration/${sdk_type}/ohos_declaration_ets" + _arkts_apis_file_dir = ets_component_out_dir + "/${sdk_type}/bundle_arkts" _babel_js = _ace_config_dir + "/node_modules/@babel/cli/bin/babel.js" _babel_config_js = _ace_config_dir + "/babel.config.js" @@ -148,7 +133,7 @@ action("build_ets_loader_library") { "--arkts-apis-file-dir", rebase_path(_arkts_apis_file_dir, root_build_dir), "--build-public-sdk", - isPublic, + "${sdk_build_public}", ] } @@ -338,12 +323,7 @@ ohos_copy("ets_loader_ark_codegen") { } ohos_copy("ohos_declaration_ets_ark") { - deps = [] - if (sdk_build_public) { - deps += [ "//out/sdk-public/public_interface/sdk-js:ohos_declaration_ets" ] - } else { - deps += [ "//interface/sdk-js:ohos_declaration_ets" ] - } + deps = [ "//interface/sdk-js:ohos_declaration_ets" ] sources = [ root_out_dir + "/ohos_declaration/${sdk_type}/ohos_declaration_ets" ] -- Gitee From 92ab6f4cd99af636350af48493af9e7341371458 Mon Sep 17 00:00:00 2001 From: l00913061 Date: Thu, 10 Apr 2025 21:24:49 +0800 Subject: [PATCH 040/123] 1.2call1.1struct Signed-off-by: l00913061 Change-Id: I90edfe7566e923f0254a516029e1cc3e318fb21f --- .gitee/CODEOWNERS | 3 + arkui-plugins/common/predefines.ts | 10 +- arkui-plugins/common/program-visitor.ts | 170 ++++++++---- .../test/demo/localtest/entry/new.ets | 3 +- .../ui-plugins/component-transformer.ts | 53 +++- arkui-plugins/ui-plugins/interop.ts | 254 ++++++++++++++++++ .../ui-plugins/legacy-transformer.ts | 133 +++++++++ 7 files changed, 576 insertions(+), 50 deletions(-) create mode 100644 arkui-plugins/ui-plugins/interop.ts create mode 100644 arkui-plugins/ui-plugins/legacy-transformer.ts diff --git a/.gitee/CODEOWNERS b/.gitee/CODEOWNERS index d0600cc8d..3a02023a8 100755 --- a/.gitee/CODEOWNERS +++ b/.gitee/CODEOWNERS @@ -26,6 +26,9 @@ compiler/test/ut/ @lixingchi1 compiler/test/utForPartialUpdate/ @lixingchi1 compiler/test/utForValidate/ @lixingchi1 compiler/test/transform_ut/ @lixingchi1 +koala-wrapper/native/src/bridges.cc @keerecles +koala-wrapper/native/src/common.cc @keerecles +koala-wrapper/native/src/generated/bridges.cc @keerecles # Code owners for ArkCompiler ace_ets2bundle diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 08ce2babe..7e705f511 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -86,5 +86,13 @@ export const OUTPUT_DEPENDENCY_MAP: Map = new Map; private pluginContext?: PluginContext; + private legacyModuleList: string[] = []; + private legacyStructMap: Map; constructor(options: ProgramVisitorOptions) { super(options); @@ -94,55 +102,86 @@ export class ProgramVisitor extends AbstractVisitor { this.hooks = options.hooks; this.filenames = new Map(); this.pluginContext = options.pluginContext; + this.legacyModuleList = []; + this.legacyStructMap = new Map(); } reset(): void { super.reset(); this.filenames = new Map(); + this.legacyStructMap = new Map(); + this.legacyModuleList = []; + } + + getLegacyModule(): void { + const moduleList = this.pluginContext?.getProjectConfig()?.dependentModuleList; + if (moduleList === undefined) { + return; + } + for (const module of moduleList) { + const language = module.language; + const moduleName = module.moduleName; + if (language !== ARKTS_1_1) { + continue; + } + if (!this.legacyStructMap.has(moduleName)) { + this.legacyStructMap.set(moduleName, {}); + this.legacyModuleList.push(moduleName); + } + } + } + + dumpHeaders( + currProgram: arkts.Program, + name: string, + cachePath: string | undefined, + prefixName: string, + extensionName: string + ): void { + debugDump( + currProgram.astNode.dumpSrc(), + getDumpFileName(this.state, prefixName, undefined, name), + true, + cachePath, + extensionName + ); } programVisitor(program: arkts.Program): arkts.Program { const skipPrefixes: (string | RegExp)[] = this.skipPrefixNames; - const visited = new Set(); const queue: arkts.Program[] = [program]; - + this.getLegacyModule(); while (queue.length > 0) { const currProgram = queue.shift()!; if (visited.has(currProgram.peer)) { continue; } - if (currProgram.peer !== program.peer) { const name: string = this.filenames.get(currProgram.peer)!; const cachePath: string | undefined = this.pluginContext?.getProjectConfig()?.cachePath; - debugDump( - currProgram.astNode.dumpSrc(), - getDumpFileName(this.state, 'ORI', undefined, name), - true, - cachePath, - program.programFileNameWithExtension - ); - const script = this.visitor(currProgram.astNode, currProgram, name); - if (script) { - debugDump( - script.dumpSrc(), - getDumpFileName(this.state, this.pluginName, undefined, name), - true, - cachePath, - program.programFileNameWithExtension - ); + if (this.legacyModuleList && matchPrefix(this.legacyModuleList, name)) { + if (this.state === arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) { + const structList = this.visitorLegacy(currProgram.astNode, currProgram, name); + const moduleName = name.split('/')[0]; + const structMap = this.legacyStructMap.get(moduleName)!; + for (const struct of structList) { + structMap[struct] = name; + } + } + } else { + this.dumpHeaders(currProgram, name, cachePath, 'Ori', program.programFileNameWithExtension); + const script = this.visitor(currProgram.astNode, currProgram, name); + if (script) { + this.dumpHeaders(currProgram, name, cachePath, this.pluginName, program.programFileNameWithExtension); + } } } - visited.add(currProgram.peer); - for (const externalSource of sortExternalSources(currProgram.externalSources)) { - // TODO: this is very time-consuming... if (matchPrefix(skipPrefixes, externalSource.getName())) { continue; } - const nextProgramArr: arkts.Program[] = externalSource.programs ?? []; for (const nextProgram of nextProgramArr) { this.filenames.set(nextProgram.peer, externalSource.getName()); @@ -152,38 +191,76 @@ export class ProgramVisitor extends AbstractVisitor { } } } - + const hasLegacy = this.legacyStructMap.size ? true : false; let programScript = program.astNode; - programScript = this.visitor(programScript, program, this.externalSourceName); - + programScript = this.visitor(programScript, program, this.externalSourceName, hasLegacy); const visitorsToReset = flattenVisitorsInHooks(this.hooks, this.state); visitorsToReset.forEach((visitor) => visitor.reset()); - return program; } - visitor(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): arkts.EtsScript { - let hook: ProgramHookLifeCycle | undefined; - - let script: arkts.EtsScript = node as arkts.EtsScript; - let count: number = 0; + preVisitor( + node: arkts.AstNode, + program?: arkts.Program, + externalSourceName?: string + ): void { const isExternal: boolean = !!externalSourceName; + let hook: ProgramHookLifeCycle | undefined = isExternal ? this.hooks?.external : this.hooks?.source; + let script: arkts.EtsScript = node as arkts.EtsScript; - // pre-run visitors - hook = isExternal ? this.hooks?.external : this.hooks?.source; const preVisitors = hook?.pre?.visitors ?? []; for (const transformer of preVisitors) { transformer.isExternal = isExternal; transformer.externalSourceName = externalSourceName; transformer.program = program; transformer.visitor(script); - if (!this.hooks?.external?.pre?.resetAfter) transformer.reset(); + if (!this.hooks?.external?.pre?.resetAfter) { + transformer.reset(); + } + } + } + + postVisitor( + node: arkts.AstNode, + program?: arkts.Program, + externalSourceName?: string + ): void { + const isExternal: boolean = !!externalSourceName; + let hook: ProgramHookLifeCycle | undefined = isExternal ? this.hooks?.external : this.hooks?.source; + let script: arkts.EtsScript = node as arkts.EtsScript; + + const postVisitors = hook?.post?.visitors ?? []; + for (const transformer of postVisitors) { + transformer.isExternal = isExternal; + transformer.externalSourceName = externalSourceName; + transformer.program = program; + transformer.visitor(script); + if (!this.hooks?.external?.pre?.resetAfter) { + transformer.reset(); + } } + } + + visitor( + node: arkts.AstNode, + program?: arkts.Program, + externalSourceName?: string, + hasLegacy: boolean = false + ): arkts.EtsScript { + let script: arkts.EtsScript = node as arkts.EtsScript; + let count: number = 0; + const isExternal: boolean = !!externalSourceName; + + // pre-run visitors + this.preVisitor(node, program, externalSourceName); for (const transformer of this.visitors) { transformer.isExternal = isExternal; transformer.externalSourceName = externalSourceName; transformer.program = program; + if (hasLegacy && transformer instanceof ComponentTransformer) { + transformer.registerMap(this.legacyStructMap); + } script = transformer.visitor(script) as arkts.EtsScript; transformer.reset(); arkts.setAllParents(script); @@ -200,16 +277,19 @@ export class ProgramVisitor extends AbstractVisitor { } // post-run visitors - hook = isExternal ? this.hooks?.external : this.hooks?.source; - const postVisitors = hook?.post?.visitors ?? []; - for (const transformer of postVisitors) { - transformer.isExternal = isExternal; - transformer.externalSourceName = externalSourceName; - transformer.program = program; - transformer.visitor(script); - if (!this.hooks?.external?.pre?.resetAfter) transformer.reset(); - } + this.postVisitor(node, program, externalSourceName); return script; } + + visitorLegacy( + node: arkts.AstNode, + program?: arkts.Program, + externalSourceName?: string, + ): string[] { + const visitor = new LegacyTransformer(); + const script = visitor.visitor(node) as arkts.EtsScript; + const structList = visitor.getList(); + return structList; + } } diff --git a/arkui-plugins/test/demo/localtest/entry/new.ets b/arkui-plugins/test/demo/localtest/entry/new.ets index 551759239..d8deb6b40 100755 --- a/arkui-plugins/test/demo/localtest/entry/new.ets +++ b/arkui-plugins/test/demo/localtest/entry/new.ets @@ -15,7 +15,7 @@ import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins import { Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickEvent, UserView } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins -import { State, Link, StateDecoratedVariable, LinkDecoratedVariable,MutableState, stateOf, observableProxy, DecoratedMutableVariable } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { State, Link, StateDecoratedVariable, LinkDecoratedVariable,MutableState, stateOf, observableProxy } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins import hilog from '@ohos.hilog' @Component @@ -38,7 +38,6 @@ struct MyStateSample { } } - @Component struct ChildLink { @Link stateVar: string = "Child"; diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 5208f9995..4ece2392e 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -31,9 +31,13 @@ import { hasDecorator, DecoratorNames, getStateManagementType, - collectPropertyDecorators, + collectPropertyDecorators } from './property-translators/utils'; -import { factory } from './ui-factory'; +import { + factory +} from './ui-factory'; +import { StructMap } from '../common/program-visitor'; +import { processStructCall } from './interop'; export interface ComponentTransformerOptions extends VisitorOptions { arkui?: string; @@ -59,6 +63,9 @@ export class ComponentTransformer extends AbstractVisitor { private context: ComponentContext = { structMembers: new Map() }; private isCustomComponentImported: boolean = false; private isEntryPointImported: boolean = false; + private hasLegacy = false; + private legacyStructMap: Map = new Map(); + private legacyCallMap: Map = new Map(); constructor(options?: ComponentTransformerOptions) { const _options: ComponentTransformerOptions = options ?? {}; @@ -75,6 +82,9 @@ export class ComponentTransformer extends AbstractVisitor { this.context = { structMembers: new Map() }; this.isCustomComponentImported = false; this.isEntryPointImported = false; + this.hasLegacy = false; + this.legacyStructMap = new Map(); + this.legacyCallMap = new Map(); } enter(node: arkts.AstNode) { @@ -342,6 +352,28 @@ export class ComponentTransformer extends AbstractVisitor { return [originMember]; } + registerMap(map: Map): void { + this.legacyStructMap = map; + this.hasLegacy = true; + } + + processImport(node: arkts.ETSImportDeclaration): void { + const source = node.source?.str!; + const specifiers = node.specifiers; + if (this.legacyStructMap.has(source)) { + const structMap = this.legacyStructMap.get(source); + if (!structMap) { + return; + } + for (const specifier of specifiers) { + const name = specifier.local.name; + if (structMap[name]) { + this.legacyCallMap.set(name, structMap[name]); + } + } + } + } + visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); const newNode = this.visitEachChild(node); @@ -353,6 +385,23 @@ export class ComponentTransformer extends AbstractVisitor { this.exit(newNode); return updateNode; } + if (!this.hasLegacy) { + return newNode; + } + if (arkts.isETSImportDeclaration(newNode)) { + this.processImport(newNode); + } + if (arkts.isCallExpression(newNode)) { + if (this.legacyCallMap.has(newNode.expression?.name)) { + const pathName = this.legacyCallMap.get(newNode.expression?.name)!; + const args = newNode.arguments; + if (args === undefined || args.length > 1 || !(args[0] instanceof arkts.ObjectExpression)) { + return processStructCall(newNode, pathName); + } + const arg = args[0]; + return processStructCall(newNode, pathName, arg); + } + } return newNode; } } diff --git a/arkui-plugins/ui-plugins/interop.ts b/arkui-plugins/ui-plugins/interop.ts new file mode 100644 index 000000000..64faa6e59 --- /dev/null +++ b/arkui-plugins/ui-plugins/interop.ts @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +import * as arkts from '@koalaui/libarkts'; +import { ARKUICOMPATIBLE, ESOBJECT, INITEMPTYOBJECT, NUMBER, SETPROPERTYBYNAME } from '../common/predefines'; + +export function createEmptyESObject(node: arkts.Identifier): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + node, + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(ESOBJECT), + arkts.factory.createIdentifier(INITEMPTYOBJECT), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined + ) + ) + ) + ] + ); +} + +export function setPropertyESObject(node: arkts.Identifier, key: arkts.StringLiteral, value: arkts.AstNode): arkts.ExpressionStatement { + return arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(ESOBJECT), + arkts.factory.createIdentifier(SETPROPERTYBYNAME), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + node, + key, + value + ] + ) + ); +} + +function initialArgs(node: arkts.Identifier, args?: arkts.ObjectExpression): arkts.Statement[] { + if (!args) { + return []; + } + const result: arkts.Statement[] = []; + + for (const property of args.properties) { + const key = property.key; + const value = property.value; + //TODO: ident type of value + const key_result = arkts.factory.createStringLiteral(key?.name); + const value_result = value.value; + const setProperty = setPropertyESObject(node, key_result, value); + result.push(setProperty); + } + return result; +} + +function createLegacyStruct(name: string, param: arkts.Expression[]): arkts.Statement { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier('component'), + arkts.factory.createTSAsExpression( + arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(name) + ) + ), + param + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(ESOBJECT) + ) + ), + false + ) + ) + ] + ); +} + +function paramsLambdaDeclaration(args?: arkts.ObjectExpression): arkts.Statement[] { + const result = []; + result.push( + arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier('paramLambda'), + arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + arkts.factory.createBlock([arkts.factory.createReturnStatement( + args ? args : arkts.ObjectExpression.createObjectExpression( + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + [], + false + ) + )]), + arkts.factory.createFunctionSignature( + undefined, + [], + undefined, + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ) + ), + + ] + ) + ); + return result; +} + +function createWrapperBlock(name: string, path: string, args?: arkts.ObjectExpression): arkts.BlockStatement { + const param = arkts.factory.createIdentifier('param'); + const extraInfo = arkts.factory.createIdentifier('extraInfo'); + const component = arkts.factory.createIdentifier('component'); + const parent = arkts.factory.createIdentifier('parent'); + const elmtId = arkts.factory.createIdentifier('elmtId'); + const lambda = arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + arkts.factory.createBlock([]), + arkts.factory.createFunctionSignature( + undefined, + [], + undefined, + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ); + const initialArgsStatement = initialArgs(param, args); + return arkts.factory.createBlock( + [ + ] + ); +} + +function createInitializer(name: string, number: arkts.ETSTypeReference, esobject: arkts.ETSTypeReference, + path: string, args?: arkts.ObjectExpression): arkts.ArrowFunctionExpression { + const block = createWrapperBlock(name, path, args); + return arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + block, + arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('elmtId', number), + undefined, + ), + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('instance', esobject), + undefined, + ), + ], + undefined, + false, + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ); +} + +function createUpdater(number: arkts.ETSTypeReference, esobject: arkts.ETSTypeReference): arkts.ArrowFunctionExpression { + return arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + arkts.factory.createBlock( + [ + + ] + ), + arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('elmtId', number), + undefined, + ), + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('instance', esobject), + undefined, + ), + ], + undefined, + false, + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ); +} + +export function processStructCall(node: arkts.CallExpression, path: string, args?: arkts.ObjectExpression): arkts.CallExpression { + const number = arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(NUMBER) + ) + ); + const esobject = arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(ESOBJECT) + ) + ); + const initializer = createInitializer(node.expression.name, number, esobject, path, args); + const updater = createUpdater(number, esobject); + return arkts.factory.createCallExpression( + arkts.factory.createIdentifier(ARKUICOMPATIBLE), + undefined, + [ + initializer, + updater, + ] + ); +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/legacy-transformer.ts b/arkui-plugins/ui-plugins/legacy-transformer.ts new file mode 100644 index 000000000..6719810bd --- /dev/null +++ b/arkui-plugins/ui-plugins/legacy-transformer.ts @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; +import { ESOBJECT } from '../common/predefines'; + +interface LegacyTransformerOptions extends VisitorOptions { + structList?: string[] +} + +export class LegacyTransformer extends AbstractVisitor { + private structList: string[] = []; + + constructor(options?: LegacyTransformerOptions) { + const _options: LegacyTransformerOptions = options ?? {}; + super(_options); + this.structList = _options.structList ?? []; + } + + getList(): string[] { + return this.structList; + } + + processComponent(node: arkts.StructDeclaration): arkts.StructDeclaration | arkts.ClassDeclaration { + const definition: arkts.ClassDefinition = node.definition!; + const ident = definition.ident!; + const hasExportFlag = + (node.modifiers & arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT) === + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; + if (hasExportFlag) { + this.structList.push(ident.name); + } + const newDefinition = arkts.factory.updateClassDefinition( + definition, + definition.ident, + definition.typeParams, + definition.superTypeParams, + definition.implements, + undefined, + definition.super, + [...definition.body], + definition.modifiers, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); + + //TODO: need check + if (arkts.isStructDeclaration(node)) { + const _node = arkts.factory.createClassDeclaration(newDefinition); + _node.modifiers = node.modifiers; + return _node; + } else { + return arkts.factory.updateClassDeclaration(node, newDefinition); + } + } + + processConstructor(node: arkts.MethodDefinition): arkts.MethodDefinition { + const esobject = arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(ESOBJECT) + ) + ); + const script = arkts.factory.createScriptFunction( + arkts.factory.createBlock([]), + arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('parent', esobject), + undefined, + ), + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('params', esobject), + undefined, + ), + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('localStorage', esobject), + undefined, + ), + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('elmtId', esobject), + undefined, + ), + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('paramsLambda', esobject), + undefined, + ), + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('extraInfo', esobject), + undefined, + ) + ], undefined, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + ); + return arkts.factory.updateMethodDefinition( + node, + node.kind, + node.name, + arkts.factory.createFunctionExpression(script), + node.modifiers, + false + ); + } + + visitor(node: arkts.AstNode): arkts.AstNode { + const newNode = this.visitEachChild(node); + if (arkts.isStructDeclaration(newNode)) { + const updateNode = this.processComponent(newNode); + return updateNode; + } + if (arkts.isMethodDefinition(newNode)) { + const kind = newNode.kind; + if (kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR) { + const updateNode = this.processConstructor(newNode); + return updateNode; + } + } + return newNode; + } +} \ No newline at end of file -- Gitee From c6e8758e2fece9322d634b7b736e604bda6a17a7 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Fri, 11 Apr 2025 20:34:09 +0800 Subject: [PATCH 041/123] add node utilities to skip unnecessary update Signed-off-by: Jiakai Shi Change-Id: Ibb8219d0c5e438d61e2980abec2510cd710a7819 --- koala-wrapper/src/arkts-api/class-by-peer.ts | 37 +- .../src/arkts-api/factory/nodeFactory.ts | 321 +++---- .../node-utilities/AnnotationUsage.ts | 27 + .../node-utilities/ArrowFunctionExpression.ts | 35 + .../node-utilities/AssignmentExpression.ts | 38 + .../node-utilities/BinaryExpression.ts | 37 + .../node-utilities/BlockExpression.ts | 27 + .../node-utilities/BlockStatement.ts | 27 + .../node-utilities/CallExpression.ts | 45 + .../node-utilities/ChainExpression.ts | 27 + .../node-utilities/ClassDeclaration.ts | 27 + .../node-utilities/ClassDefinition.ts | 73 ++ .../arkts-api/node-utilities/ClassProperty.ts | 51 ++ .../node-utilities/ConditionalExpression.ts | 36 + .../node-utilities/ETSFunctionType.ts | 42 + .../node-utilities/ETSImportDeclaration.ts | 39 + .../ETSNewClassInstanceExpression.ts | 34 + .../node-utilities/ETSParameterExpression.ts | 43 + .../node-utilities/ETSPrimitiveType.ts | 28 + .../node-utilities/ETSTypeReference.ts | 27 + .../node-utilities/ETSTypeReferencePart.ts | 36 + .../node-utilities/ETSUndefinedType.ts | 24 + .../arkts-api/node-utilities/ETSUnionType.ts | 27 + .../node-utilities/ExpressionStatement.ts | 28 + .../node-utilities/FunctionDeclaration.ts | 37 + .../node-utilities/FunctionExpression.ts | 28 + .../arkts-api/node-utilities/Identifier.ts | 27 + .../arkts-api/node-utilities/IfStatement.ts | 37 + .../node-utilities/ImportSpecifier.ts | 31 + .../node-utilities/MemberExpression.ts | 42 + .../node-utilities/MethodDefinition.ts | 45 + .../arkts-api/node-utilities/NullLiteral.ts | 24 + .../arkts-api/node-utilities/NumberLiteral.ts | 30 + .../node-utilities/ReturnStatement.ts | 27 + .../node-utilities/ScriptFunction.ts | 46 + .../arkts-api/node-utilities/StringLiteral.ts | 27 + .../node-utilities/StructDeclaration.ts | 28 + .../node-utilities/SuperExpression.ts | 24 + .../node-utilities/TSAsExpression.ts | 36 + .../node-utilities/TSInterfaceBody.ts | 28 + .../node-utilities/TSInterfaceDeclaration.ts | 43 + .../node-utilities/TSNonNullExpression.ts | 27 + .../node-utilities/TSTypeAliasDeclaration.ts | 40 + .../node-utilities/TSTypeParameter.ts | 36 + .../TSTypeParameterDeclaration.ts | 31 + .../TSTypeParameterInstantiation.ts | 30 + .../node-utilities/ThisExpression.ts | 24 + .../node-utilities/UndefinedLiteral.ts | 24 + .../node-utilities/VariableDeclaration.ts | 38 + .../node-utilities/VariableDeclarator.ts | 39 + .../src/arkts-api/peers/ArktsObject.ts | 27 +- .../to-be-generated/MemberExpression.ts | 40 +- koala-wrapper/src/arkts-api/types.ts | 791 ++++++++---------- .../src/arkts-api/utilities/private.ts | 170 ++-- .../src/arkts-api/utilities/public.ts | 2 + 55 files changed, 2249 insertions(+), 766 deletions(-) create mode 100644 koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ArrowFunctionExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/AssignmentExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/BinaryExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/BlockExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/BlockStatement.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/CallExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ChainExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ClassDeclaration.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ClassDefinition.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ClassProperty.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ConditionalExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSFunctionType.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSImportDeclaration.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSNewClassInstanceExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSParameterExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSPrimitiveType.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSTypeReference.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSTypeReferencePart.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSUndefinedType.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ETSUnionType.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ExpressionStatement.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/FunctionDeclaration.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/FunctionExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/Identifier.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/IfStatement.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ImportSpecifier.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/MemberExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/NullLiteral.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/NumberLiteral.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ReturnStatement.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ScriptFunction.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/StringLiteral.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/StructDeclaration.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/SuperExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TSAsExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TSInterfaceBody.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TSInterfaceDeclaration.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TSNonNullExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TSTypeAliasDeclaration.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TSTypeParameter.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TSTypeParameterDeclaration.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TSTypeParameterInstantiation.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ThisExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/UndefinedLiteral.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/VariableDeclarator.ts diff --git a/koala-wrapper/src/arkts-api/class-by-peer.ts b/koala-wrapper/src/arkts-api/class-by-peer.ts index 8c5692dc9..f8d79996c 100644 --- a/koala-wrapper/src/arkts-api/class-by-peer.ts +++ b/koala-wrapper/src/arkts-api/class-by-peer.ts @@ -13,19 +13,34 @@ * limitations under the License. */ -import { Es2pandaAstNodeType } from "../Es2pandaEnums" -import { throwError } from "../utils" -import { global } from "./static/global" -import { KNativePointer, nullptr } from "@koalaui/interop" -import { AstNode, UnsupportedNode } from "./peers/AstNode" +import { Es2pandaAstNodeType } from '../Es2pandaEnums'; +import { throwError } from '../utils'; +import { global } from './static/global'; +import { KNativePointer, nullptr } from '@koalaui/interop'; +import { AstNode, UnsupportedNode } from './peers/AstNode'; -export const nodeByType = new Map([]) +export const nodeByType = new Map([]); + +const cache = new Map(); +export function clearNodeCache(): void { + cache.clear(); +} + +function getOrPut(peer: KNativePointer, create: (peer: KNativePointer) => AstNode): AstNode { + if (cache.has(peer)) { + return cache.get(peer)!; + } + + const newNode = create(peer); + cache.set(peer, newNode); + return newNode; +} export function classByPeer(peer: KNativePointer): T { if (peer === nullptr) { - throwError('classByPeer: peer is NULLPTR') + throwError('classByPeer: peer is NULLPTR'); } - const type = global.generatedEs2panda._AstNodeTypeConst(global.context, peer) - const node = nodeByType.get(type) ?? UnsupportedNode - return new node(peer) as T -} \ No newline at end of file + const type = global.generatedEs2panda._AstNodeTypeConst(global.context, peer); + const node = nodeByType.get(type) ?? UnsupportedNode; + return getOrPut(peer, (peer) => new node(peer)) as T; +} diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index 394dad37e..5283543ac 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -78,75 +78,79 @@ import { classPropertySetOptional, hasModifierFlag } from "../utilities/public" - -/** - * @deprecated - */ -function compose( - create: (...args: ARGS) => T, - update: (node: T, original: T) => T = updateNodeByNode -): (node: T, ...args: ARGS) => T { - return (node: T, ...args: ARGS) => update(create(...args), node); -} - -function updateThenAttach( - update: (original: T, ...args: ARGS) => T, - ...attachFuncs: ((node: T, original: T) => T)[] -): (node: T, ...args: ARGS) => T { - return (node: T, ...args: ARGS) => { - let _node: T = update(node, ...args); - attachFuncs.forEach((attach) => { - _node = attach(_node, node); - }) - return _node; - } -} - -function attachModifiers( - node: T, - original: T -): T { - node.modifiers = original.modifiers; - return node; -} +import { updateIdentifier } from "../node-utilities/Identifier" +import { updateCallExpression } from "../node-utilities/CallExpression" +import { updateExpressionStatement } from "../node-utilities/ExpressionStatement" +import { updateMemberExpression } from "../node-utilities/MemberExpression" +import { updateFunctionDeclaration } from "../node-utilities/FunctionDeclaration" +import { updateBlockStatement } from "../node-utilities/BlockStatement" +import { updateArrowFunctionExpression } from "../node-utilities/ArrowFunctionExpression" +import { updateScriptFunction } from "../node-utilities/ScriptFunction" +import { updateStringLiteral } from "../node-utilities/StringLiteral" +import { updateNumberLiteral } from "../node-utilities/NumberLiteral" +import { updateETSParameterExpression } from "../node-utilities/ETSParameterExpression" +import { updateTSTypeParameter } from "../node-utilities/TSTypeParameter" +import { updateTSTypeParameterDeclaration } from "../node-utilities/TSTypeParameterDeclaration" +import { updateETSPrimitiveType } from "../node-utilities/ETSPrimitiveType" +import { updateETSTypeReference } from "../node-utilities/ETSTypeReference" +import { updateETSTypeReferencePart } from "../node-utilities/ETSTypeReferencePart" +import { updateETSImportDeclaration } from "../node-utilities/ETSImportDeclaration" +import { updateImportSpecifier } from "../node-utilities/ImportSpecifier" +import { updateVariableDeclaration } from "../node-utilities/VariableDeclaration" +import { updateVariableDeclarator } from "../node-utilities/VariableDeclarator" +import { updateETSUnionType } from "../node-utilities/ETSUnionType" +import { updateReturnStatement } from "../node-utilities/ReturnStatement" +import { updateIfStatement } from "../node-utilities/IfStatement" +import { updateBinaryExpression } from "../node-utilities/BinaryExpression" +import { updateClassDeclaration } from "../node-utilities/ClassDeclaration" +import { updateStructDeclaration } from "../node-utilities/StructDeclaration" +import { updateClassDefinition } from "../node-utilities/ClassDefinition" +import { updateClassProperty } from "../node-utilities/ClassProperty" +import { updateETSFunctionType } from "../node-utilities/ETSFunctionType" +import { updateFunctionExpression } from "../node-utilities/FunctionExpression" +import { updateMethodDefinition } from "../node-utilities/MethodDefinition" +import { updateSuperExpression } from "../node-utilities/SuperExpression" +import { updateTSTypeParameterInstantiation } from "../node-utilities/TSTypeParameterInstantiation" +import { updateTSInterfaceDeclaration } from "../node-utilities/TSInterfaceDeclaration" +import { updateTSInterfaceBody } from "../node-utilities/TSInterfaceBody" +import { updateUndefinedLiteral } from "../node-utilities/UndefinedLiteral" +import { updateAnnotationUsage } from "../node-utilities/AnnotationUsage" +import { updateAssignmentExpression } from "../node-utilities/AssignmentExpression" +import { updateETSUndefinedType } from "../node-utilities/ETSUndefinedType" +import { updateConditionalExpression } from "../node-utilities/ConditionalExpression" +import { updateTSAsExpression } from "../node-utilities/TSAsExpression" +import { updateThisExpression } from "../node-utilities/ThisExpression" +import { updateTSTypeAliasDeclaration } from "../node-utilities/TSTypeAliasDeclaration" +import { updateTSNonNullExpression } from "../node-utilities/TSNonNullExpression" +import { updateChainExpression } from "../node-utilities/ChainExpression" +import { updateBlockExpression } from "../node-utilities/BlockExpression" +import { updateNullLiteral } from "../node-utilities/NullLiteral" +import { updateETSNewClassInstanceExpression } from "../node-utilities/ETSNewClassInstanceExpression" export const factory = { get createIdentifier() { return Identifier.create2Identifier }, get updateIdentifier() { - return updateThenAttach( - Identifier.update2Identifier, - attachModifiers - ) + return updateIdentifier }, get createCallExpression() { return CallExpression.create }, get updateCallExpression() { - return updateThenAttach( - CallExpression.update, - attachModifiers, - (node: CallExpression, original: CallExpression) => !!original.trailingBlock ? node.setTralingBlock(original.trailingBlock) : node - ) + return updateCallExpression }, get createExpressionStatement() { return ExpressionStatement.create }, get updateExpressionStatement() { - return updateThenAttach( - ExpressionStatement.update, - attachModifiers - ) + return updateExpressionStatement }, get createMemberExpression() { return MemberExpression.create }, get updateMemberExpression() { - return updateThenAttach( - MemberExpression.update, - attachModifiers - ) + return updateMemberExpression }, get createEtsScript() { return EtsScript.createFromSource @@ -158,335 +162,217 @@ export const factory = { return FunctionDeclaration.create }, get updateFunctionDeclaration() { - return updateThenAttach( - FunctionDeclaration.update, - attachModifiers - ) + return updateFunctionDeclaration }, get createBlock() { return BlockStatement.createBlockStatement }, get updateBlock() { - return updateThenAttach( - BlockStatement.updateBlockStatement, - attachModifiers - ) + return updateBlockStatement }, get createArrowFunction() { return ArrowFunctionExpression.create }, get updateArrowFunction() { - return updateThenAttach( - ArrowFunctionExpression.update, - attachModifiers, - (node: ArrowFunctionExpression, original: ArrowFunctionExpression) => node.setAnnotations(original.annotations) - ) + return updateArrowFunctionExpression }, get createScriptFunction() { return ScriptFunction.createScriptFunction }, get updateScriptFunction() { - return updateThenAttach( - ScriptFunction.updateScriptFunction, - (node: ScriptFunction, original: ScriptFunction) => ( !!original.id ? node.setIdent(original.id) : node ), - (node: ScriptFunction, original: ScriptFunction) => node.setAnnotations(original.annotations) - ) + return updateScriptFunction }, get createStringLiteral() { return StringLiteral.create1StringLiteral }, get updateStringLiteral() { - return updateThenAttach( - StringLiteral.update1StringLiteral, - attachModifiers - ) + return updateStringLiteral }, get create1StringLiteral() { return StringLiteral.create1StringLiteral }, get update1StringLiteral() { - return updateThenAttach( - StringLiteral.update1StringLiteral, - attachModifiers - ) + return updateStringLiteral }, get createNumericLiteral() { return NumberLiteral.create }, get updateNumericLiteral() { - return updateThenAttach( - compose(NumberLiteral.create), // TODO: No UpdateNumberLiteral, need to change this - attachModifiers - ) + return updateNumberLiteral }, get createParameterDeclaration() { return ETSParameterExpression.create }, get updateParameterDeclaration() { - return updateThenAttach( - ETSParameterExpression.update, - attachModifiers, - (node: ETSParameterExpression, original: ETSParameterExpression) => { node.annotations = original.annotations; return node; } - ) + return updateETSParameterExpression }, get createTypeParameter() { return TSTypeParameter.createTSTypeParameter }, get updateTypeParameter() { - return updateThenAttach( - TSTypeParameter.updateTSTypeParameter, - attachModifiers - ) + return updateTSTypeParameter }, get createTypeParameterDeclaration() { return TSTypeParameterDeclaration.createTSTypeParameterDeclaration }, get updateTypeParameterDeclaration() { - return updateThenAttach( - TSTypeParameterDeclaration.updateTSTypeParameterDeclaration, - attachModifiers - ) + return updateTSTypeParameterDeclaration }, get createPrimitiveType() { return ETSPrimitiveType.createETSPrimitiveType }, get updatePrimitiveType() { - return updateThenAttach( - ETSPrimitiveType.updateETSPrimitiveType, - attachModifiers - ) + return updateETSPrimitiveType }, get createTypeReference() { return ETSTypeReference.createETSTypeReference }, get updateTypeReference() { - return updateThenAttach( - ETSTypeReference.updateETSTypeReference, - attachModifiers - ) + return updateETSTypeReference }, get createTypeReferencePart() { return ETSTypeReferencePart.createETSTypeReferencePart }, get updateTypeReferencePart() { - return updateThenAttach( - ETSTypeReferencePart.updateETSTypeReferencePart, - attachModifiers - ) + return updateETSTypeReferencePart }, get createImportDeclaration() { return ETSImportDeclaration.createETSImportDeclaration }, get updateImportDeclaration() { - return updateThenAttach( - ETSImportDeclaration.updateETSImportDeclaration, - attachModifiers - ) + return updateETSImportDeclaration }, get createImportSpecifier() { return ImportSpecifier.createImportSpecifier }, get updateImportSpecifier() { - return updateThenAttach( - ImportSpecifier.updateImportSpecifier, - attachModifiers - ) + return updateImportSpecifier }, get createVariableDeclaration() { return VariableDeclaration.create }, get updateVariableDeclaration() { - return updateThenAttach( - VariableDeclaration.update, - attachModifiers - ) + return updateVariableDeclaration }, get createVariableDeclarator() { return VariableDeclarator.create }, get updateVariableDeclarator() { - return updateThenAttach( - VariableDeclarator.update, - attachModifiers - ) + return updateVariableDeclarator }, get createUnionType() { return ETSUnionType.createETSUnionType }, get updateUnionType() { - return updateThenAttach( - ETSUnionType.updateETSUnionType, - attachModifiers - ) + return updateETSUnionType }, get createReturnStatement() { return ReturnStatement.create1ReturnStatement }, get updateReturnStatement() { - return updateThenAttach( - ReturnStatement.update1ReturnStatement, - attachModifiers - ) + return updateReturnStatement }, get createIfStatement() { return IfStatement.create }, get updateIfStatement() { - return updateThenAttach( - IfStatement.update, - attachModifiers - ) + return updateIfStatement }, get createBinaryExpression() { return BinaryExpression.createBinaryExpression }, get updateBinaryExpression() { - return updateThenAttach( - BinaryExpression.updateBinaryExpression, - attachModifiers - ) + return updateBinaryExpression }, get createClassDeclaration() { return ClassDeclaration.createClassDeclaration }, get updateClassDeclaration() { - return updateThenAttach( - ClassDeclaration.updateClassDeclaration, - attachModifiers - ) + return updateClassDeclaration }, get createStructDeclaration() { return StructDeclaration.create }, get updateStructDeclaration() { - return updateThenAttach( - StructDeclaration.update, - attachModifiers - ) + return updateStructDeclaration }, get createClassDefinition() { return ClassDefinition.createClassDefinition }, get updateClassDefinition() { - return updateThenAttach( - ClassDefinition.updateClassDefinition, - (node: ClassDefinition, original: ClassDefinition) => node.setAnnotations(original.annotations) - ) + return updateClassDefinition }, get createClassProperty() { return ClassProperty.createClassProperty }, get updateClassProperty() { - return updateThenAttach( - ClassProperty.updateClassProperty, - (node: ClassProperty, original: ClassProperty) => node.setAnnotations(original.annotations), - (node: ClassProperty, original: ClassProperty) => { - if (hasModifierFlag(original, Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL)) { - return classPropertySetOptional(node, true); - } - return node; - } - ) + return updateClassProperty }, get createFunctionType() { return ETSFunctionType.createETSFunctionType }, get updateFunctionType() { - return updateThenAttach( - ETSFunctionType.updateETSFunctionType, - attachModifiers, - (node: ETSFunctionType, original: ETSFunctionType) => node.setAnnotations(original.annotations) - ) + return updateETSFunctionType }, get createFunctionExpression() { return FunctionExpression.create }, get updateFunctionExpression() { - return updateThenAttach( - FunctionExpression.update, - attachModifiers - ) + return updateFunctionExpression }, get createMethodDefinition() { return MethodDefinition.create }, get updateMethodDefinition() { - return updateThenAttach( - MethodDefinition.update, - (node: MethodDefinition, original: MethodDefinition) => node.setOverloads(original.overloads) - ) + return updateMethodDefinition }, get createSuperExpression() { return SuperExpression.createSuperExpression }, get updateSuperExpression() { - return updateThenAttach( - SuperExpression.updateSuperExpression, - attachModifiers - ) + return updateSuperExpression }, get createTSTypeParameterInstantiation() { return TSTypeParameterInstantiation.createTSTypeParameterInstantiation }, get updateTSTypeParameterInstantiation() { - return updateThenAttach( - TSTypeParameterInstantiation.updateTSTypeParameterInstantiation, - attachModifiers - ) + return updateTSTypeParameterInstantiation }, get createInterfaceDeclaration() { return TSInterfaceDeclaration.createTSInterfaceDeclaration }, get updateInterfaceDeclaration() { - return updateThenAttach( - TSInterfaceDeclaration.updateTSInterfaceDeclaration, - attachModifiers - ) + return updateTSInterfaceDeclaration }, get createInterfaceBody() { return TSInterfaceBody.createTSInterfaceBody }, get updateInterfaceBody() { - return updateThenAttach( - TSInterfaceBody.updateTSInterfaceBody, - attachModifiers - ) + return updateTSInterfaceBody }, get createUndefinedLiteral() { return UndefinedLiteral.createUndefinedLiteral }, get updateUndefinedLiteral() { - return updateThenAttach( - UndefinedLiteral.updateUndefinedLiteral, - attachModifiers - ) + return updateUndefinedLiteral }, get createAnnotationUsage() { return AnnotationUsage.createAnnotationUsage }, get updateAnnotationUsage() { - return updateThenAttach( - AnnotationUsage.updateAnnotationUsage, - attachModifiers - ) + return updateAnnotationUsage }, get createAssignmentExpression() { return AssignmentExpression.create }, get updateAssignmentExpression() { - return updateThenAttach( - AssignmentExpression.update, - attachModifiers - ) + return updateAssignmentExpression }, get createETSUndefinedType() { return ETSUndefinedType.createETSUndefinedType }, get updateETSUndefinedType() { - return updateThenAttach( - ETSUndefinedType.updateETSUndefinedType, - attachModifiers - ) + return updateETSUndefinedType }, get createFunctionSignature() { return FunctionSignature.createFunctionSignature @@ -495,68 +381,55 @@ export const factory = { return ConditionalExpression.createConditionalExpression }, get updateConditionalExpression() { - return updateThenAttach( - ConditionalExpression.updateConditionalExpression, - attachModifiers - ) + return updateConditionalExpression }, get createTSAsExpression() { return TSAsExpression.createTSAsExpression }, get updateTSAsExpression() { - return updateThenAttach( - TSAsExpression.updateTSAsExpression, - attachModifiers - ) + return updateTSAsExpression }, get createThisExpression() { return ThisExpression.createThisExpression }, get updateThisExpression() { - return updateThenAttach( - ThisExpression.updateThisExpression, - attachModifiers - ) + return updateThisExpression }, get createTSTypeAliasDeclaration() { return TSTypeAliasDeclaration.createTSTypeAliasDeclaration }, get updateTSTypeAliasDeclaration() { - return updateThenAttach( - TSTypeAliasDeclaration.updateTSTypeAliasDeclaration, - attachModifiers, - (node: TSTypeAliasDeclaration, original: TSTypeAliasDeclaration) => node.setAnnotations(original.annotations) - ) + return updateTSTypeAliasDeclaration }, get createTSNonNullExpression() { return TSNonNullExpression.createTSNonNullExpression }, get updateTSNonNullExpression() { - return TSNonNullExpression.updateTSNonNullExpression + return updateTSNonNullExpression }, get createChainExpression() { return ChainExpression.createChainExpression }, get updateChainExpression() { - return ChainExpression.updateChainExpression + return updateChainExpression }, get createBlockExpression() { return BlockExpression.createBlockExpression }, get updateBlockExpression() { - return BlockExpression.updateBlockExpression + return updateBlockExpression }, get createNullLiteral() { return NullLiteral.createNullLiteral }, get updateNullLiteral() { - return NullLiteral.updateNullLiteral + return updateNullLiteral }, get createETSNewClassInstanceExpression() { return ETSNewClassInstanceExpression.createETSNewClassInstanceExpression }, get updateETSNewClassInstanceExpression() { - return ETSNewClassInstanceExpression.updateETSNewClassInstanceExpression + return updateETSNewClassInstanceExpression }, get createETSStringLiteralType(){ return ETSStringLiteralType.create; diff --git a/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts b/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts new file mode 100644 index 000000000..e79cc04c3 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AnnotationUsage, Expression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateAnnotationUsage(original: AnnotationUsage, expr?: Expression): AnnotationUsage { + if (isSameNativeObject(expr, original.expr)) { + return original; + } + + const update = updateThenAttach(AnnotationUsage.updateAnnotationUsage, attachModifiers); + return update(original, expr); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ArrowFunctionExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ArrowFunctionExpression.ts new file mode 100644 index 000000000..9ad9e11af --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ArrowFunctionExpression.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ScriptFunction } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { ArrowFunctionExpression } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateArrowFunctionExpression( + original: ArrowFunctionExpression, + func: ScriptFunction +): ArrowFunctionExpression { + if (isSameNativeObject(func, original.scriptFunction)) { + return original; + } + + const update = updateThenAttach( + ArrowFunctionExpression.update, + attachModifiers, + (node: ArrowFunctionExpression, original: ArrowFunctionExpression) => node.setAnnotations(original.annotations) + ); + return update(original, func); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/AssignmentExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/AssignmentExpression.ts new file mode 100644 index 000000000..de701b0ad --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/AssignmentExpression.ts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { AssignmentExpression } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaTokenType } from '../../generated/Es2pandaEnums'; + +export function updateAssignmentExpression( + original: AssignmentExpression, + left: AstNode, + assignmentOperator: Es2pandaTokenType, + right: AstNode +): AssignmentExpression { + if ( + isSameNativeObject(left, original.left) && + isSameNativeObject(assignmentOperator, original.operatorType) && + isSameNativeObject(right, original.right) + ) { + return original; + } + + const update = updateThenAttach(AssignmentExpression.update, attachModifiers); + return update(original, left, assignmentOperator, right); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/BinaryExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/BinaryExpression.ts new file mode 100644 index 000000000..25a182b16 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/BinaryExpression.ts @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BinaryExpression, Expression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaTokenType } from '../../generated/Es2pandaEnums'; + +export function updateBinaryExpression( + original: BinaryExpression, + left: Expression | undefined, + right: Expression | undefined, + operatorType: Es2pandaTokenType +): BinaryExpression { + if ( + isSameNativeObject(left, original.left) && + isSameNativeObject(right, original.right) && + isSameNativeObject(operatorType, original.operatorType) + ) { + return original; + } + + const update = updateThenAttach(BinaryExpression.updateBinaryExpression, attachModifiers); + return update(original, left, right, operatorType); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/BlockExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/BlockExpression.ts new file mode 100644 index 000000000..e1489fb2e --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/BlockExpression.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BlockExpression, Statement } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateBlockExpression(original: BlockExpression, statements: readonly Statement[]): BlockExpression { + if (isSameNativeObject(statements, original.statements)) { + return original; + } + + const update = updateThenAttach(BlockExpression.updateBlockExpression, attachModifiers); + return update(original, statements); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/BlockStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/BlockStatement.ts new file mode 100644 index 000000000..d9571384f --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/BlockStatement.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BlockStatement, Statement } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateBlockStatement(original: BlockStatement, statementList: readonly Statement[]): BlockStatement { + if (isSameNativeObject(statementList, original.statements)) { + return original; + } + + const update = updateThenAttach(BlockStatement.updateBlockStatement, attachModifiers); + return update(original, statementList); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/CallExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/CallExpression.ts new file mode 100644 index 000000000..d1489441a --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/CallExpression.ts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TypeNode } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { CallExpression } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateCallExpression( + original: CallExpression, + expression: AstNode, + typeArguments: readonly TypeNode[] | undefined, + args: readonly AstNode[] | undefined, + isOptional?: boolean, + trailingComma?: boolean +): CallExpression { + if ( + isSameNativeObject(expression, original.expression) && + isSameNativeObject(typeArguments, original.typeArguments) && + isSameNativeObject(args, original.arguments) + ) { + return original; + } + + const update = updateThenAttach( + CallExpression.update, + attachModifiers, + (node: CallExpression, original: CallExpression) => + !!original.trailingBlock ? node.setTralingBlock(original.trailingBlock) : node + ); + return update(original, expression, typeArguments, args, isOptional, trailingComma); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ChainExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ChainExpression.ts new file mode 100644 index 000000000..fdadb8843 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ChainExpression.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ChainExpression, Expression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateChainExpression(original: ChainExpression, expression?: Expression): ChainExpression { + if (isSameNativeObject(expression, original.getExpression)) { + return original; + } + + const update = updateThenAttach(ChainExpression.updateChainExpression, attachModifiers); + return update(original, expression); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ClassDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/ClassDeclaration.ts new file mode 100644 index 000000000..1474e8d84 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ClassDeclaration.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClassDeclaration, ClassDefinition } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateClassDeclaration(original: ClassDeclaration, def?: ClassDefinition): ClassDeclaration { + if (isSameNativeObject(def, original.definition)) { + return original; + } + + const update = updateThenAttach(ClassDeclaration.updateClassDeclaration, attachModifiers); + return update(original, def); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ClassDefinition.ts b/koala-wrapper/src/arkts-api/node-utilities/ClassDefinition.ts new file mode 100644 index 000000000..1e9ae0ffb --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ClassDefinition.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + ClassDefinition, + Expression, + Identifier, + TSClassImplements, + TSTypeParameterDeclaration, + TSTypeParameterInstantiation, +} from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { MethodDefinition } from '../types'; +import { updateThenAttach } from '../utilities/private'; +import { Es2pandaClassDefinitionModifiers, Es2pandaModifierFlags } from '../../generated/Es2pandaEnums'; +import { classDefinitionFlags } from '../utilities/public'; + +export function updateClassDefinition( + original: ClassDefinition, + ident: Identifier | undefined, + typeParams: TSTypeParameterDeclaration | undefined, + superTypeParams: TSTypeParameterInstantiation | undefined, + _implements: readonly TSClassImplements[], + ctor: MethodDefinition | undefined, + superClass: Expression | undefined, + body: readonly AstNode[], + modifiers: Es2pandaClassDefinitionModifiers, + flags: Es2pandaModifierFlags +): ClassDefinition { + if ( + isSameNativeObject(ident, original.ident) && + isSameNativeObject(typeParams, original.typeParams) && + isSameNativeObject(superTypeParams, original.superTypeParams) && + isSameNativeObject(_implements, original.implements) && + isSameNativeObject(superClass, original.super) && + isSameNativeObject(body, original.body) && + isSameNativeObject(modifiers, original.modifiers) && + isSameNativeObject(flags, classDefinitionFlags(original)) + /* TODO: no getter for ctor */ + ) { + return original; + } + + const update = updateThenAttach( + ClassDefinition.updateClassDefinition, + (node: ClassDefinition, original: ClassDefinition) => node.setAnnotations(original.annotations) + ); + return update( + original, + ident, + typeParams, + superTypeParams, + _implements, + undefined, + superClass, + body, + modifiers, + flags + ); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ClassProperty.ts b/koala-wrapper/src/arkts-api/node-utilities/ClassProperty.ts new file mode 100644 index 000000000..06450c0cb --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ClassProperty.ts @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClassProperty, Expression, TypeNode } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { updateThenAttach } from '../utilities/private'; +import { classPropertySetOptional, hasModifierFlag } from '../utilities/public'; +import { Es2pandaModifierFlags } from '../../generated/Es2pandaEnums'; + +export function updateClassProperty( + original: ClassProperty, + key: Expression | undefined, + value: Expression | undefined, + typeAnnotation: TypeNode | undefined, + modifiers: Es2pandaModifierFlags, + isComputed: boolean +): ClassProperty { + if ( + isSameNativeObject(key, original.key) && + isSameNativeObject(value, original.value) && + isSameNativeObject(typeAnnotation, original.typeAnnotation) && + isSameNativeObject(modifiers, original.modifiers) && + isSameNativeObject(isComputed, original.isComputed) + ) { + return original; + } + + const update = updateThenAttach( + ClassProperty.updateClassProperty, + (node: ClassProperty, original: ClassProperty) => node.setAnnotations(original.annotations), + (node: ClassProperty, original: ClassProperty) => { + if (hasModifierFlag(original, Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL)) { + return classPropertySetOptional(node, true); + } + return node; + } + ); + return update(original, key, value, typeAnnotation, modifiers, isComputed); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ConditionalExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ConditionalExpression.ts new file mode 100644 index 000000000..e1d2d5b2f --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ConditionalExpression.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ConditionalExpression, Expression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateConditionalExpression( + original: ConditionalExpression, + test?: Expression, + consequent?: Expression, + alternate?: Expression +): ConditionalExpression { + if ( + isSameNativeObject(test, original.test) && + isSameNativeObject(consequent, original.consequent) && + isSameNativeObject(alternate, original.alternate) + ) { + return original; + } + + const update = updateThenAttach(ConditionalExpression.updateConditionalExpression, attachModifiers); + return update(original, test, consequent, alternate); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSFunctionType.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSFunctionType.ts new file mode 100644 index 000000000..a0e522040 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSFunctionType.ts @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ETSFunctionType, FunctionSignature } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaScriptFunctionFlags } from '../../generated/Es2pandaEnums'; + +export function updateETSFunctionType( + original: ETSFunctionType, + signature: FunctionSignature | undefined, + funcFlags: Es2pandaScriptFunctionFlags +): ETSFunctionType { + if ( + isSameNativeObject(signature?.typeParams, original.typeParams) && + isSameNativeObject(signature?.returnType, original.returnType) && + isSameNativeObject(signature?.params, original.params) && + isSameNativeObject(funcFlags, original.flags) + /* TODO: no getter for signature's hasReceiver */ + ) { + return original; + } + + const update = updateThenAttach( + ETSFunctionType.updateETSFunctionType, + attachModifiers, + (node: ETSFunctionType, original: ETSFunctionType) => node.setAnnotations(original.annotations) + ); + return update(original, signature, funcFlags); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSImportDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSImportDeclaration.ts new file mode 100644 index 000000000..1186fe3d4 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSImportDeclaration.ts @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ETSImportDeclaration, StringLiteral } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaImportKinds } from '../../generated/Es2pandaEnums'; + +export function updateETSImportDeclaration( + original: ETSImportDeclaration, + source: StringLiteral | undefined, + specifiers: readonly AstNode[], + importKind: Es2pandaImportKinds +): ETSImportDeclaration { + if ( + isSameNativeObject(source, original.source) && + isSameNativeObject(specifiers, original.specifiers) && + isSameNativeObject(importKind, Number(original.isTypeKind)) + ) { + /* TODO: probably should set importMetadata, but no getter provided yet */ + return original; + } + + const update = updateThenAttach(ETSImportDeclaration.updateETSImportDeclaration, attachModifiers); + return update(original, source, specifiers, importKind); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSNewClassInstanceExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSNewClassInstanceExpression.ts new file mode 100644 index 000000000..512085cb0 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSNewClassInstanceExpression.ts @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ETSNewClassInstanceExpression, Expression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateETSNewClassInstanceExpression( + original: ETSNewClassInstanceExpression, + typeReference: Expression | undefined, + _arguments: readonly Expression[] +): ETSNewClassInstanceExpression { + if ( + isSameNativeObject(typeReference, original.getTypeRef) && + isSameNativeObject(_arguments, original.getArguments) + ) { + return original; + } + + const update = updateThenAttach(ETSNewClassInstanceExpression.updateETSNewClassInstanceExpression, attachModifiers); + return update(original, typeReference, _arguments); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSParameterExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSParameterExpression.ts new file mode 100644 index 000000000..b9e8f0514 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSParameterExpression.ts @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Identifier } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { ETSParameterExpression } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateETSParameterExpression( + original: ETSParameterExpression, + identifier: Identifier, + initializer: AstNode | undefined +): ETSParameterExpression { + if ( + isSameNativeObject(identifier, original.identifier) && + !initializer // TODO: get this from ETSParameterExpression + ) { + return original; + } + + const update = updateThenAttach( + ETSParameterExpression.update, + attachModifiers, + (node: ETSParameterExpression, original: ETSParameterExpression) => { + node.annotations = original.annotations; + return node; + } + ); + return update(original, identifier, initializer); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSPrimitiveType.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSPrimitiveType.ts new file mode 100644 index 000000000..0cba48bd8 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSPrimitiveType.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ETSPrimitiveType } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaPrimitiveType } from '../../generated/Es2pandaEnums'; + +export function updateETSPrimitiveType(original: ETSPrimitiveType, type: Es2pandaPrimitiveType): ETSPrimitiveType { + if (isSameNativeObject(type, original.getPrimitiveType)) { + return original; + } + + const update = updateThenAttach(ETSPrimitiveType.updateETSPrimitiveType, attachModifiers); + return update(original, type); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSTypeReference.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSTypeReference.ts new file mode 100644 index 000000000..005d510bf --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSTypeReference.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ETSTypeReference, ETSTypeReferencePart } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateETSTypeReference(original: ETSTypeReference, part?: ETSTypeReferencePart): ETSTypeReference { + if (isSameNativeObject(part, original.part)) { + return original; + } + + const update = updateThenAttach(ETSTypeReference.updateETSTypeReference, attachModifiers); + return update(original, part); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSTypeReferencePart.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSTypeReferencePart.ts new file mode 100644 index 000000000..fcc821203 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSTypeReferencePart.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ETSTypeReferencePart, Expression, TSTypeParameterInstantiation } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateETSTypeReferencePart( + original: ETSTypeReferencePart, + name?: Expression, + typeParams?: TSTypeParameterInstantiation, + prev?: ETSTypeReferencePart +): ETSTypeReferencePart { + if ( + isSameNativeObject(name, original.name) && + isSameNativeObject(typeParams, original.typeParams) && + isSameNativeObject(prev, original.previous) + ) { + return original; + } + + const update = updateThenAttach(ETSTypeReferencePart.updateETSTypeReferencePart, attachModifiers); + return update(original, name, typeParams, prev); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSUndefinedType.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSUndefinedType.ts new file mode 100644 index 000000000..f88a53794 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSUndefinedType.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ETSUndefinedType } from '../../generated'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateETSUndefinedType(original: ETSUndefinedType): ETSUndefinedType { + /* TODO: no getter provided yet */ + + const update = updateThenAttach(ETSUndefinedType.updateETSUndefinedType, attachModifiers); + return update(original); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ETSUnionType.ts b/koala-wrapper/src/arkts-api/node-utilities/ETSUnionType.ts new file mode 100644 index 000000000..c8dc20720 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ETSUnionType.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ETSUnionType, TypeNode } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateETSUnionType(original: ETSUnionType, types: readonly TypeNode[]): ETSUnionType { + if (isSameNativeObject(types, original.types)) { + return original; + } + + const update = updateThenAttach(ETSUnionType.updateETSUnionType, attachModifiers); + return update(original, types); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ExpressionStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/ExpressionStatement.ts new file mode 100644 index 000000000..4950ba1ff --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ExpressionStatement.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { ExpressionStatement } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateExpressionStatement(original: ExpressionStatement, expression: AstNode): ExpressionStatement { + if (isSameNativeObject(expression, original.expression)) { + return original; + } + + const update = updateThenAttach(ExpressionStatement.update, attachModifiers); + return update(original, expression); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/FunctionDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/FunctionDeclaration.ts new file mode 100644 index 000000000..7a579c288 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/FunctionDeclaration.ts @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AnnotationUsage, ScriptFunction } from '../../generated'; +import { FunctionDeclaration } from '../types'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateFunctionDeclaration( + original: FunctionDeclaration, + scriptFunction: ScriptFunction, + isAnon: boolean, + annotations?: AnnotationUsage[] +): FunctionDeclaration { + if ( + isSameNativeObject(scriptFunction, original.scriptFunction) && + isSameNativeObject(isAnon, original.isAnon) && + isSameNativeObject(annotations, original.annotations) + ) { + return original; + } + + const update = updateThenAttach(FunctionDeclaration.update, attachModifiers); + return update(original, scriptFunction, isAnon, annotations); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/FunctionExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/FunctionExpression.ts new file mode 100644 index 000000000..ba2135801 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/FunctionExpression.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ScriptFunction } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { FunctionExpression } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateFunctionExpression(original: FunctionExpression, expression: ScriptFunction): FunctionExpression { + if (isSameNativeObject(expression, original.scriptFunction)) { + return original; + } + + const update = updateThenAttach(FunctionExpression.update, attachModifiers); + return update(original, expression); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/Identifier.ts b/koala-wrapper/src/arkts-api/node-utilities/Identifier.ts new file mode 100644 index 000000000..f31d25fc6 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/Identifier.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Identifier, TypeNode } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateIdentifier(original: Identifier, name: string, typeAnnotation?: TypeNode): Identifier { + if (isSameNativeObject(name, original.name) && isSameNativeObject(typeAnnotation, original.typeAnnotation)) { + return original; + } + + const update = updateThenAttach(Identifier.update2Identifier, attachModifiers); + return update(original, name, typeAnnotation); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/IfStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/IfStatement.ts new file mode 100644 index 000000000..2e3e9275c --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/IfStatement.ts @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { IfStatement } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateIfStatement( + original: IfStatement, + test: AstNode, + consequent: AstNode, + alternate?: AstNode +): IfStatement { + if ( + isSameNativeObject(test, original.test) && + isSameNativeObject(consequent, original.consequent) && + isSameNativeObject(alternate, original.alternate) + ) { + return original; + } + + const update = updateThenAttach(IfStatement.update, attachModifiers); + return update(original, test, consequent, alternate); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ImportSpecifier.ts b/koala-wrapper/src/arkts-api/node-utilities/ImportSpecifier.ts new file mode 100644 index 000000000..d09684550 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ImportSpecifier.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Identifier, ImportSpecifier } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateImportSpecifier( + original: ImportSpecifier, + imported?: Identifier, + local?: Identifier +): ImportSpecifier { + if (isSameNativeObject(imported, original.imported) && isSameNativeObject(local, original.local)) { + return original; + } + + const update = updateThenAttach(ImportSpecifier.updateImportSpecifier, attachModifiers); + return update(original, imported, local); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/MemberExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/MemberExpression.ts new file mode 100644 index 000000000..960dacfaf --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/MemberExpression.ts @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { MemberExpression } from '../to-be-generated/MemberExpression'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaMemberExpressionKind } from '../../generated/Es2pandaEnums'; + +export function updateMemberExpression( + original: MemberExpression, + object: AstNode, + property: AstNode, + kind: Es2pandaMemberExpressionKind, + computed: boolean, + optional: boolean +): MemberExpression { + if ( + isSameNativeObject(object, original.object) && + isSameNativeObject(property, original.property) && + isSameNativeObject(kind, original.kind) && + isSameNativeObject(computed, original.computed) && + isSameNativeObject(optional, original.optional) + ) { + return original; + } + + const update = updateThenAttach(MemberExpression.update, attachModifiers); + return update(original, object, property, kind, computed, optional); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts b/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts new file mode 100644 index 000000000..44afa1dbc --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KInt } from '@koalaui/interop'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { MethodDefinition } from '../types'; +import { updateThenAttach } from '../utilities/private'; +import { Es2pandaMethodDefinitionKind } from '../../generated/Es2pandaEnums'; + +export function updateMethodDefinition( + original: MethodDefinition, + kind: Es2pandaMethodDefinitionKind, + key: AstNode, + value: AstNode, + modifiers: KInt, + isComputed: boolean +): MethodDefinition { + if ( + isSameNativeObject(kind, original.kind) && + isSameNativeObject(key, original.name) && + isSameNativeObject(value, original.scriptFunction) && + isSameNativeObject(modifiers, original.modifiers) + /* TODO: no getter for isComputed */ + ) { + return original; + } + + const update = updateThenAttach(MethodDefinition.update, (node: MethodDefinition, original: MethodDefinition) => + node.setOverloads(original.overloads) + ); + return update(original, kind, key, value, modifiers, isComputed); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/NullLiteral.ts b/koala-wrapper/src/arkts-api/node-utilities/NullLiteral.ts new file mode 100644 index 000000000..9ab1bb363 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/NullLiteral.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NullLiteral } from '../../generated'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateNullLiteral(original: NullLiteral): NullLiteral { + /* TODO: no getter provided yet */ + + const update = updateThenAttach(NullLiteral.updateNullLiteral, attachModifiers); + return update(original); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/NumberLiteral.ts b/koala-wrapper/src/arkts-api/node-utilities/NumberLiteral.ts new file mode 100644 index 000000000..1dfab1450 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/NumberLiteral.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NumberLiteral } from '../types'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, compose, updateThenAttach } from '../utilities/private'; + +export function updateNumberLiteral(original: NumberLiteral, value: number): NumberLiteral { + if (isSameNativeObject(value, original.value)) { + return original; + } + + const update = updateThenAttach( + compose(NumberLiteral.create), // TODO: No UpdateNumberLiteral, need to change this + attachModifiers + ); + return update(original, value); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ReturnStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/ReturnStatement.ts new file mode 100644 index 000000000..9fc05a371 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ReturnStatement.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Expression, ReturnStatement } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateReturnStatement(original: ReturnStatement, argument?: Expression): ReturnStatement { + if (isSameNativeObject(argument, original.argument)) { + return original; + } + + const update = updateThenAttach(ReturnStatement.update1ReturnStatement, attachModifiers); + return update(original, argument); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ScriptFunction.ts b/koala-wrapper/src/arkts-api/node-utilities/ScriptFunction.ts new file mode 100644 index 000000000..745a5398c --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ScriptFunction.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { FunctionSignature, ScriptFunction } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { updateThenAttach } from '../utilities/private'; + +export function updateScriptFunction( + original: ScriptFunction, + databody: AstNode | undefined, + datasignature: FunctionSignature | undefined, + datafuncFlags: number, + dataflags: number +): ScriptFunction { + if ( + isSameNativeObject(databody, original.body) && + isSameNativeObject(datasignature?.params, original.params) && + isSameNativeObject(datasignature?.typeParams, original.typeParams) && + isSameNativeObject(datasignature?.returnType, original.returnTypeAnnotation) && + isSameNativeObject(datasignature?.hasReceiver, original.hasReceiver) && + isSameNativeObject(datafuncFlags, original.flags) && + isSameNativeObject(dataflags, original.modifiers) + ) { + return original; + } + + const update = updateThenAttach( + ScriptFunction.updateScriptFunction, + (node: ScriptFunction, original: ScriptFunction) => (!!original.id ? node.setIdent(original.id) : node), + (node: ScriptFunction, original: ScriptFunction) => node.setAnnotations(original.annotations) + ); + return update(original, databody, datasignature, datafuncFlags, dataflags); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/StringLiteral.ts b/koala-wrapper/src/arkts-api/node-utilities/StringLiteral.ts new file mode 100644 index 000000000..53f330d42 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/StringLiteral.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { StringLiteral } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateStringLiteral(original: StringLiteral, str: string): StringLiteral { + if (isSameNativeObject(str, original.str)) { + return original; + } + + const update = updateThenAttach(StringLiteral.update1StringLiteral, attachModifiers); + return update(original, str); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/StructDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/StructDeclaration.ts new file mode 100644 index 000000000..ee57547d2 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/StructDeclaration.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClassDefinition } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { StructDeclaration } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateStructDeclaration(original: StructDeclaration, definition: ClassDefinition): StructDeclaration { + if (isSameNativeObject(definition, original.definition)) { + return original; + } + + const update = updateThenAttach(StructDeclaration.update, attachModifiers); + return update(original, definition); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/SuperExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/SuperExpression.ts new file mode 100644 index 000000000..d1bee071b --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/SuperExpression.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { SuperExpression } from '../../generated'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateSuperExpression(original: SuperExpression): SuperExpression { + /* TODO: no getter provided yet */ + + const update = updateThenAttach(SuperExpression.updateSuperExpression, attachModifiers); + return update(original); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSAsExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/TSAsExpression.ts new file mode 100644 index 000000000..f82b8afc1 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TSAsExpression.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Expression, TSAsExpression, TypeNode } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTSAsExpression( + original: TSAsExpression, + expression: Expression | undefined, + typeAnnotation: TypeNode | undefined, + isConst: boolean +): TSAsExpression { + if ( + isSameNativeObject(expression, original.expr) && + isSameNativeObject(typeAnnotation, original.typeAnnotation) && + isSameNativeObject(isConst, original.isConst) + ) { + return original; + } + + const update = updateThenAttach(TSAsExpression.updateTSAsExpression, attachModifiers); + return update(original, expression, typeAnnotation, isConst); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceBody.ts b/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceBody.ts new file mode 100644 index 000000000..a1a6350f7 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceBody.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TSInterfaceBody } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTSInterfaceBody(original: TSInterfaceBody, body: readonly AstNode[]): TSInterfaceBody { + if (isSameNativeObject(body, original.body)) { + return original; + } + + const update = updateThenAttach(TSInterfaceBody.updateTSInterfaceBody, attachModifiers); + return update(original, body); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceDeclaration.ts new file mode 100644 index 000000000..d268c5d82 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceDeclaration.ts @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TSInterfaceDeclaration, TSInterfaceHeritage } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { AstNode } from '../peers/AstNode'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTSInterfaceDeclaration( + original: TSInterfaceDeclaration, + _extends: readonly TSInterfaceHeritage[], + id: AstNode | undefined, + typeParams: AstNode | undefined, + body: AstNode | undefined, + isStatic: boolean, + isExternal: boolean +): TSInterfaceDeclaration { + if ( + isSameNativeObject(_extends, original.extends) && + isSameNativeObject(id, original.id) && + isSameNativeObject(typeParams, original.typeParams) && + isSameNativeObject(body, original.body) && + isSameNativeObject(isStatic, original.isStatic) && + isSameNativeObject(isExternal, original.isFromExternal) + ) { + return original; + } + + const update = updateThenAttach(TSInterfaceDeclaration.updateTSInterfaceDeclaration, attachModifiers); + return update(original, _extends, id, typeParams, body, isStatic, isExternal); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSNonNullExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/TSNonNullExpression.ts new file mode 100644 index 000000000..d387e39f9 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TSNonNullExpression.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Expression, TSNonNullExpression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTSNonNullExpression(original: TSNonNullExpression, expr?: Expression): TSNonNullExpression { + if (isSameNativeObject(expr, original.expr)) { + return original; + } + + const update = updateThenAttach(TSNonNullExpression.updateTSNonNullExpression, attachModifiers); + return update(original, expr); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSTypeAliasDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/TSTypeAliasDeclaration.ts new file mode 100644 index 000000000..3531ee3a9 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TSTypeAliasDeclaration.ts @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Identifier, TSTypeAliasDeclaration, TSTypeParameterDeclaration, TypeNode } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTSTypeAliasDeclaration( + original: TSTypeAliasDeclaration, + id?: Identifier, + typeParams?: TSTypeParameterDeclaration, + typeAnnotation?: TypeNode +): TSTypeAliasDeclaration { + if ( + isSameNativeObject(id, original.id) && + isSameNativeObject(typeParams, original.typeParams) && + isSameNativeObject(typeAnnotation, original.typeAnnotation) + ) { + return original; + } + + const update = updateThenAttach( + TSTypeAliasDeclaration.updateTSTypeAliasDeclaration, + attachModifiers, + (node: TSTypeAliasDeclaration, original: TSTypeAliasDeclaration) => node.setAnnotations(original.annotations) + ); + return update(original, id, typeParams, typeAnnotation); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameter.ts b/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameter.ts new file mode 100644 index 000000000..9a5ac75d5 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameter.ts @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Identifier, TSTypeParameter, TypeNode } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTSTypeParameter( + original: TSTypeParameter, + name?: Identifier, + constraint?: TypeNode, + defaultType?: TypeNode +): TSTypeParameter { + if ( + isSameNativeObject(name, original.name) && + isSameNativeObject(constraint, original.constraint) && + isSameNativeObject(defaultType, original.defaultType) + ) { + return original; + } + + const update = updateThenAttach(TSTypeParameter.updateTSTypeParameter, attachModifiers); + return update(original, name, constraint, defaultType); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameterDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameterDeclaration.ts new file mode 100644 index 000000000..3f1395049 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameterDeclaration.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TSTypeParameter, TSTypeParameterDeclaration } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTSTypeParameterDeclaration( + original: TSTypeParameterDeclaration, + params: readonly TSTypeParameter[], + requiredParams: number +): TSTypeParameterDeclaration { + if (isSameNativeObject(params, original.params) && isSameNativeObject(requiredParams, original.requiredParams)) { + return original; + } + + const update = updateThenAttach(TSTypeParameterDeclaration.updateTSTypeParameterDeclaration, attachModifiers); + return update(original, params, requiredParams); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameterInstantiation.ts b/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameterInstantiation.ts new file mode 100644 index 000000000..49d8746e4 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TSTypeParameterInstantiation.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TSTypeParameterInstantiation, TypeNode } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTSTypeParameterInstantiation( + original: TSTypeParameterInstantiation, + params: readonly TypeNode[] +): TSTypeParameterInstantiation { + if (isSameNativeObject(params, original.params)) { + return original; + } + + const update = updateThenAttach(TSTypeParameterInstantiation.updateTSTypeParameterInstantiation, attachModifiers); + return update(original, params); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ThisExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ThisExpression.ts new file mode 100644 index 000000000..f2f04c716 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ThisExpression.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ThisExpression } from '../../generated'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateThisExpression(original: ThisExpression): ThisExpression { + /* TODO: no getter provided yet */ + + const update = updateThenAttach(ThisExpression.updateThisExpression, attachModifiers); + return update(original); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/UndefinedLiteral.ts b/koala-wrapper/src/arkts-api/node-utilities/UndefinedLiteral.ts new file mode 100644 index 000000000..aaedc726c --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/UndefinedLiteral.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { UndefinedLiteral } from '../../generated'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateUndefinedLiteral(original: UndefinedLiteral): UndefinedLiteral { + /* TODO: no getter provided yet */ + + const update = updateThenAttach(UndefinedLiteral.updateUndefinedLiteral, attachModifiers); + return update(original); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts new file mode 100644 index 000000000..24432ec6d --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { KInt } from '@koalaui/interop'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { VariableDeclaration, VariableDeclarator } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaVariableDeclarationKind } from '../../generated/Es2pandaEnums'; + +export function updateVariableDeclaration( + original: VariableDeclaration, + modifiers: KInt, + kind: Es2pandaVariableDeclarationKind, + declarators: readonly VariableDeclarator[] +): VariableDeclaration { + if ( + isSameNativeObject(modifiers, original.modifiers) && + isSameNativeObject(kind, original.declarationKind) && + isSameNativeObject(declarators, original.declarators) + ) { + return original; + } + + const update = updateThenAttach(VariableDeclaration.update, attachModifiers); + return update(original, modifiers, kind, declarators); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/VariableDeclarator.ts b/koala-wrapper/src/arkts-api/node-utilities/VariableDeclarator.ts new file mode 100644 index 000000000..52c002fd3 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/VariableDeclarator.ts @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Identifier } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { VariableDeclarator } from '../types'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaVariableDeclaratorFlag } from '../../generated/Es2pandaEnums'; +import { AstNode } from '../peers/AstNode'; + +export function updateVariableDeclarator( + original: VariableDeclarator, + flag: Es2pandaVariableDeclaratorFlag, + name: Identifier, + initializer: AstNode | undefined +): VariableDeclarator { + if ( + isSameNativeObject(name, original.name) && + isSameNativeObject(initializer, original.initializer) + /* TODO: no getter for flag */ + ) { + return original; + } + + const update = updateThenAttach(VariableDeclarator.update, attachModifiers); + return update(original, flag, name, initializer); +} diff --git a/koala-wrapper/src/arkts-api/peers/ArktsObject.ts b/koala-wrapper/src/arkts-api/peers/ArktsObject.ts index 9bd967b5d..bfa1e6e09 100644 --- a/koala-wrapper/src/arkts-api/peers/ArktsObject.ts +++ b/koala-wrapper/src/arkts-api/peers/ArktsObject.ts @@ -13,12 +13,33 @@ * limitations under the License. */ -import { KNativePointer } from "@koalaui/interop" +import { KNativePointer } from '@koalaui/interop'; export abstract class ArktsObject { protected constructor(peer: KNativePointer) { - this.peer = peer + this.peer = peer; } - readonly peer: KNativePointer + readonly peer: KNativePointer; +} + +export function isSameNativeObject( + first: T | readonly T[], + second: T | readonly T[] +): boolean { + if (Array.isArray(first) && Array.isArray(second)) { + if (first.length !== second.length) { + return false; + } + for (let i = 0; i < first.length; i++) { + if (!isSameNativeObject(first[i], second[i])) { + return false; + } + } + return true; + } + if (first instanceof ArktsObject && second instanceof ArktsObject) { + return first?.peer === second?.peer; + } + return first === second; } diff --git a/koala-wrapper/src/arkts-api/to-be-generated/MemberExpression.ts b/koala-wrapper/src/arkts-api/to-be-generated/MemberExpression.ts index a8f50ec11..0a953323a 100644 --- a/koala-wrapper/src/arkts-api/to-be-generated/MemberExpression.ts +++ b/koala-wrapper/src/arkts-api/to-be-generated/MemberExpression.ts @@ -13,8 +13,7 @@ * limitations under the License. */ - -import { Expression } from "../../generated" +import { Expression } from '../../generated'; import { assertValidPeer, AstNode, @@ -23,13 +22,13 @@ import { KNativePointer, passNode, unpackNonNullableNode, - global -} from "../../reexport-for-generated" + global, +} from '../../reexport-for-generated'; export class MemberExpression extends Expression { constructor(peer: KNativePointer) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION) - super(peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION); + super(peer); } static create( @@ -48,7 +47,7 @@ export class MemberExpression extends Expression { computed, optional ) - ) + ); } static update( @@ -69,30 +68,41 @@ export class MemberExpression extends Expression { computed, optional ) - ) + ); } protected override dumpMessage(): string { - return ` ` + return ` `; } get object(): AstNode { - return unpackNonNullableNode(global.generatedEs2panda._MemberExpressionObject(global.context, this.peer)) + return unpackNonNullableNode(global.generatedEs2panda._MemberExpressionObject(global.context, this.peer)); } get property(): AstNode { - return unpackNonNullableNode(global.generatedEs2panda._MemberExpressionProperty(global.context, this.peer)) + return unpackNonNullableNode(global.generatedEs2panda._MemberExpressionProperty(global.context, this.peer)); } get kind(): Es2pandaMemberExpressionKind { - return global.generatedEs2panda._MemberExpressionKindConst(global.context, this.peer) + return global.generatedEs2panda._MemberExpressionKindConst(global.context, this.peer); } get computed(): boolean { - return global.generatedEs2panda._MemberExpressionIsComputedConst(global.context, this.peer) + return global.generatedEs2panda._MemberExpressionIsComputedConst(global.context, this.peer); } get optional(): boolean { - return false // todo: no corresponding method in es2panda + return false; // todo: no corresponding method in es2panda + } + + /** @deprecated */ + setObject(object_arg?: Expression): this { + global.generatedEs2panda._MemberExpressionSetObject(global.context, this.peer, passNode(object_arg)); + return this; + } + /** @deprecated */ + setProperty(prop?: Expression): this { + global.generatedEs2panda._MemberExpressionSetProperty(global.context, this.peer, passNode(prop)); + return this; } -} \ No newline at end of file +} diff --git a/koala-wrapper/src/arkts-api/types.ts b/koala-wrapper/src/arkts-api/types.ts index b4aaae91a..3faf2f690 100644 --- a/koala-wrapper/src/arkts-api/types.ts +++ b/koala-wrapper/src/arkts-api/types.ts @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { global } from "./static/global" -import { KInt, KNativePointer, KNativePointer as KPtr, nullptr } from "@koalaui/interop" +import { global } from './static/global'; +import { KInt, KNativePointer, KNativePointer as KPtr, nullptr } from '@koalaui/interop'; import { Es2pandaContextState, Es2pandaMethodDefinitionKind, @@ -22,7 +22,7 @@ import { Es2pandaTokenType, Es2pandaVariableDeclarationKind, Es2pandaVariableDeclaratorFlag, -} from "../generated/Es2pandaEnums" +} from '../generated/Es2pandaEnums'; import { allFlags, arrayOfNullptr, @@ -36,16 +36,16 @@ import { unpackNonNullableNode, unpackString, updatePeerByNode, -} from "./utilities/private" -import { proceedToState } from "./utilities/public" -import { Es2pandaAstNodeType } from "../Es2pandaEnums" -import { AstNode } from "./peers/AstNode" -import { ArktsObject } from "./peers/ArktsObject" -import { Config } from "./peers/Config" -import { Context } from "./peers/Context" -import * as path from "node:path" -import { nodeByType } from "./class-by-peer" -import { MemberExpression } from "./to-be-generated/MemberExpression" +} from './utilities/private'; +import { proceedToState } from './utilities/public'; +import { Es2pandaAstNodeType } from '../Es2pandaEnums'; +import { AstNode } from './peers/AstNode'; +import { ArktsObject } from './peers/ArktsObject'; +import { Config } from './peers/Config'; +import { Context } from './peers/Context'; +import * as path from 'node:path'; +import { nodeByType } from './class-by-peer'; +import { MemberExpression } from './to-be-generated/MemberExpression'; import { AnnotationUsage, BlockStatement, @@ -62,24 +62,20 @@ import { StringLiteral, TSTypeParameterDeclaration, TSTypeParameterInstantiation, - TypeNode -} from "../generated" + TypeNode, +} from '../generated'; export class EtsScript extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) - super(peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE); + super(peer); } - // TODO: - // static create( - // statementList: Statement[] - // ): EtsScript { - // } - static fromContext(): EtsScript { - console.log("[TS WRAPPER] GET AST FROM CONTEXT"); - return new EtsScript(global.es2panda._ProgramAst(global.context, global.es2panda._ContextProgram(global.context))) + console.log('[TS WRAPPER] GET AST FROM CONTEXT'); + return new EtsScript( + global.es2panda._ProgramAst(global.context, global.es2panda._ContextProgram(global.context)) + ); } /** @@ -87,68 +83,73 @@ export class EtsScript extends AstNode { */ static createFromSource( source: string, - state: Es2pandaContextState = Es2pandaContextState.ES2PANDA_STATE_PARSED, + state: Es2pandaContextState = Es2pandaContextState.ES2PANDA_STATE_PARSED ): EtsScript { if (!global.configIsInitialized()) { - global.config = Config.createDefault().peer + global.config = Config.createDefault().peer; } - global.compilerContext = Context.createFromString(source) - proceedToState(state) - return new EtsScript(global.es2panda._ProgramAst(global.context, global.es2panda._ContextProgram(global.context))) + global.compilerContext = Context.createFromString(source); + proceedToState(state); + return new EtsScript( + global.es2panda._ProgramAst(global.context, global.es2panda._ContextProgram(global.context)) + ); } /** * @deprecated */ - static updateByStatements( - node: EtsScript, - statements: readonly AstNode[], - ): EtsScript { - global.generatedEs2panda._BlockStatementSetStatements(global.context, node.peer, passNodeArray(statements), statements.length) - return node + static updateByStatements(node: EtsScript, statements: readonly AstNode[]): EtsScript { + global.generatedEs2panda._BlockStatementSetStatements( + global.context, + node.peer, + passNodeArray(statements), + statements.length + ); + return node; } get statements(): readonly AstNode[] { - return unpackNodeArray(global.generatedEs2panda._BlockStatementStatements(global.context, this.peer)) + return unpackNodeArray(global.generatedEs2panda._BlockStatementStatements(global.context, this.peer)); } set statements(nodes: readonly AstNode[]) { - global.generatedEs2panda._BlockStatementSetStatements(global.context, this.peer, passNodeArray(nodes), nodes.length) + global.generatedEs2panda._BlockStatementSetStatements( + global.context, + this.peer, + passNodeArray(nodes), + nodes.length + ); } } export class ExpressionStatement extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT) - super(peer) - this.expression = unpackNonNullableNode(global.generatedEs2panda._ExpressionStatementGetExpression(global.context, this.peer)) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT); + super(peer); } - static create( - expression: AstNode, - ): ExpressionStatement { + static create(expression: AstNode): ExpressionStatement { return new ExpressionStatement( - global.generatedEs2panda._CreateExpressionStatement( - global.context, - expression.peer - ) - ) + global.generatedEs2panda._CreateExpressionStatement(global.context, expression.peer) + ); } - static update( - node: ExpressionStatement, - expression: AstNode, - ): ExpressionStatement { + static update(node: ExpressionStatement, expression: AstNode): ExpressionStatement { return new ExpressionStatement( - global.generatedEs2panda._UpdateExpressionStatement( - global.context, - node.peer, - expression.peer - ) - ) + global.generatedEs2panda._UpdateExpressionStatement(global.context, node.peer, expression.peer) + ); } - readonly expression: AstNode + get expression(): AstNode { + return unpackNonNullableNode( + global.generatedEs2panda._ExpressionStatementGetExpressionConst(global.context, this.peer) + ); + } + /** @deprecated */ + setExpression(expr?: Expression): this { + global.generatedEs2panda._ExpressionStatementSetExpression(global.context, this.peer, passNode(expr)); + return this; + } } // TODO: @@ -156,15 +157,21 @@ export class ExpressionStatement extends AstNode { // Need to clarify with the compiler people if they will provide create signature with a trailing block argument. export class CallExpression extends Expression { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION) - super(peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION); + super(peer); this.expression = unpackNonNullableNode( - global.generatedEs2panda._CallExpressionCallee(global.context, this.peer)) - const tsTypeParameterInstantiation = unpackNode(global.generatedEs2panda._CallExpressionTypeParams(global.context, this.peer)) - this.typeArguments = tsTypeParameterInstantiation ? - unpackNodeArray(global.generatedEs2panda._TSTypeParameterInstantiationParamsConst(global.context, tsTypeParameterInstantiation.peer)) : undefined - this.arguments = unpackNodeArray( - global.generatedEs2panda._CallExpressionArguments(global.context, this.peer)) + global.generatedEs2panda._CallExpressionCallee(global.context, this.peer) + ); + this.typeParams = unpackNode(global.generatedEs2panda._CallExpressionTypeParams(global.context, this.peer)); + this.typeArguments = this.typeParams + ? unpackNodeArray( + global.generatedEs2panda._TSTypeParameterInstantiationParamsConst( + global.context, + this.typeParams.peer + ) + ) + : undefined; + this.arguments = unpackNodeArray(global.generatedEs2panda._CallExpressionArguments(global.context, this.peer)); } static create( @@ -179,11 +186,13 @@ export class CallExpression extends Expression { passNode(expression), passNodeArray(args), args?.length ?? 0, - typeArguments ? passNode(TSTypeParameterInstantiation.createTSTypeParameterInstantiation(typeArguments)) : nullptr, + typeArguments + ? passNode(TSTypeParameterInstantiation.createTSTypeParameterInstantiation(typeArguments)) + : nullptr, isOptional, trailingComma - ) - return new CallExpression(peer) + ); + return new CallExpression(peer); } static update( @@ -200,17 +209,17 @@ export class CallExpression extends Expression { passNode(expression), passNodeArray(args), args?.length ?? 0, - typeArguments ? passNode(TSTypeParameterInstantiation.createTSTypeParameterInstantiation(typeArguments)) : nullptr, + typeArguments + ? passNode(TSTypeParameterInstantiation.createTSTypeParameterInstantiation(typeArguments)) + : nullptr, isOptional, trailingComma - ) - return new CallExpression(peer) + ); + return new CallExpression(peer); } get trailingBlock(): BlockStatement | undefined { - return unpackNode( - global.generatedEs2panda._CallExpressionTrailingBlockConst(global.context, this.peer) - ); + return unpackNode(global.generatedEs2panda._CallExpressionTrailingBlockConst(global.context, this.peer)); } setTralingBlock(trailingBlock: BlockStatement | undefined): this { @@ -219,22 +228,31 @@ export class CallExpression extends Expression { return this; } - readonly expression: AstNode // Expression - readonly typeArguments: readonly TypeNode[] | undefined - readonly arguments: readonly Expression[] + /** @deprecated */ + setCallee(callee?: Expression): this { + global.generatedEs2panda._CallExpressionSetCallee(global.context, this.peer, passNode(callee)); + return this; + } + + /** @deprecated */ + setTypeParams(typeParams?: TSTypeParameterInstantiation): this { + global.generatedEs2panda._CallExpressionSetTypeParams(global.context, this.peer, passNode(typeParams)); + return this; + } + + readonly expression: AstNode; // Expression + readonly typeArguments: readonly TypeNode[] | undefined; + readonly arguments: readonly Expression[]; + readonly typeParams: TSTypeParameterInstantiation | undefined; } export class AssignmentExpression extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ASSIGNMENT_EXPRESSION) - super(peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ASSIGNMENT_EXPRESSION); + super(peer); } - static create( - left: AstNode, - assignmentOperator: Es2pandaTokenType, - right: AstNode - ): AssignmentExpression { + static create(left: AstNode, assignmentOperator: Es2pandaTokenType, right: AstNode): AssignmentExpression { return new AssignmentExpression( global.generatedEs2panda._CreateAssignmentExpression( global.context, @@ -242,7 +260,7 @@ export class AssignmentExpression extends AstNode { passNode(right), assignmentOperator ) - ) + ); } static update( @@ -259,213 +277,94 @@ export class AssignmentExpression extends AstNode { passNode(right), assignmentOperator ) - ) + ); + } + + get left(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AssignmentExpressionLeftConst(global.context, this.peer)); + } + get right(): Expression | undefined { + return unpackNode(global.generatedEs2panda._AssignmentExpressionRightConst(global.context, this.peer)); + } + get operatorType(): Es2pandaTokenType { + return global.generatedEs2panda._AssignmentExpressionOperatorTypeConst(global.context, this.peer); + } + /** @deprecated */ + setRight(expr?: Expression): this { + global.generatedEs2panda._AssignmentExpressionSetRight(global.context, this.peer, passNode(expr)); + return this; + } + /** @deprecated */ + setLeft(expr?: Expression): this { + global.generatedEs2panda._AssignmentExpressionSetLeft(global.context, this.peer, passNode(expr)); + return this; + } + setOperatorType(operatorType: Es2pandaTokenType): this { + global.generatedEs2panda._AssignmentExpressionSetOperatorType(global.context, this.peer, operatorType); + return this; } } export class TSUnionType extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE) - super(peer) - this.types = unpackNodeArray(global.generatedEs2panda._TSUnionTypeTypesConst(global.context, this.peer)) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE); + super(peer); + this.types = unpackNodeArray(global.generatedEs2panda._TSUnionTypeTypesConst(global.context, this.peer)); } - static create( - node: undefined | TSUnionType, - types: AstNode[], - ): TSUnionType { + static create(node: undefined | TSUnionType, types: AstNode[]): TSUnionType { return new TSUnionType( updatePeerByNode( - global.generatedEs2panda._CreateTSUnionType( - global.context, - passNodeArray(types), - types.length - ), + global.generatedEs2panda._CreateTSUnionType(global.context, passNodeArray(types), types.length), node ) - ) + ); } - readonly types: readonly AstNode[] + readonly types: readonly AstNode[]; } export class NumberLiteral extends Literal { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL) - super(peer) - this.value = 0.0 + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL); + super(peer); + this.value = 0.0; } - static create( - value: number, - ): NumberLiteral { - return new NumberLiteral( - global.es2panda._CreateNumberLiteral( - global.context, - value - ) - ) + static create(value: number): NumberLiteral { + return new NumberLiteral(global.es2panda._CreateNumberLiteral(global.context, value)); } protected override dumpMessage(): string { - return ` ` + return ` `; } - readonly value: number = 0.0 + readonly value: number = 0.0; } -// export class ScriptFunction extends AstNode { -// constructor(peer: KPtr) { -// assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION) -// super(peer) -// this.parameters = unpackNodeArray(global.generatedEs2panda._ScriptFunctionParams(global.context, this.peer)) -// this.typeParamsDecl = unpackNode(global.generatedEs2panda._ScriptFunctionTypeParams(global.context, this.peer)) -// this.returnTypeAnnotation = unpackNode(global.generatedEs2panda._ScriptFunctionReturnTypeAnnotation(global.context, this.peer)) -// this.body = unpackNode(global.generatedEs2panda._ScriptFunctionBody(global.context, this.peer)) -// // this.signature = unpackNode(global.generatedEs2panda._ScriptFunctionSignature(global.context, this.peer)) -// // this.declare = global.generatedEs2panda._ScriptFunctionDeclareConst(global.context, this.peer) -// this.ident = unpackNode(global.generatedEs2panda._ScriptFunctionId(global.context, this.peer)) - -// this.scriptFunctionFlags = this._correctScriptFunctionFlags() -// } - -// static create( -// body: AstNode | undefined, -// functionFlags: Es2pandaScriptFunctionFlags, -// modifierFlags: Es2pandaModifierFlags, -// declare: boolean, -// ident: Identifier | undefined, -// parameters: ETSParameterExpression[]|undefined, -// typeParamsDecl: TSTypeParameterDeclaration|undefined, -// returnTypeAnnotation: TypeNode|undefined, -// annotations?: AnnotationUsage[], -// ): ScriptFunction { -// const peer = global.generatedEs2panda._CreateScriptFunction( -// global.context, -// passNode(body), -// FunctionSignature.createFunctionSignature( -// typeParamsDecl, -// parameters ?? [], -// returnTypeAnnotation, -// false -// ).peer, -// functionFlags, -// modifierFlags -// ) -// if (ident !== undefined) { -// global.generatedEs2panda._ScriptFunctionSetIdent(global.context, peer, ident.peer) -// } -// const res = new ScriptFunction(peer) -// if (annotations) { -// res.annotations = annotations -// } -// return res -// } - -// setIdent(id: Identifier): ScriptFunction { -// assertValidPeer(id.peer, Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER); -// global.generatedEs2panda._ScriptFunctionSetIdent(global.context, this.peer, id.peer); -// return this; -// } - -// protected override dumpMessage(): string { -// const scriptFunctionFlags = global.generatedEs2panda._ScriptFunctionFlagsConst(global.context, this.peer) -// return ` ` -// } - -// private _correctScriptFunctionFlags(): KInt { -// let flags: KInt = global.generatedEs2panda._ScriptFunctionFlagsConst(global.context, this.peer) -// if (this._hasReturn()) { -// flags |= Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_HAS_RETURN -// global.generatedEs2panda._ScriptFunctionAddFlag(global.context, this.peer, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_HAS_RETURN) -// } -// if (this._isAsync()) { -// flags |= Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC -// global.generatedEs2panda._ScriptFunctionAddFlag(global.context, this.peer, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC) -// } -// return flags -// } - -// private _hasReturn(): boolean { -// if (this.body === undefined) { -// return false -// } -// let hasReturn: boolean = false -// // TODO: goes through whole subtree, optimizable (unnecessary now) -// this.body.getSubtree().forEach( -// (node: AstNode) => { -// hasReturn = hasReturn || nodeType(node) === Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT -// } -// ) -// return hasReturn -// } - -// private _isAsync(): boolean { -// return (this.modifiers & Es2pandaModifierFlags.MODIFIER_FLAGS_ASYNC) !== 0 -// } - -// readonly parameters: ETSParameterExpression[] -// readonly typeParamsDecl?: TSTypeParameterDeclaration -// readonly returnTypeAnnotation: TypeNode | undefined -// readonly body?: BlockStatement -// // readonly signature: FunctionSignature -// readonly scriptFunctionFlags: KInt -// readonly ident?: Identifier - -// get annotations(): AnnotationUsage[] { -// return unpackNodeArray(global.es2panda._ScriptFunctionAnnotations( -// global.context, -// this.peer, -// nullptr -// )) -// } - -// set annotations(newAnnotations: AnnotationUsage[]) { -// global.es2panda._ScriptFunctionSetAnnotations( -// global.context, -// this.peer, -// passNodeArray(newAnnotations), -// newAnnotations.length -// ); -// } -// } - export class ArrowFunctionExpression extends Expression { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION) - super(peer) - this.scriptFunction = unpackNonNullableNode(global.generatedEs2panda._ArrowFunctionExpressionFunction(global.context, this.peer)) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION); + super(peer); + this.scriptFunction = unpackNonNullableNode( + global.generatedEs2panda._ArrowFunctionExpressionFunction(global.context, this.peer) + ); } - static create( - func: ScriptFunction, - ): ArrowFunctionExpression { + static create(func: ScriptFunction): ArrowFunctionExpression { return new ArrowFunctionExpression( - global.generatedEs2panda._CreateArrowFunctionExpression( - global.context, - passNode(func) - ) - ) + global.generatedEs2panda._CreateArrowFunctionExpression(global.context, passNode(func)) + ); } - static update( - node: ArrowFunctionExpression, - func: ScriptFunction, - ): ArrowFunctionExpression { + static update(node: ArrowFunctionExpression, func: ScriptFunction): ArrowFunctionExpression { return new ArrowFunctionExpression( - global.generatedEs2panda._UpdateArrowFunctionExpression( - global.context, - node.peer, - passNode(func) - ) - ) + global.generatedEs2panda._UpdateArrowFunctionExpression(global.context, node.peer, passNode(func)) + ); } get annotations(): AnnotationUsage[] { - return unpackNodeArray(global.generatedEs2panda._ArrowFunctionExpressionAnnotations( - global.context, - this.peer - )); + return unpackNodeArray(global.generatedEs2panda._ArrowFunctionExpressionAnnotations(global.context, this.peer)); } setAnnotations(annotations: AnnotationUsage[]): this { @@ -479,20 +378,28 @@ export class ArrowFunctionExpression extends Expression { return this; } - readonly scriptFunction: ScriptFunction + readonly scriptFunction: ScriptFunction; } export class FunctionDeclaration extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION) - super(peer) - this.scriptFunction = unpackNonNullableNode(global.generatedEs2panda._FunctionDeclarationFunction(global.context, this.peer)) - this.parameters = unpackNodeArray(global.generatedEs2panda._ScriptFunctionParams(global.context, this.scriptFunction.peer)) - this.name = unpackNode(global.generatedEs2panda._ScriptFunctionId(global.context, this.scriptFunction.peer)) - this.body = unpackNode(global.generatedEs2panda._ScriptFunctionBody(global.context, this.scriptFunction.peer)) - this.typeParamsDecl = unpackNode(global.generatedEs2panda._ScriptFunctionTypeParams(global.context, this.scriptFunction.peer)) - this.returnType = unpackNode(global.generatedEs2panda._ScriptFunctionReturnTypeAnnotation(global.context, this.scriptFunction.peer)) - this.isAnon = global.generatedEs2panda._FunctionDeclarationIsAnonymousConst(global.context, this.peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION); + super(peer); + this.scriptFunction = unpackNonNullableNode( + global.generatedEs2panda._FunctionDeclarationFunction(global.context, this.peer) + ); + this.parameters = unpackNodeArray( + global.generatedEs2panda._ScriptFunctionParams(global.context, this.scriptFunction.peer) + ); + this.name = unpackNode(global.generatedEs2panda._ScriptFunctionId(global.context, this.scriptFunction.peer)); + this.body = unpackNode(global.generatedEs2panda._ScriptFunctionBody(global.context, this.scriptFunction.peer)); + this.typeParamsDecl = unpackNode( + global.generatedEs2panda._ScriptFunctionTypeParams(global.context, this.scriptFunction.peer) + ); + this.returnType = unpackNode( + global.generatedEs2panda._ScriptFunctionReturnTypeAnnotation(global.context, this.scriptFunction.peer) + ); + this.isAnon = global.generatedEs2panda._FunctionDeclarationIsAnonymousConst(global.context, this.peer); } static create( @@ -509,13 +416,13 @@ export class FunctionDeclaration extends AstNode { 0, isAnon ) - ) + ); // TODO: maybe wrong - res.modifiers = scriptFunction.modifiers + res.modifiers = scriptFunction.modifiers; if (annotations) { - res.annotations = annotations + res.annotations = annotations; } - return res + return res; } static update( @@ -534,91 +441,80 @@ export class FunctionDeclaration extends AstNode { 0, isAnon ) - ) + ); if (annotations) { - res.annotations = annotations + res.annotations = annotations; } - return res + return res; } get annotations(): AnnotationUsage[] { - return unpackNodeArray(global.generatedEs2panda._FunctionDeclarationAnnotationsConst(global.context, this.peer)) + return unpackNodeArray( + global.generatedEs2panda._FunctionDeclarationAnnotationsConst(global.context, this.peer) + ); } set annotations(newAnnotations: AnnotationUsage[]) { - global.generatedEs2panda._FunctionDeclarationSetAnnotations(global.context, this.peer, passNodeArray(newAnnotations), newAnnotations.length) + global.generatedEs2panda._FunctionDeclarationSetAnnotations( + global.context, + this.peer, + passNodeArray(newAnnotations), + newAnnotations.length + ); } - readonly scriptFunction: ScriptFunction - readonly parameters: readonly AstNode[] - readonly name?: Identifier - readonly body?: BlockStatement - readonly typeParamsDecl?: TSTypeParameterDeclaration - readonly returnType?: AstNode - readonly isAnon: boolean + readonly scriptFunction: ScriptFunction; + readonly parameters: readonly AstNode[]; + readonly name?: Identifier; + readonly body?: BlockStatement; + readonly typeParamsDecl?: TSTypeParameterDeclaration; + readonly returnType?: AstNode; + readonly isAnon: boolean; } export class FunctionExpression extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION) - super(peer) - this.scriptFunction = unpackNonNullableNode(global.generatedEs2panda._FunctionExpressionFunction(global.context, this.peer)) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION); + super(peer); + this.scriptFunction = unpackNonNullableNode( + global.generatedEs2panda._FunctionExpressionFunction(global.context, this.peer) + ); } - static create( - expression: ScriptFunction, - ): FunctionExpression { + static create(expression: ScriptFunction): FunctionExpression { return new FunctionExpression( - global.generatedEs2panda._CreateFunctionExpression( - global.context, - passNode(expression) - ) - ) + global.generatedEs2panda._CreateFunctionExpression(global.context, passNode(expression)) + ); } - static update( - node: FunctionExpression, - expression: ScriptFunction, - ): FunctionExpression { + static update(node: FunctionExpression, expression: ScriptFunction): FunctionExpression { return new FunctionExpression( - global.generatedEs2panda._UpdateFunctionExpression( - global.context, - node.peer, - passNode(expression) - ) - ) + global.generatedEs2panda._UpdateFunctionExpression(global.context, node.peer, passNode(expression)) + ); } - readonly scriptFunction: ScriptFunction + readonly scriptFunction: ScriptFunction; } export class ETSParameterExpression extends Expression { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION) - super(peer) - this.identifier = unpackNonNullableNode(global.generatedEs2panda._ETSParameterExpressionIdent(global.context, this.peer)) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION); + super(peer); } - static create( - identifier: Identifier, - initializer: AstNode | undefined - ): ETSParameterExpression { + static create(identifier: Identifier, initializer: AstNode | undefined): ETSParameterExpression { if (initializer !== undefined) { return new ETSParameterExpression( global.generatedEs2panda._CreateETSParameterExpression1( global.context, passNode(identifier), - passNode(initializer), + passNode(initializer) ) - ) + ); } return new ETSParameterExpression( - global.generatedEs2panda._CreateETSParameterExpression( - global.context, - passNode(identifier), - false - ) - ) + global.generatedEs2panda._CreateETSParameterExpression(global.context, passNode(identifier), false) + ); } static update( @@ -632,9 +528,9 @@ export class ETSParameterExpression extends Expression { global.context, node.peer, passNode(identifier), - passNode(initializer), + passNode(initializer) ) - ) + ); } return new ETSParameterExpression( global.generatedEs2panda._UpdateETSParameterExpression( @@ -643,15 +539,11 @@ export class ETSParameterExpression extends Expression { passNode(identifier), false ) - ) + ); } get annotations(): AnnotationUsage[] { - return unpackNodeArray(global.es2panda._ETSParameterExpressionAnnotations( - global.context, - this.peer, - nullptr - )) + return unpackNodeArray(global.es2panda._ETSParameterExpressionAnnotations(global.context, this.peer, nullptr)); } set annotations(newAnnotations: AnnotationUsage[]) { @@ -664,41 +556,58 @@ export class ETSParameterExpression extends Expression { } get type(): AstNode | undefined { - return unpackNode(global.generatedEs2panda._ETSParameterExpressionTypeAnnotation(global.context, this.peer)) + return unpackNode(global.generatedEs2panda._ETSParameterExpressionTypeAnnotation(global.context, this.peer)); } set type(t: AstNode | undefined) { - if (t === undefined) - return - global.generatedEs2panda._ETSParameterExpressionSetTypeAnnotation(global.context, this.peer, t.peer) + if (t === undefined) return; + global.generatedEs2panda._ETSParameterExpressionSetTypeAnnotation(global.context, this.peer, t.peer); } get optional(): Boolean { - return global.generatedEs2panda._ETSParameterExpressionIsOptionalConst(global.context, this.peer) + return global.generatedEs2panda._ETSParameterExpressionIsOptionalConst(global.context, this.peer); + } + + get initializer(): Expression | undefined { + return unpackNode(global.generatedEs2panda._ETSParameterExpressionInitializerConst(global.context, this.peer)); + } + + /** @deprecated */ + setInitializer(initExpr?: Expression): this { + global.generatedEs2panda._ETSParameterExpressionSetInitializer(global.context, this.peer, passNode(initExpr)); + return this; } setOptional(value: boolean): this { - global.generatedEs2panda._ETSParameterExpressionSetOptional(global.context, this.peer, value) - return this + global.generatedEs2panda._ETSParameterExpressionSetOptional(global.context, this.peer, value); + return this; + } + + get identifier(): Identifier { + return unpackNonNullableNode( + global.generatedEs2panda._ETSParameterExpressionIdentConst(global.context, this.peer) + ); } - identifier: Identifier + /** @deprecated */ + setIdent(ident?: Identifier): this { + global.generatedEs2panda._ETSParameterExpressionSetIdent(global.context, this.peer, passNode(ident)); + return this; + } } export class IfStatement extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT) - super(peer) - this.test = unpackNonNullableNode(global.generatedEs2panda._IfStatementTest(global.context, this.peer)) - this.consequent = unpackNonNullableNode(global.generatedEs2panda._IfStatementConsequent(global.context, this.peer)) - this.alternate = unpackNode(global.generatedEs2panda._IfStatementAlternate(global.context, this.peer)) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT); + super(peer); + this.test = unpackNonNullableNode(global.generatedEs2panda._IfStatementTest(global.context, this.peer)); + this.consequent = unpackNonNullableNode( + global.generatedEs2panda._IfStatementConsequent(global.context, this.peer) + ); + this.alternate = unpackNode(global.generatedEs2panda._IfStatementAlternate(global.context, this.peer)); } - static create( - test: AstNode, - consequent: AstNode, - alternate?: AstNode - ): IfStatement { + static create(test: AstNode, consequent: AstNode, alternate?: AstNode): IfStatement { return new IfStatement( global.generatedEs2panda._CreateIfStatement( global.context, @@ -706,15 +615,10 @@ export class IfStatement extends AstNode { passNode(consequent), passNode(alternate) ) - ) + ); } - static update( - node: IfStatement, - test: AstNode, - consequent: AstNode, - alternate?: AstNode - ): IfStatement { + static update(node: IfStatement, test: AstNode, consequent: AstNode, alternate?: AstNode): IfStatement { return new IfStatement( global.generatedEs2panda._UpdateIfStatement( global.context, @@ -723,55 +627,47 @@ export class IfStatement extends AstNode { passNode(consequent), passNode(alternate) ) - ) + ); } - test: AstNode - consequent: AstNode - alternate: AstNode | undefined + test: AstNode; + consequent: AstNode; + alternate: AstNode | undefined; } export class StructDeclaration extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION) - super(peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION); + super(peer); // TODO: is struct definition the same as struct definition? - this.definition = unpackNonNullableNode(global.generatedEs2panda._ClassDeclarationDefinition(global.context, this.peer)) + this.definition = unpackNonNullableNode( + global.generatedEs2panda._ClassDeclarationDefinition(global.context, this.peer) + ); } - static create( - definition: ClassDefinition, - ): StructDeclaration { + static create(definition: ClassDefinition): StructDeclaration { return new StructDeclaration( - global.generatedEs2panda._CreateETSStructDeclaration( - global.context, - passNode(definition) - ) - ) + global.generatedEs2panda._CreateETSStructDeclaration(global.context, passNode(definition)) + ); } - static update( - node: StructDeclaration, - definition: ClassDefinition, - ): StructDeclaration { + static update(node: StructDeclaration, definition: ClassDefinition): StructDeclaration { return new StructDeclaration( - global.generatedEs2panda._UpdateETSStructDeclaration( - global.context, - node.peer, - passNode(definition) - ) - ) + global.generatedEs2panda._UpdateETSStructDeclaration(global.context, node.peer, passNode(definition)) + ); } - readonly definition: ClassDefinition + readonly definition: ClassDefinition; } export class MethodDefinition extends AstNode { constructor(peer: KPtr, key?: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION) - super(peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION); + super(peer); this.kind = global.generatedEs2panda._MethodDefinitionKindConst(global.context, this.peer); - this.scriptFunction = unpackNonNullableNode(global.generatedEs2panda._MethodDefinitionFunction(global.context, this.peer)) + this.scriptFunction = unpackNonNullableNode( + global.generatedEs2panda._MethodDefinitionFunction(global.context, this.peer) + ); assertValidPeer(this.scriptFunction.peer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION); // Somehow the scriptFunction cannot attach method's key to its ident after checker @@ -781,8 +677,10 @@ export class MethodDefinition extends AstNode { this.scriptFunction = this.scriptFunction.setIdent(_name as Identifier); } - this.name = unpackNonNullableNode(global.generatedEs2panda._ScriptFunctionId(global.context, this.scriptFunction.peer)) - this.kind = global.generatedEs2panda._MethodDefinitionKindConst(global.context, this.peer) + this.name = unpackNonNullableNode( + global.generatedEs2panda._ScriptFunctionId(global.context, this.scriptFunction.peer) + ); + this.kind = global.generatedEs2panda._MethodDefinitionKindConst(global.context, this.peer); } static create( @@ -802,7 +700,7 @@ export class MethodDefinition extends AstNode { isComputed ), key.peer - ) + ); } static update( @@ -824,7 +722,7 @@ export class MethodDefinition extends AstNode { isComputed ), key.peer - ) + ); } // TODO: does not work @@ -833,25 +731,32 @@ export class MethodDefinition extends AstNode { } get overloads(): readonly MethodDefinition[] { - return unpackNodeArray(global.generatedEs2panda._MethodDefinitionOverloadsConst(global.context, this.peer)) + return unpackNodeArray(global.generatedEs2panda._MethodDefinitionOverloadsConst(global.context, this.peer)); } setOverloads(overloads: readonly MethodDefinition[]): this { - global.generatedEs2panda._MethodDefinitionSetOverloads(global.context, this.peer, passNodeArray(overloads), overloads.length) - return this + global.generatedEs2panda._MethodDefinitionSetOverloads( + global.context, + this.peer, + passNodeArray(overloads), + overloads.length + ); + return this; } readonly kind: Es2pandaMethodDefinitionKind; - readonly scriptFunction: ScriptFunction - readonly name: Identifier + readonly scriptFunction: ScriptFunction; + readonly name: Identifier; } export class VariableDeclaration extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION) - super(peer) - this.declarationKind = global.generatedEs2panda._VariableDeclarationKindConst(global.context, this.peer) - this.declarators = unpackNodeArray(global.generatedEs2panda._VariableDeclarationDeclaratorsConst(global.context, this.peer)) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION); + super(peer); + this.declarationKind = global.generatedEs2panda._VariableDeclarationKindConst(global.context, this.peer); + this.declarators = unpackNodeArray( + global.generatedEs2panda._VariableDeclarationDeclaratorsConst(global.context, this.peer) + ); } static create( @@ -864,10 +769,10 @@ export class VariableDeclaration extends AstNode { kind, passNodeArray(declarators), declarators.length - ) - global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags) - global.generatedEs2panda._AstNodeAddModifier(global.context, peer, modifiers) - return new VariableDeclaration(peer) + ); + global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags); + global.generatedEs2panda._AstNodeAddModifier(global.context, peer, modifiers); + return new VariableDeclaration(peer); } static update( @@ -882,21 +787,21 @@ export class VariableDeclaration extends AstNode { kind, passNodeArray(declarators), declarators.length - ) - global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags) - global.generatedEs2panda._AstNodeAddModifier(global.context, peer, modifiers) - return new VariableDeclaration(peer) + ); + global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags); + global.generatedEs2panda._AstNodeAddModifier(global.context, peer, modifiers); + return new VariableDeclaration(peer); } - readonly declarationKind: Es2pandaVariableDeclarationKind - readonly declarators: readonly VariableDeclarator[] + readonly declarationKind: Es2pandaVariableDeclarationKind; + readonly declarators: readonly VariableDeclarator[]; } export class VariableDeclarator extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR) - super(peer) - this.name = unpackNonNullableNode(global.generatedEs2panda._VariableDeclaratorId(global.context, this.peer)) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR); + super(peer); + this.name = unpackNonNullableNode(global.generatedEs2panda._VariableDeclaratorId(global.context, this.peer)); } static create( @@ -904,15 +809,11 @@ export class VariableDeclarator extends AstNode { name: Identifier, initializer: AstNode | undefined ): VariableDeclarator { - const peer = global.generatedEs2panda._CreateVariableDeclarator( - global.context, - flag, - passNode(name) - ) + const peer = global.generatedEs2panda._CreateVariableDeclarator(global.context, flag, passNode(name)); if (initializer !== undefined) { - global.generatedEs2panda._VariableDeclaratorSetInit(global.context, peer, initializer.peer) + global.generatedEs2panda._VariableDeclaratorSetInit(global.context, peer, initializer.peer); } - return new VariableDeclarator(peer) + return new VariableDeclarator(peer); } static update( @@ -926,34 +827,39 @@ export class VariableDeclarator extends AstNode { node.peer, flag, passNode(name) - ) + ); if (initializer !== undefined) { - global.generatedEs2panda._VariableDeclaratorSetInit(global.context, peer, initializer.peer) + global.generatedEs2panda._VariableDeclaratorSetInit(global.context, peer, initializer.peer); } - return new VariableDeclarator(peer) + return new VariableDeclarator(peer); } get initializer(): AstNode | undefined { - return unpackNode(global.generatedEs2panda._VariableDeclaratorInit(global.context, this.peer)) + return unpackNode(global.generatedEs2panda._VariableDeclaratorInit(global.context, this.peer)); } - readonly name: Identifier + /** @deprecated */ + setInit(init?: Expression): this { + global.generatedEs2panda._VariableDeclaratorSetInit(global.context, this.peer, passNode(init)); + return this; + } + + get flag(): Es2pandaVariableDeclaratorFlag { + return global.generatedEs2panda._VariableDeclaratorFlag(global.context, this.peer); + } + + readonly name: Identifier; } export class SuperExpression extends AstNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION) - super(peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION); + super(peer); this.id = unpackNode(global.generatedEs2panda._TSInterfaceDeclarationId(global.context, this.peer)); } - static create( - ): SuperExpression { - return new SuperExpression( - global.generatedEs2panda._CreateSuperExpression( - global.context, - ) - ) + static create(): SuperExpression { + return new SuperExpression(global.generatedEs2panda._CreateSuperExpression(global.context)); } readonly id?: Identifier; @@ -961,23 +867,16 @@ export class SuperExpression extends AstNode { export class ETSStringLiteralType extends TypeNode { constructor(peer: KPtr) { - assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_STRING_LITERAL_TYPE) - super(peer) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_STRING_LITERAL_TYPE); + super(peer); } - static create( - str: string, - ): ETSStringLiteralType { - return new ETSStringLiteralType( - global.es2panda._CreateETSStringLiteralType( - global.context, - passString(str) - ) - ) + static create(str: string): ETSStringLiteralType { + return new ETSStringLiteralType(global.es2panda._CreateETSStringLiteralType(global.context, passString(str))); } } -const pairs: [Es2pandaAstNodeType, { new(peer: KNativePointer): AstNode }][] = [ +const pairs: [Es2pandaAstNodeType, { new (peer: KNativePointer): AstNode }][] = [ [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE, EtsScript], [Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER, Identifier], [Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL, NumberLiteral], @@ -999,8 +898,6 @@ const pairs: [Es2pandaAstNodeType, { new(peer: KNativePointer): AstNode }][] = [ [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION, FunctionExpression], [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, ETSTypeReference], [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, ETSTypeReferencePart], - [Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, ObjectExpression] -] -pairs.forEach(([nodeType, astNode]) => - nodeByType.set(nodeType, astNode) -) \ No newline at end of file + [Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, ObjectExpression], +]; +pairs.forEach(([nodeType, astNode]) => nodeByType.set(nodeType, astNode)); diff --git a/koala-wrapper/src/arkts-api/utilities/private.ts b/koala-wrapper/src/arkts-api/utilities/private.ts index 6fc2348d3..30db3e472 100644 --- a/koala-wrapper/src/arkts-api/utilities/private.ts +++ b/koala-wrapper/src/arkts-api/utilities/private.ts @@ -13,8 +13,8 @@ * limitations under the License. */ -import { global } from "../static/global" -import { isNumber, throwError } from "../../utils" +import { global } from '../static/global'; +import { isNumber, throwError } from '../../utils'; import { KInt, KNativePointer as KPtr, @@ -22,142 +22,180 @@ import { nullptr, withString, withStringArray, - withStringResult -} from "@koalaui/interop" -import { NativePtrDecoder } from "./nativePtrDecoder" -import { Es2pandaModifierFlags, Es2pandaScriptFunctionFlags } from "../../generated/Es2pandaEnums" -import { classByPeer } from "../class-by-peer" -import type { AstNode } from "../peers/AstNode" -import { ArktsObject } from "../peers/ArktsObject" -import { Es2pandaAstNodeType } from "../../Es2pandaEnums" - -export const arrayOfNullptr = new BigUint64Array([nullptr]) - -export const allFlags = - Object.values(Es2pandaModifierFlags) - .filter(isNumber) - .reduce( - (prev, next) => (prev | next), - 0 - - ) + withStringResult, +} from '@koalaui/interop'; +import { NativePtrDecoder } from './nativePtrDecoder'; +import { Es2pandaModifierFlags, Es2pandaScriptFunctionFlags } from '../../generated/Es2pandaEnums'; +import { classByPeer } from '../class-by-peer'; +import type { AstNode } from '../peers/AstNode'; +import { ArktsObject } from '../peers/ArktsObject'; +import { Es2pandaAstNodeType } from '../../Es2pandaEnums'; + +export const arrayOfNullptr = new BigUint64Array([nullptr]); + +export const allFlags = Object.values(Es2pandaModifierFlags) + .filter(isNumber) + .reduce((prev, next) => prev | next, 0); export function assertValidPeer(peer: KPtr, expectedKind: Es2pandaAstNodeType): void { if (peer === nullptr) { - throwError(`invalid peer`) + throwError(`invalid peer`); } - const peerType = global.generatedEs2panda._AstNodeTypeConst(global.context, peer) + const peerType = global.generatedEs2panda._AstNodeTypeConst(global.context, peer); if (peerType !== expectedKind) { - throwError(`expected: ${Es2pandaAstNodeType[expectedKind]}, got: ${Es2pandaAstNodeType[peerType]}`) + throwError(`expected: ${Es2pandaAstNodeType[expectedKind]}, got: ${Es2pandaAstNodeType[peerType]}`); } } -export function acceptNativeObjectArrayResult(arrayObject: KNativePointer, factory: (instance: KNativePointer) => T): T[] { +export function acceptNativeObjectArrayResult( + arrayObject: KNativePointer, + factory: (instance: KNativePointer) => T +): T[] { return new NativePtrDecoder().decode(arrayObject).map(factory); } export function unpackNonNullableNode(peer: KNativePointer): T { if (peer === nullptr) { - throwError('peer is NULLPTR (maybe you should use unpackNode)') + throwError('peer is NULLPTR (maybe you should use unpackNode)'); } - return classByPeer(peer) as T + return classByPeer(peer) as T; } export function unpackNode(peer: KNativePointer): T | undefined { if (peer === nullptr) { - return undefined + return undefined; } - return classByPeer(peer) as T + return classByPeer(peer) as T; } export function passNode(node: ArktsObject | undefined): KNativePointer { - return node?.peer ?? nullptr + return node?.peer ?? nullptr; } // meaning unpackNonNullableNodeArray export function unpackNodeArray(nodesPtr: KNativePointer): T[] { if (nodesPtr === nullptr) { - throwError('nodesPtr is NULLPTR (maybe you should use unpackNodeArray)') + throwError('nodesPtr is NULLPTR (maybe you should use unpackNodeArray)'); } - return (new NativePtrDecoder()) - .decode(nodesPtr) - .map((peer: KNativePointer) => unpackNonNullableNode(peer)) + return new NativePtrDecoder().decode(nodesPtr).map((peer: KNativePointer) => unpackNonNullableNode(peer)); } export function passNodeArray(nodes: readonly AstNode[] | undefined): BigUint64Array { - return new BigUint64Array( - nodes?.map(node => BigInt(node.peer)) ?? [] - ) + return new BigUint64Array(nodes?.map((node) => BigInt(node.peer)) ?? []); } -export function unpackNonNullableObject(type: { new (peer: KNativePointer): T }, peer: KNativePointer): T { +export function unpackNonNullableObject( + Type: { new (peer: KNativePointer): T }, + peer: KNativePointer +): T { if (peer === nullptr) { - throwError('peer is NULLPTR (maybe you should use unpackObject)') + throwError('peer is NULLPTR (maybe you should use unpackObject)'); } - return new type(peer) + return new Type(peer); } -export function unpackObject(type: { new (peer: KNativePointer): T }, peer: KNativePointer): T | undefined { +export function unpackObject( + Type: { new (peer: KNativePointer): T }, + peer: KNativePointer +): T | undefined { if (peer === nullptr) { - return undefined + return undefined; } - return new type(peer) + return new Type(peer); } export function unpackString(peer: KNativePointer): string { - return withStringResult(peer) ?? throwError(`failed to unpack (peer shouldn't be NULLPTR)`) + return withStringResult(peer) ?? throwError(`failed to unpack (peer shouldn't be NULLPTR)`); } export function passString(str: string | undefined): string { if (str === undefined) { - return "" + return ''; } - return withString(str, (it: string) => it) + return withString(str, (it: string) => it); } export function passStringArray(strings: readonly string[]): string[] { - return withStringArray(strings, (it: string[]) => it) + return withStringArray(strings, (it: string[]) => it); } export function passNodeWithNewModifiers(node: T, modifiers: KInt): T { - return (unpackNonNullableNode(node.peer) as T).updateModifiers(modifiers) + return (unpackNonNullableNode(node.peer) as T).updateModifiers(modifiers); } export function scriptFunctionHasBody(peer: KNativePointer): boolean { - const flags = global.generatedEs2panda._ScriptFunctionFlagsConst(global.context, peer) - return (flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL) === 0 - && (flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL_OVERLOAD) === 0 + const flags = global.generatedEs2panda._ScriptFunctionFlagsConst(global.context, peer); + return ( + (flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL) === 0 && + (flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL_OVERLOAD) === 0 + ); } // TODO: remove this // TODO: update scopes and other data export function updatePeerByNode(peer: KNativePointer, original: T | undefined): KNativePointer { if (peer === nullptr) { - throwError('updatePeerByNode called on NULLPTR') + throwError('updatePeerByNode called on NULLPTR'); } if (original === undefined) { - return peer + return peer; } - global.generatedEs2panda._AstNodeSetOriginalNode(global.context, peer, original.peer) - global.generatedEs2panda._AstNodeSetParent(global.context, peer, global.generatedEs2panda._AstNodeParent(global.context, original.peer)) - global.es2panda._AstNodeUpdateChildren(global.context, peer) - global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags) - global.generatedEs2panda._AstNodeAddModifier(global.context, peer, original.modifiers) - global.es2panda._AstNodeUpdateChildren(global.context, peer) - return peer + global.generatedEs2panda._AstNodeSetOriginalNode(global.context, peer, original.peer); + global.generatedEs2panda._AstNodeSetParent( + global.context, + peer, + global.generatedEs2panda._AstNodeParent(global.context, original.peer) + ); + global.es2panda._AstNodeUpdateChildren(global.context, peer); + global.generatedEs2panda._AstNodeClearModifier(global.context, peer, allFlags); + global.generatedEs2panda._AstNodeAddModifier(global.context, peer, original.modifiers); + global.es2panda._AstNodeUpdateChildren(global.context, peer); + return peer; } // TODO: update scopes and other data export function updateNodeByNode(node: T, original: AstNode): T { if (original.peer === nullptr) { - throwError('update called on NULLPTR') + throwError('update called on NULLPTR'); } - global.generatedEs2panda._AstNodeSetOriginalNode(global.context, node.peer, original.peer) - global.generatedEs2panda._AstNodeSetParent(global.context, node.peer, global.generatedEs2panda._AstNodeParent(global.context, original.peer)) - global.es2panda._AstNodeUpdateChildren(global.context, node.peer) - return node + global.generatedEs2panda._AstNodeSetOriginalNode(global.context, node.peer, original.peer); + global.generatedEs2panda._AstNodeSetParent( + global.context, + node.peer, + global.generatedEs2panda._AstNodeParent(global.context, original.peer) + ); + global.es2panda._AstNodeUpdateChildren(global.context, node.peer); + return node; } export function nodeType(node: AstNode): Es2pandaAstNodeType { - return global.generatedEs2panda._AstNodeTypeConst(global.context, passNode(node)) + return global.generatedEs2panda._AstNodeTypeConst(global.context, passNode(node)); +} + +/** + * @deprecated + */ +export function compose( + create: (...args: ARGS) => T, + update: (node: T, original: T) => T = updateNodeByNode +): (node: T, ...args: ARGS) => T { + return (node: T, ...args: ARGS) => update(create(...args), node); +} + +export function updateThenAttach( + update: (original: T, ...args: ARGS) => T, + ...attachFuncs: ((node: T, original: T) => T)[] +): (node: T, ...args: ARGS) => T { + return (node: T, ...args: ARGS) => { + let _node: T = update(node, ...args); + attachFuncs.forEach((attach) => { + _node = attach(_node, node); + }); + return _node; + }; +} + +export function attachModifiers(node: T, original: T): T { + node.modifiers = original.modifiers; + return node; } diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index 32d33dbf0..eac5cfad8 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -22,6 +22,7 @@ import { Es2pandaContextState, Es2pandaModifierFlags } from "../../generated/Es2 import type { AstNode } from "../peers/AstNode" import { ClassDefinition, ClassProperty, ETSImportDeclaration, ImportSpecifier, isClassDefinition, isScriptFunction, type AnnotationUsage } from "../../generated" import { Program } from "../peers/Program" +import { clearNodeCache } from "../class-by-peer" export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { @@ -30,6 +31,7 @@ export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false console.log("[TS WRAPPER] PROCEED TO STATE: SKIPPING"); return } + clearNodeCache() try { global.es2panda._ProceedToState(global.context, state) if (global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && !forceDtsEmit) { -- Gitee From b04ab8aa3b4544290855c97d40d28082784679cc Mon Sep 17 00:00:00 2001 From: seaside_wu Date: Mon, 14 Apr 2025 16:05:34 +0800 Subject: [PATCH 042/123] uiplugin adapt to Mac Signed-off-by: seaside_wu Change-Id: If7b29130d9c86fe2ec53fe216b0c812627c826de --- koala-wrapper/build_ts_wrapper.py | 2 +- koala-wrapper/native/BUILD.gn | 21 +++++++++++++++++++++ koala-wrapper/native/src/common.cc | 2 +- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/koala-wrapper/build_ts_wrapper.py b/koala-wrapper/build_ts_wrapper.py index f83ab26a1..178f8772f 100755 --- a/koala-wrapper/build_ts_wrapper.py +++ b/koala-wrapper/build_ts_wrapper.py @@ -65,7 +65,7 @@ def copy_output(options): copy_files(os.path.join(options.root_out_dir, 'libes2panda.dll'), os.path.join(options.source_path, 'build/native/es2panda.node'), True) - if options.current_os == "linux" : + if options.current_os == "linux" or options.current_os == "mac" : copy_files(os.path.join(options.root_out_dir, 'libes2panda.node'), os.path.join(options.output_path, 'build/native/es2panda.node'), True) copy_files(os.path.join(options.root_out_dir, 'libes2panda.node'), diff --git a/koala-wrapper/native/BUILD.gn b/koala-wrapper/native/BUILD.gn index 65e8bb331..1f7e783fa 100644 --- a/koala-wrapper/native/BUILD.gn +++ b/koala-wrapper/native/BUILD.gn @@ -50,6 +50,27 @@ shared_library("es2panda") { configs -= [ "//build/config/compiler:compiler" ] + if (is_mac) { + cflags_cc = [ + "-std=c++17", + "-Wall", + "-Werror", + "-Wno-unused-variable", + "-fPIC", + ] + + ldflags = [ + "-fPIC", + "-Wl,-undefined,dynamic_lookup", + "-fuse-ld=lld", + "-Wl,--icf=all", + "-Wl,--color-diagnostics", + "-m64" + ] + defines += [ "KOALA_MACOS" ] + output_extension = "node" + } + if (current_os == "linux") { cflags_cc = [ "-std=c++17", diff --git a/koala-wrapper/native/src/common.cc b/koala-wrapper/native/src/common.cc index 7ddc761cc..eb7a6acb5 100644 --- a/koala-wrapper/native/src/common.cc +++ b/koala-wrapper/native/src/common.cc @@ -26,7 +26,7 @@ static es2panda_Impl *impl = nullptr; #define LIB_SUFFIX ".dll" #endif -#ifdef KOALA_LINUX +#if defined(KOALA_LINUX) || defined(KOALA_MACOS) #include #ifdef __x86_64__ -- Gitee From 6bdb961f97fd94fdb95ffd4b057010eb8523826d Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Mon, 14 Apr 2025 19:53:59 +0800 Subject: [PATCH 043/123] fix class-property without value can be unmemoized Signed-off-by: Jiakai Shi Change-Id: Ia4fbbeb55abff4d2e85fa79d226f1a87c83f06ee --- .../memo-plugins/function-transformer.ts | 315 ++++++++++-------- arkui-plugins/memo-plugins/utils.ts | 57 ++++ 2 files changed, 228 insertions(+), 144 deletions(-) diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 330a1296b..1d9b5a3cf 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -18,11 +18,18 @@ import { factory } from './memo-factory'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { PositionalIdTracker, + castArrowFunctionExpression, castFunctionExpression, + castOverloadsToMethods, castParameters, + findMemoFromTypeAnnotation, hasMemoAnnotation, hasMemoIntrinsicAnnotation, hasMemoStableAnnotation, + isMemoArrowFunction, + isMemoClassProperty, + isMemoMethodDefinition, + isMemoTSTypeAliasDeclaration, isStandaloneArrowFunction, isVoidType, removeMemoAnnotation, @@ -48,7 +55,7 @@ function updateFunctionBody( ): [ arkts.BlockStatement, arkts.VariableDeclaration | undefined, - arkts.ReturnStatement | arkts.BlockStatement | undefined, + arkts.ReturnStatement | arkts.BlockStatement | undefined ] { let returnTypeAnno = !returnTypeAnnotation || stableThis @@ -91,18 +98,6 @@ function updateFunctionBody( } } -function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | undefined): boolean { - if (!typeAnnotation) return false; - if (arkts.isETSFunctionType(typeAnnotation)) { - return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation); - } else if (arkts.isETSUnionType(typeAnnotation)) { - return typeAnnotation.types.some( - (type) => arkts.isETSFunctionType(type) && (hasMemoAnnotation(type) || hasMemoIntrinsicAnnotation(type)) - ); - } - return false; -} - function updateMemoTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): arkts.TypeNode | undefined { if (!typeAnnotation) return undefined; if (!arkts.isTypeNode(typeAnnotation)) return undefined; @@ -164,31 +159,22 @@ export class FunctionTransformer extends AbstractVisitor { enter(node: arkts.AstNode) { if (arkts.isMethodDefinition(node)) { const name = node.name.name; - const isMemo = hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction); + const isMemo = isMemoMethodDefinition(node); this.scopes.push({ name, isMemo }); } - if ( - arkts.isClassProperty(node) && - !!node.key && - arkts.isIdentifier(node.key) && - !!node.value && - arkts.isArrowFunctionExpression(node.value) - ) { + if (arkts.isClassProperty(node) && !!node.key && arkts.isIdentifier(node.key)) { const name = node.key.name; - let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); - isMemo ||= hasMemoAnnotation(node.value) || hasMemoIntrinsicAnnotation(node.value); - isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + const isMemo = isMemoClassProperty(node); this.scopes.push({ name, isMemo }); } if (isStandaloneArrowFunction(node)) { const name = undefined; - const isMemo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + const isMemo = isMemoArrowFunction(node); this.scopes.push({ name, isMemo }); } if (arkts.isTSTypeAliasDeclaration(node) && !!node.id && !!node.typeAnnotation) { const name = node.id.name; - let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); - isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + const isMemo = isMemoTSTypeAliasDeclaration(node); this.scopes.push({ name, isMemo }); } if (arkts.isClassDefinition(node)) { @@ -227,7 +213,9 @@ export class FunctionTransformer extends AbstractVisitor { if (this.scopes[this.scopes.length - 1].isMemo == false) { if (this.scopes[this.scopes.length - 1].name) { console.error( - `Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${this.scopes[this.scopes.length - 1].name}` + `Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${ + this.scopes[this.scopes.length - 1].name + }` ); throw 'Invalid @memo usage'; } else { @@ -284,30 +272,28 @@ export class FunctionTransformer extends AbstractVisitor { return updateScriptFunction; } - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - this.enter(beforeChildren); - const node = this.visitEachChild(beforeChildren); - this.exit(beforeChildren); - if (arkts.isMethodDefinition(node)) { - if ( - node.scriptFunction.body && - (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) - ) { - return arkts.factory.updateMethodDefinition( - node, - node.kind, - node.name, - arkts.factory.createFunctionExpression( - this.signatureTransformer.visitor( - removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)) - ) - ), - node.modifiers, - false - ); - } - - return arkts.factory.updateMethodDefinition( + private updateMethodDefinition(node: arkts.MethodDefinition): arkts.MethodDefinition { + let updateMethod: arkts.MethodDefinition; + const that = this; + const updateOverloads = node.overloads?.map((overload) => that.visitor(overload)) ?? undefined; + if ( + node.scriptFunction.body && + (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) + ) { + updateMethod = arkts.factory.updateMethodDefinition( + node, + node.kind, + node.name, + arkts.factory.createFunctionExpression( + this.signatureTransformer.visitor( + removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)) + ) + ), + node.modifiers, + false + ); + } else { + updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, node.name, @@ -316,114 +302,155 @@ export class FunctionTransformer extends AbstractVisitor { false ); } - if (arkts.isCallExpression(node)) { - const expr = node.expression; - const decl = arkts.getDecl(expr); - if ( - decl && - arkts.isMethodDefinition(decl) && - (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction)) - ) { - this.checkMemoCallInMethod(decl); - const updatedArguments = node.arguments.map((it, index) => { - const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type; - if (type && arkts.isETSFunctionType(type)) { - if ( - !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) && - !hasMemoIntrinsicAnnotation( - decl.scriptFunction.params[index] as arkts.ETSParameterExpression - ) - ) { - return it; //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) - } - if (arkts.isArrowFunctionExpression(it)) { - this.enterAnonymousScope(it.scriptFunction); - const res = this.updateScriptFunction(it.scriptFunction); - this.exitAnonymousScope(); - return arkts.factory.updateArrowFunction(it, res); - } - } - return it; - }); - return arkts.factory.updateCallExpression(node, node.expression, undefined, [ - ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), - ...updatedArguments, - ]); - } - if (isStandaloneArrowFunction(node.expression)) { - const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.expression.scriptFunction.id?.name) return node; - this.exitAnonymousScope(); - this.checkMemoCallInFunction(); - - this.enterAnonymousScope(node.expression.scriptFunction); - const res = this.updateScriptFunction( - node.expression.scriptFunction, - node.expression.scriptFunction.id?.name - ); - this.exitAnonymousScope(); + if (!!updateOverloads) { + updateMethod.setOverloads(castOverloadsToMethods(updateOverloads)); + } + return updateMethod; + } - return arkts.factory.updateCallExpression( - node, - arkts.factory.updateArrowFunction(node.expression, res), - node.typeArguments, - [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...node.arguments] - ); + private updateDeclaredMemoCall(node: arkts.CallExpression, decl: arkts.MethodDefinition): arkts.CallExpression { + this.checkMemoCallInMethod(decl); + const updatedArguments = node.arguments.map((it, index) => { + const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type; + if (type && arkts.isETSFunctionType(type)) { + if ( + !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) && + !hasMemoIntrinsicAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) + ) { + return it; //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) + } + if (arkts.isArrowFunctionExpression(it)) { + this.enterAnonymousScope(it.scriptFunction); + const res = this.updateScriptFunction(it.scriptFunction); + this.exitAnonymousScope(); + return arkts.factory.updateArrowFunction(it, res); + } } + return it; + }); + return arkts.factory.updateCallExpression(node, node.expression, undefined, [ + ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), + ...updatedArguments, + ]); + } + + private udpateAnonymousMemoCall( + node: arkts.CallExpression, + expression: arkts.ArrowFunctionExpression + ): arkts.CallExpression { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== expression.scriptFunction.id?.name) { + return node; } + this.exitAnonymousScope(); + this.checkMemoCallInFunction(); + + this.enterAnonymousScope(expression.scriptFunction); + const res = this.updateScriptFunction(expression.scriptFunction, expression.scriptFunction.id?.name); + this.exitAnonymousScope(); + + return arkts.factory.updateCallExpression( + node, + arkts.factory.updateArrowFunction(expression, res), + node.typeArguments, + [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...node.arguments] + ); + } + + private updateCallExpression(node: arkts.CallExpression): arkts.CallExpression { + const expr = node.expression; + const decl = arkts.getDecl(expr); if ( - arkts.isClassProperty(node) && - !!node.key && - arkts.isIdentifier(node.key) && - !!node.value && - arkts.isArrowFunctionExpression(node.value) + decl && + arkts.isMethodDefinition(decl) && + (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction)) ) { - const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.key?.name) return node; - this.exitAnonymousScope(); + return this.updateDeclaredMemoCall(node, decl); + } + if (isStandaloneArrowFunction(node.expression)) { + return this.udpateAnonymousMemoCall(node, node.expression); + } + return node; + } + + private updateClassProperty(node: arkts.ClassProperty, key: arkts.Identifier): arkts.ClassProperty { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== key.name) { + return node; + } + this.exitAnonymousScope(); + let res: arkts.ScriptFunction | undefined; + if (!!node.value && arkts.isArrowFunctionExpression(node.value)) { this.enterAnonymousScope(node.value.scriptFunction); - const res = this.updateScriptFunction(node.value.scriptFunction, node.key.name); + res = this.updateScriptFunction(node.value.scriptFunction, key.name); this.exitAnonymousScope(); + } - let typeAnnotation: arkts.TypeNode | undefined; - if (!!node.typeAnnotation && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-property ${node.key.name}`); - throw 'Invalid @memo usage'; - } + let typeAnnotation: arkts.TypeNode | undefined; + if (!!node.typeAnnotation && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-property ${key.name}`); + throw 'Invalid @memo usage'; + } - return arkts.factory.updateClassProperty( - node, - node.key, - arkts.factory.updateArrowFunction(node.value, res), - typeAnnotation, - node.modifiers, - node.isComputed - ); + return arkts.factory.updateClassProperty( + node, + node.key, + res ? arkts.factory.updateArrowFunction(castArrowFunctionExpression(node.value), res) : undefined, + typeAnnotation, + node.modifiers, + node.isComputed + ); + } + + private updateTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration): arkts.TSTypeAliasDeclaration { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== node.id?.name) { + return node; } - if (arkts.isTSTypeAliasDeclaration(node)) { - const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.id?.name) return node; - this.exitAnonymousScope(); + this.exitAnonymousScope(); - let typeAnnotation: arkts.TypeNode | undefined; - if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-type ${node.id!.name}`); - throw 'Invalid @memo usage'; - } + let typeAnnotation: arkts.TypeNode | undefined; + if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-type ${node.id!.name}`); + throw 'Invalid @memo usage'; + } + + return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation); + } - return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation); + private updateStandaloneArrowFunction(node: arkts.ArrowFunctionExpression): arkts.ArrowFunctionExpression { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== node.scriptFunction.id?.name) { + return node; } - if (isStandaloneArrowFunction(node)) { - const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.scriptFunction.id?.name) return node; - this.exitAnonymousScope(); + this.exitAnonymousScope(); - this.enterAnonymousScope(node.scriptFunction); - const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); - this.exitAnonymousScope(); + this.enterAnonymousScope(node.scriptFunction); + const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); + this.exitAnonymousScope(); + + return arkts.factory.updateArrowFunction(node, res); + } - return arkts.factory.updateArrowFunction(node, res); + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + this.enter(beforeChildren); + const node = this.visitEachChild(beforeChildren); + this.exit(beforeChildren); + if (arkts.isMethodDefinition(node)) { + return this.updateMethodDefinition(node); + } + if (arkts.isCallExpression(node)) { + return this.updateCallExpression(node); + } + if (arkts.isClassProperty(node) && !!node.key && arkts.isIdentifier(node.key)) { + return this.updateClassProperty(node, node.key); + } + if (arkts.isTSTypeAliasDeclaration(node)) { + return this.updateTSTypeAliasDeclaration(node); + } + if (isStandaloneArrowFunction(node)) { + return this.updateStandaloneArrowFunction(node); } return node; } diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index 44553ed5c..cae4fa891 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -207,6 +207,24 @@ export function castFunctionExpression(value: arkts.Expression | undefined): ark return value as unknown as arkts.FunctionExpression; } +/** + * es2panda API is weird here + * + * @deprecated + */ +export function castArrowFunctionExpression(value: arkts.Expression | undefined): arkts.ArrowFunctionExpression { + return value as unknown as arkts.ArrowFunctionExpression; +} + +/** + * es2panda API is weird here + * + * @deprecated + */ +export function castOverloadsToMethods(overloads: arkts.AstNode[]): readonly arkts.MethodDefinition[] { + return overloads as unknown as readonly arkts.MethodDefinition[]; +} + export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.ArrowFunctionExpression { if (!arkts.isArrowFunctionExpression(node)) return false; @@ -215,3 +233,42 @@ export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.Ar return !arkts.isClassProperty(node.parent) && !(arkts.isCallExpression(node.parent) && node.parent.expression); } + +export function isMemoClassProperty(node: arkts.ClassProperty): boolean { + let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); + if (node.value) { + isMemo ||= + arkts.isArrowFunctionExpression(node.value) && + (hasMemoAnnotation(node.value) || hasMemoIntrinsicAnnotation(node.value)); + } + isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + return isMemo; +} + +export function isMemoMethodDefinition(node: arkts.MethodDefinition): boolean { + return hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction); +} + +export function isMemoArrowFunction(node: arkts.ArrowFunctionExpression): boolean { + return hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); +} + +export function isMemoTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration): boolean { + let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); + isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + return isMemo; +} + +export function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | undefined): boolean { + if (!typeAnnotation) { + return false; + } + if (arkts.isETSFunctionType(typeAnnotation)) { + return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation); + } else if (arkts.isETSUnionType(typeAnnotation)) { + return typeAnnotation.types.some( + (type) => arkts.isETSFunctionType(type) && (hasMemoAnnotation(type) || hasMemoIntrinsicAnnotation(type)) + ); + } + return false; +} -- Gitee From b35771cbd036ab3240c7a5e57c65b1397f77ca19 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Mon, 14 Apr 2025 19:53:59 +0800 Subject: [PATCH 044/123] fix class-property without value can be unmemoized Signed-off-by: Jiakai Shi Change-Id: Ia4fbbeb55abff4d2e85fa79d226f1a87c83f06ee --- .../memo-plugins/function-transformer.ts | 315 ++++++++++-------- arkui-plugins/memo-plugins/utils.ts | 57 ++++ 2 files changed, 228 insertions(+), 144 deletions(-) diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 330a1296b..1d9b5a3cf 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -18,11 +18,18 @@ import { factory } from './memo-factory'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { PositionalIdTracker, + castArrowFunctionExpression, castFunctionExpression, + castOverloadsToMethods, castParameters, + findMemoFromTypeAnnotation, hasMemoAnnotation, hasMemoIntrinsicAnnotation, hasMemoStableAnnotation, + isMemoArrowFunction, + isMemoClassProperty, + isMemoMethodDefinition, + isMemoTSTypeAliasDeclaration, isStandaloneArrowFunction, isVoidType, removeMemoAnnotation, @@ -48,7 +55,7 @@ function updateFunctionBody( ): [ arkts.BlockStatement, arkts.VariableDeclaration | undefined, - arkts.ReturnStatement | arkts.BlockStatement | undefined, + arkts.ReturnStatement | arkts.BlockStatement | undefined ] { let returnTypeAnno = !returnTypeAnnotation || stableThis @@ -91,18 +98,6 @@ function updateFunctionBody( } } -function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | undefined): boolean { - if (!typeAnnotation) return false; - if (arkts.isETSFunctionType(typeAnnotation)) { - return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation); - } else if (arkts.isETSUnionType(typeAnnotation)) { - return typeAnnotation.types.some( - (type) => arkts.isETSFunctionType(type) && (hasMemoAnnotation(type) || hasMemoIntrinsicAnnotation(type)) - ); - } - return false; -} - function updateMemoTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): arkts.TypeNode | undefined { if (!typeAnnotation) return undefined; if (!arkts.isTypeNode(typeAnnotation)) return undefined; @@ -164,31 +159,22 @@ export class FunctionTransformer extends AbstractVisitor { enter(node: arkts.AstNode) { if (arkts.isMethodDefinition(node)) { const name = node.name.name; - const isMemo = hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction); + const isMemo = isMemoMethodDefinition(node); this.scopes.push({ name, isMemo }); } - if ( - arkts.isClassProperty(node) && - !!node.key && - arkts.isIdentifier(node.key) && - !!node.value && - arkts.isArrowFunctionExpression(node.value) - ) { + if (arkts.isClassProperty(node) && !!node.key && arkts.isIdentifier(node.key)) { const name = node.key.name; - let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); - isMemo ||= hasMemoAnnotation(node.value) || hasMemoIntrinsicAnnotation(node.value); - isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + const isMemo = isMemoClassProperty(node); this.scopes.push({ name, isMemo }); } if (isStandaloneArrowFunction(node)) { const name = undefined; - const isMemo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + const isMemo = isMemoArrowFunction(node); this.scopes.push({ name, isMemo }); } if (arkts.isTSTypeAliasDeclaration(node) && !!node.id && !!node.typeAnnotation) { const name = node.id.name; - let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); - isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + const isMemo = isMemoTSTypeAliasDeclaration(node); this.scopes.push({ name, isMemo }); } if (arkts.isClassDefinition(node)) { @@ -227,7 +213,9 @@ export class FunctionTransformer extends AbstractVisitor { if (this.scopes[this.scopes.length - 1].isMemo == false) { if (this.scopes[this.scopes.length - 1].name) { console.error( - `Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${this.scopes[this.scopes.length - 1].name}` + `Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${ + this.scopes[this.scopes.length - 1].name + }` ); throw 'Invalid @memo usage'; } else { @@ -284,30 +272,28 @@ export class FunctionTransformer extends AbstractVisitor { return updateScriptFunction; } - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - this.enter(beforeChildren); - const node = this.visitEachChild(beforeChildren); - this.exit(beforeChildren); - if (arkts.isMethodDefinition(node)) { - if ( - node.scriptFunction.body && - (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) - ) { - return arkts.factory.updateMethodDefinition( - node, - node.kind, - node.name, - arkts.factory.createFunctionExpression( - this.signatureTransformer.visitor( - removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)) - ) - ), - node.modifiers, - false - ); - } - - return arkts.factory.updateMethodDefinition( + private updateMethodDefinition(node: arkts.MethodDefinition): arkts.MethodDefinition { + let updateMethod: arkts.MethodDefinition; + const that = this; + const updateOverloads = node.overloads?.map((overload) => that.visitor(overload)) ?? undefined; + if ( + node.scriptFunction.body && + (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) + ) { + updateMethod = arkts.factory.updateMethodDefinition( + node, + node.kind, + node.name, + arkts.factory.createFunctionExpression( + this.signatureTransformer.visitor( + removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)) + ) + ), + node.modifiers, + false + ); + } else { + updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, node.name, @@ -316,114 +302,155 @@ export class FunctionTransformer extends AbstractVisitor { false ); } - if (arkts.isCallExpression(node)) { - const expr = node.expression; - const decl = arkts.getDecl(expr); - if ( - decl && - arkts.isMethodDefinition(decl) && - (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction)) - ) { - this.checkMemoCallInMethod(decl); - const updatedArguments = node.arguments.map((it, index) => { - const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type; - if (type && arkts.isETSFunctionType(type)) { - if ( - !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) && - !hasMemoIntrinsicAnnotation( - decl.scriptFunction.params[index] as arkts.ETSParameterExpression - ) - ) { - return it; //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) - } - if (arkts.isArrowFunctionExpression(it)) { - this.enterAnonymousScope(it.scriptFunction); - const res = this.updateScriptFunction(it.scriptFunction); - this.exitAnonymousScope(); - return arkts.factory.updateArrowFunction(it, res); - } - } - return it; - }); - return arkts.factory.updateCallExpression(node, node.expression, undefined, [ - ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), - ...updatedArguments, - ]); - } - if (isStandaloneArrowFunction(node.expression)) { - const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.expression.scriptFunction.id?.name) return node; - this.exitAnonymousScope(); - this.checkMemoCallInFunction(); - - this.enterAnonymousScope(node.expression.scriptFunction); - const res = this.updateScriptFunction( - node.expression.scriptFunction, - node.expression.scriptFunction.id?.name - ); - this.exitAnonymousScope(); + if (!!updateOverloads) { + updateMethod.setOverloads(castOverloadsToMethods(updateOverloads)); + } + return updateMethod; + } - return arkts.factory.updateCallExpression( - node, - arkts.factory.updateArrowFunction(node.expression, res), - node.typeArguments, - [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...node.arguments] - ); + private updateDeclaredMemoCall(node: arkts.CallExpression, decl: arkts.MethodDefinition): arkts.CallExpression { + this.checkMemoCallInMethod(decl); + const updatedArguments = node.arguments.map((it, index) => { + const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type; + if (type && arkts.isETSFunctionType(type)) { + if ( + !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) && + !hasMemoIntrinsicAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) + ) { + return it; //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) + } + if (arkts.isArrowFunctionExpression(it)) { + this.enterAnonymousScope(it.scriptFunction); + const res = this.updateScriptFunction(it.scriptFunction); + this.exitAnonymousScope(); + return arkts.factory.updateArrowFunction(it, res); + } } + return it; + }); + return arkts.factory.updateCallExpression(node, node.expression, undefined, [ + ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), + ...updatedArguments, + ]); + } + + private udpateAnonymousMemoCall( + node: arkts.CallExpression, + expression: arkts.ArrowFunctionExpression + ): arkts.CallExpression { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== expression.scriptFunction.id?.name) { + return node; } + this.exitAnonymousScope(); + this.checkMemoCallInFunction(); + + this.enterAnonymousScope(expression.scriptFunction); + const res = this.updateScriptFunction(expression.scriptFunction, expression.scriptFunction.id?.name); + this.exitAnonymousScope(); + + return arkts.factory.updateCallExpression( + node, + arkts.factory.updateArrowFunction(expression, res), + node.typeArguments, + [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...node.arguments] + ); + } + + private updateCallExpression(node: arkts.CallExpression): arkts.CallExpression { + const expr = node.expression; + const decl = arkts.getDecl(expr); if ( - arkts.isClassProperty(node) && - !!node.key && - arkts.isIdentifier(node.key) && - !!node.value && - arkts.isArrowFunctionExpression(node.value) + decl && + arkts.isMethodDefinition(decl) && + (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction)) ) { - const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.key?.name) return node; - this.exitAnonymousScope(); + return this.updateDeclaredMemoCall(node, decl); + } + if (isStandaloneArrowFunction(node.expression)) { + return this.udpateAnonymousMemoCall(node, node.expression); + } + return node; + } + + private updateClassProperty(node: arkts.ClassProperty, key: arkts.Identifier): arkts.ClassProperty { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== key.name) { + return node; + } + this.exitAnonymousScope(); + let res: arkts.ScriptFunction | undefined; + if (!!node.value && arkts.isArrowFunctionExpression(node.value)) { this.enterAnonymousScope(node.value.scriptFunction); - const res = this.updateScriptFunction(node.value.scriptFunction, node.key.name); + res = this.updateScriptFunction(node.value.scriptFunction, key.name); this.exitAnonymousScope(); + } - let typeAnnotation: arkts.TypeNode | undefined; - if (!!node.typeAnnotation && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-property ${node.key.name}`); - throw 'Invalid @memo usage'; - } + let typeAnnotation: arkts.TypeNode | undefined; + if (!!node.typeAnnotation && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-property ${key.name}`); + throw 'Invalid @memo usage'; + } - return arkts.factory.updateClassProperty( - node, - node.key, - arkts.factory.updateArrowFunction(node.value, res), - typeAnnotation, - node.modifiers, - node.isComputed - ); + return arkts.factory.updateClassProperty( + node, + node.key, + res ? arkts.factory.updateArrowFunction(castArrowFunctionExpression(node.value), res) : undefined, + typeAnnotation, + node.modifiers, + node.isComputed + ); + } + + private updateTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration): arkts.TSTypeAliasDeclaration { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== node.id?.name) { + return node; } - if (arkts.isTSTypeAliasDeclaration(node)) { - const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.id?.name) return node; - this.exitAnonymousScope(); + this.exitAnonymousScope(); - let typeAnnotation: arkts.TypeNode | undefined; - if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-type ${node.id!.name}`); - throw 'Invalid @memo usage'; - } + let typeAnnotation: arkts.TypeNode | undefined; + if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-type ${node.id!.name}`); + throw 'Invalid @memo usage'; + } + + return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation); + } - return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation); + private updateStandaloneArrowFunction(node: arkts.ArrowFunctionExpression): arkts.ArrowFunctionExpression { + const scope = this.scopes[this.scopes.length - 1]; + if (!scope || !scope.isMemo || scope.name !== node.scriptFunction.id?.name) { + return node; } - if (isStandaloneArrowFunction(node)) { - const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.scriptFunction.id?.name) return node; - this.exitAnonymousScope(); + this.exitAnonymousScope(); - this.enterAnonymousScope(node.scriptFunction); - const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); - this.exitAnonymousScope(); + this.enterAnonymousScope(node.scriptFunction); + const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); + this.exitAnonymousScope(); + + return arkts.factory.updateArrowFunction(node, res); + } - return arkts.factory.updateArrowFunction(node, res); + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { + this.enter(beforeChildren); + const node = this.visitEachChild(beforeChildren); + this.exit(beforeChildren); + if (arkts.isMethodDefinition(node)) { + return this.updateMethodDefinition(node); + } + if (arkts.isCallExpression(node)) { + return this.updateCallExpression(node); + } + if (arkts.isClassProperty(node) && !!node.key && arkts.isIdentifier(node.key)) { + return this.updateClassProperty(node, node.key); + } + if (arkts.isTSTypeAliasDeclaration(node)) { + return this.updateTSTypeAliasDeclaration(node); + } + if (isStandaloneArrowFunction(node)) { + return this.updateStandaloneArrowFunction(node); } return node; } diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index 44553ed5c..cae4fa891 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -207,6 +207,24 @@ export function castFunctionExpression(value: arkts.Expression | undefined): ark return value as unknown as arkts.FunctionExpression; } +/** + * es2panda API is weird here + * + * @deprecated + */ +export function castArrowFunctionExpression(value: arkts.Expression | undefined): arkts.ArrowFunctionExpression { + return value as unknown as arkts.ArrowFunctionExpression; +} + +/** + * es2panda API is weird here + * + * @deprecated + */ +export function castOverloadsToMethods(overloads: arkts.AstNode[]): readonly arkts.MethodDefinition[] { + return overloads as unknown as readonly arkts.MethodDefinition[]; +} + export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.ArrowFunctionExpression { if (!arkts.isArrowFunctionExpression(node)) return false; @@ -215,3 +233,42 @@ export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.Ar return !arkts.isClassProperty(node.parent) && !(arkts.isCallExpression(node.parent) && node.parent.expression); } + +export function isMemoClassProperty(node: arkts.ClassProperty): boolean { + let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); + if (node.value) { + isMemo ||= + arkts.isArrowFunctionExpression(node.value) && + (hasMemoAnnotation(node.value) || hasMemoIntrinsicAnnotation(node.value)); + } + isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + return isMemo; +} + +export function isMemoMethodDefinition(node: arkts.MethodDefinition): boolean { + return hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction); +} + +export function isMemoArrowFunction(node: arkts.ArrowFunctionExpression): boolean { + return hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); +} + +export function isMemoTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration): boolean { + let isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); + isMemo ||= hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + return isMemo; +} + +export function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | undefined): boolean { + if (!typeAnnotation) { + return false; + } + if (arkts.isETSFunctionType(typeAnnotation)) { + return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation); + } else if (arkts.isETSUnionType(typeAnnotation)) { + return typeAnnotation.types.some( + (type) => arkts.isETSFunctionType(type) && (hasMemoAnnotation(type) || hasMemoIntrinsicAnnotation(type)) + ); + } + return false; +} -- Gitee From 9979b1d419ee610ec34aafea955268eaad431a5b Mon Sep 17 00:00:00 2001 From: y00896775 Date: Wed, 9 Apr 2025 10:48:41 +0800 Subject: [PATCH 045/123] develop builderParam Signed-off-by: y00896775 Change-Id: I80d1ed06993ba7b0003bcb1037f20c7489e5d627 --- arkui-plugins/ui-plugins/component-transformer.ts | 4 ++-- .../ui-plugins/property-translators/builderParam.ts | 12 +++--------- .../ui-plugins/property-translators/utils.ts | 10 +++++++--- arkui-plugins/ui-plugins/utils.ts | 10 ++++++++-- 4 files changed, 20 insertions(+), 16 deletions(-) diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 4ece2392e..32bca2f24 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -346,8 +346,8 @@ export class ComponentTransformer extends AbstractVisitor { ); return [originMember, newMember]; } - if (hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { - originMember.setAnnotations([annotation('memo')]); + if (hasDecorator(member, DecoratorNames.BUILDER_PARAM) && !!originMember.typeAnnotation) { + originMember.typeAnnotation.setAnnotations([annotation('memo')]); } return [originMember]; } diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts index f6b08b836..bde4d63b9 100644 --- a/arkui-plugins/ui-plugins/property-translators/builderParam.ts +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -41,19 +41,13 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const mutableThis: arkts.Expression = generateThisBacking(newName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(mutableThis, originalName); - // const updateStruct: arkts.AstNode = this.generateUpdateStruct(mutableThis, originalName); currentStructInfo.initializeBody.push(initializeStruct); - // currentStructInfo.updateBody.push(updateStruct); arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( - newName, - this.property, - '', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE - ); + const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, '', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, true); const thisGetValue: arkts.Expression = generateThisBacking(newName, false, true); const thisSetValue: arkts.Expression = generateThisBacking(newName, false, false); const getter: arkts.MethodDefinition = this.translateGetter( @@ -75,7 +69,7 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.Expression ): arkts.MethodDefinition { - return createGetter(originalName, typeAnnotation, returnValue); + return createGetter(originalName, typeAnnotation, returnValue, true); } translateSetter( diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 595aced52..d564d1e08 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -83,13 +83,17 @@ export function getStateManagementType(node: arkts.ClassProperty): string { export function createGetter( name: string, type: arkts.TypeNode | undefined, - returns: arkts.Expression + returns: arkts.Expression, + needMemo: boolean = false, ): arkts.MethodDefinition { + const returnType: arkts.TypeNode | undefined = type?.clone(); + if (needMemo) { + returnType?.setAnnotations([annotation('memo')]); + } const body = arkts.factory.createBlock([arkts.factory.createReturnStatement(returns)]); - const scriptFunction = arkts.factory.createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature(undefined, [], type?.clone(), false), + arkts.FunctionSignature.createFunctionSignature(undefined, [], returnType, false), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_GETTER, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index c73d54b14..d4d6429f0 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -14,6 +14,7 @@ */ import * as arkts from '@koalaui/libarkts'; +import { annotation } from "../common/arkts-utils"; export enum CustomComponentNames { ENTRY_ANNOTATION_NAME = 'Entry', @@ -90,14 +91,19 @@ export function createOptionalClassProperty( name: string, property: arkts.ClassProperty, stageManagementIdent: string, - modifiers: arkts.Es2pandaModifierFlags + modifiers: arkts.Es2pandaModifierFlags, + needMemo: boolean = false ): arkts.ClassProperty { + const newType: arkts.TypeNode | undefined = property.typeAnnotation?.clone(); + if (needMemo) { + newType?.setAnnotations([annotation('memo')]); + } const newProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier(name), undefined, stageManagementIdent.length ? createStageManagementType(stageManagementIdent, property) - : property.typeAnnotation?.clone(), + : newType, modifiers, false ); -- Gitee From 3f154bab82e90be7ce65462a7cac58dc0d9adf26 Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Tue, 15 Apr 2025 11:22:48 +0800 Subject: [PATCH 046/123] fix reusable torecord Signed-off-by: fengyuxin Change-Id: I695f2e8f549b22719958e8da3b103bcf85478d44 --- arkui-plugins/ui-plugins/property-translators/utils.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 595aced52..95b8d8be0 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -282,16 +282,12 @@ export function generateToRecord(newName: string, originalName: string): arkts.P return arkts.Property.createProperty( arkts.factory.createStringLiteral(originalName), arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(newName), + arkts.factory.createIdentifier('paramsCasted'), + arkts.factory.createIdentifier(originalName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false - ), - 'get', - true ), arkts.ETSNewClassInstanceExpression.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( -- Gitee From 6f5a05e8436556abc3a3fcc5168215145f008cff Mon Sep 17 00:00:00 2001 From: l00913061 Date: Fri, 11 Apr 2025 11:33:20 +0800 Subject: [PATCH 047/123] add router register Signed-off-by: l00913061 Change-Id: I8efb8d9ac35896a15135047bfbf5db538eadb1c6 --- arkui-plugins/common/debug.ts | 2 +- .../test/demo/localtest/entry/new.ets | 65 ++++++++++--------- .../ui-plugins/checked-transformer.ts | 20 ++++++ .../ui-plugins/component-transformer.ts | 6 +- arkui-plugins/ui-plugins/router.ts | 58 +++++++++++++++++ .../ui-plugins/struct-translators/utils.ts | 15 +++++ arkui-plugins/ui-plugins/utils.ts | 5 ++ 7 files changed, 138 insertions(+), 33 deletions(-) create mode 100644 arkui-plugins/ui-plugins/router.ts diff --git a/arkui-plugins/common/debug.ts b/arkui-plugins/common/debug.ts index f39940e8f..9b5eca654 100644 --- a/arkui-plugins/common/debug.ts +++ b/arkui-plugins/common/debug.ts @@ -16,7 +16,7 @@ import * as fs from 'fs'; import * as path from 'path'; import * as arkts from '@koalaui/libarkts'; -const isDebugLog: boolean = false; +const isDebugLog: boolean = true; const isDebugDump: boolean = false; const isPerformance: boolean = false; arkts.Performance.getInstance().skip(!isPerformance); diff --git a/arkui-plugins/test/demo/localtest/entry/new.ets b/arkui-plugins/test/demo/localtest/entry/new.ets index d8deb6b40..87d3c02b0 100755 --- a/arkui-plugins/test/demo/localtest/entry/new.ets +++ b/arkui-plugins/test/demo/localtest/entry/new.ets @@ -18,51 +18,58 @@ import { Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickE import { State, Link, StateDecoratedVariable, LinkDecoratedVariable,MutableState, stateOf, observableProxy } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins import hilog from '@ohos.hilog' +@Entry @Component struct MyStateSample { - @State stateVar: string = "Parent"; - message: string = "var"; + @State stateVar: string = "state var"; + message: string = `click to change state variable, add **`; changeValue() { - this.stateVar+="~"; + this.stateVar+="**" } build() { - Column(undefined) { - Button("ParentChange").backgroundColor("#FFFF00FF") + Column() { + Button("clean variable").onClick((e: ClickEvent) => { this.stateVar = "state var" }) + Text("Hello World").fontSize(20) + Button(this.message).backgroundColor("#FFFF00FF") .onClick((e: ClickEvent) => { hilog.info(0x0000, 'testTag', 'On Click'); - this.changeValue(); + this.changeValue() }) Text(this.stateVar).fontSize(20) - ChildLink({stateVar: this.stateVar, stateVar1: this.stateVar, stateVar2: ""} as __Options_ChildLink) - } + Child({linkVar: this.stateVar, propVar: this.stateVar}) + }.margin(10) } } @Component -struct ChildLink { - @Link stateVar: string = "Child"; - @State stateVar1: string = "Child"; - @Link stateVar2: string = "Child"; - changeValue() { - this.stateVar+="~"; +struct Child { + @Link linkVar: string; + @Prop propVar: string = "Prop"; + + changeValue1() { + this.linkVar+="!!" } - build() { - Button("ChildChange").backgroundColor("#FFFF00FF") - .onClick((e: ClickEvent) => { - hilog.info(0x0000, 'testTag', 'On Click'); - this.changeValue(); - }) - Text(this.stateVar).fontSize(50) + + changeValue2() { + this.propVar+="~~" } -} -export class ComExampleTrivialApplication extends UserView { - getBuilder() { - hilog.info(0x0000, 'testTag', 'getBuilder'); - let wrapper = @memo () => { - hilog.info(0x0000, 'testTag', 'MyStateSample'); - MyStateSample(undefined); + build() { + Column() { + Button(`click to change Link variable, add symbol !!`) + .backgroundColor("#4169E1") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + this.changeValue1() + }) + Button(`click to change Prop variable, add symbol ~~`) + .backgroundColor("#3CB371") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + this.changeValue2() + }) + Text(`Link variable in child: ${this.linkVar}`).fontSize(30) + Text(`Prop variable in child: ${this.propVar}`).fontSize(30) } - return wrapper; } } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index e23a7f260..14ba5bb50 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -35,6 +35,7 @@ import { isKnownMethodDefinition, isEtsGlobalClass, isReourceNode, + isEntryClass, } from './struct-translators/utils'; import { isBuilderLambda, @@ -51,6 +52,7 @@ import { } from './builder-lambda-translators/utils'; import { isEntryWrapperClass } from './entry-translators/utils'; import { classifyProperty, PropertyTranslator } from './property-translators'; +import { createRegisterMethod } from './router'; export class CheckedTransformer extends AbstractVisitor { private scopeInfos: ScopeInfo[] = []; @@ -115,11 +117,29 @@ export class CheckedTransformer extends AbstractVisitor { return transformEtsGlobalClassMembers(node); } else if (arkts.isCallExpression(node) && isReourceNode(node)) { return transformResource(node, this.projectConfig); + } else if (arkts.isClassDeclaration(node) && isEntryClass(node)) { + const newNode = addRegisterRouterMethod(node); + return newNode; + } else if (arkts.isETSImportDeclaration(node)) { + const specifiers = node.specifiers; + for (const specifier of specifiers) { + const decl = arkts.getDecl(specifier); + console.log("print import decl:" + specifier.imported?.name) + console.log(decl?.dumpJson()); + } } return node; } } +function addRegisterRouterMethod( + node: arkts.ClassDeclaration +): arkts.ClassDeclaration { + const definition: arkts.ClassDefinition = node.definition!; + const registerMethod = createRegisterMethod() + return node; +} + function tranformClassMembers( node: arkts.ClassDeclaration, isDecl?: boolean, diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 4ece2392e..9bc1924b6 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -257,14 +257,14 @@ export class ComponentTransformer extends AbstractVisitor { definition: arkts.ClassDefinition, newDefinitionBody: arkts.AstNode[] ): arkts.ClassDefinition { - const staticMethonBody: arkts.AstNode[] = []; + const staticMethodBody: arkts.AstNode[] = []; const hasExportFlag = (node.modifiers & arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT) === arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; if (hasExportFlag) { const buildCompatibleNode: arkts.MethodDefinition = this.createStaticMethod(definition); if (!!buildCompatibleNode) { - staticMethonBody.push(buildCompatibleNode); + staticMethodBody.push(buildCompatibleNode); } } return arkts.factory.updateClassDefinition( @@ -291,7 +291,7 @@ export class ComponentTransformer extends AbstractVisitor { ]) ) ), - [...newDefinitionBody, ...definition.body, ...staticMethonBody], + [...newDefinitionBody, ...definition.body, ...staticMethodBody], definition.modifiers, arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL ); diff --git a/arkui-plugins/ui-plugins/router.ts b/arkui-plugins/ui-plugins/router.ts new file mode 100644 index 000000000..202555f73 --- /dev/null +++ b/arkui-plugins/ui-plugins/router.ts @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getCustomComponentOptionsName, Router } from './utils'; + + +export function addRegisterRouterMethod( + node: arkts.ClassDeclaration +): arkts.ClassDeclaration { + const definition: arkts.ClassDefinition = node.definition!; + const registerMethod = createRegisterMethod() + return node; +} + +export function createRegisterMethod(): arkts.MethodDefinition { + const script = arkts.factory.createScriptFunction( + arkts.factory.createBlock([createRegisterCall()]), + arkts.FunctionSignature.createFunctionSignature( + undefined, + [], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC + ); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + arkts.factory.createIdentifier(Router.REGISTERROUTER), + arkts.factory.createFunctionExpression(script), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + false + ); +} + +export function createRegisterCall (): arkts.Statement { + return arkts.factory.createCallExpression( + arkts.factory.createIdentifier(Router.REGISTERPAGE), + undefined, + [ + + ] + ) +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts index 502917ecf..1c3ebf9af 100644 --- a/arkui-plugins/ui-plugins/struct-translators/utils.ts +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -16,6 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { Dollars } from '../utils'; import { CustomComponentNames } from '../utils'; +import { isAnnotation } from '../../common/arkts-utils'; export type ScopeInfo = { name: string; @@ -77,3 +78,17 @@ export function isReourceNode(node: arkts.CallExpression): boolean { } return false; } + +/** + * Determine whether it is Entry class. + * + * @param node class declaration node + */ +export function isEntryClass(node: arkts.ClassDeclaration): boolean { + node.definition!.annotations.forEach((anno) => { + if (isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION_NAME)) { + return true; + } + }) + return false; +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index c73d54b14..d6432288a 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -48,6 +48,11 @@ export enum Dollars { DOLLAR_DOLLAR = '$$', } +export enum Router { + REGISTERROUTER = 'registerRouter', + REGISTERPAGE = 'registerPage', +} + export function findLocalImport( node: arkts.ETSImportDeclaration, sourceName: string, -- Gitee From 42d457dfc39c98705c2e7628d365e7896fd42183 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Tue, 15 Apr 2025 15:21:52 +0800 Subject: [PATCH 048/123] fix prop bug and transform regular property Signed-off-by: y00896775 Change-Id: Iff366754ec7eefb6a455bbbe5b3915ca9be3913b --- .../ui-plugins/property-translators/prop.ts | 22 ++++--- .../property-translators/regularProperty.ts | 66 +++++++++++++++---- 2 files changed, 66 insertions(+), 22 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts index 5874336e0..7745be3e6 100644 --- a/arkui-plugins/ui-plugins/property-translators/prop.ts +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -103,12 +103,15 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon this.property.value ?? arkts.factory.createIdentifier('undefined'), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ); - const nonNullItem = arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true) - ); const args: arkts.Expression[] = [ arkts.factory.create1StringLiteral(originalName), - this.property.value ? binaryItem : nonNullItem, + this.property.value + ? binaryItem + : arkts.factory.createTSAsExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true), + this.property.typeAnnotation ? this.property.typeAnnotation.clone() : undefined, + false + ), ]; judgeIfAddWatchFunc(args, this.property); const right = arkts.factory.createETSNewClassInstanceExpression( @@ -146,14 +149,17 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon false, false ); - const nonNullItem = arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true) - ); return arkts.factory.createIfStatement( binaryItem, arkts.factory.createBlock([ arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(member, undefined, [nonNullItem]) + arkts.factory.createCallExpression(member, undefined, [ + arkts.factory.createTSAsExpression( + factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true), + this.property.typeAnnotation ? this.property.typeAnnotation.clone() : undefined, + false + ), + ]) ), ]) ); diff --git a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts index 875f14d35..795ff6b46 100644 --- a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts +++ b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts @@ -15,10 +15,12 @@ import * as arkts from '@koalaui/libarkts'; -import { createGetter, createSetter } from './utils'; +import { createGetter, generateToRecord, generateThisBacking, createSetter2 } from './utils'; import { PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; +import { createOptionalClassProperty } from '../utils'; import { backingField, expectName } from '../../common/arkts-utils'; +import { factory } from './factory'; export class regularPropertyTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -28,10 +30,44 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini return this.translateWithoutInitializer(newName, originalName); } - cacheTranslatedInitializer(newName: string, originalName: string): void {} + cacheTranslatedInitializer(newName: string, originalName: string): void { + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + currentStructInfo.initializeBody.push(initializeStruct); + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } + arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - return [this.property]; + const field: arkts.ClassProperty = createOptionalClassProperty( + newName, + this.property, + '', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); + const thisValue: arkts.Expression = generateThisBacking(newName, false, false); + const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( + arkts.factory.createBinaryExpression( + thisValue, + arkts.factory.createIdentifier('value'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_EQUAL + ) + ); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + arkts.factory.createTSAsExpression(thisValue, this.property.typeAnnotation, false) + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisSet + ); + + return [field, getter, setter]; } translateGetter( @@ -45,23 +81,25 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - left: arkts.MemberExpression + statement: arkts.AstNode ): arkts.MethodDefinition { - const right: arkts.Identifier = arkts.factory.createIdentifier('value'); - return createSetter(originalName, typeAnnotation, left, right); + return createSetter2(originalName, typeAnnotation, statement); } generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { - return arkts.factory.createAssignmentExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('this'), - arkts.factory.createIdentifier(originalName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false + const binaryItem = arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName ), + this.property.value ?? arkts.factory.createIdentifier('undefined'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ); + const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( + generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - this.property.value ?? arkts.factory.createIdentifier('undefined') + binaryItem ); + return arkts.factory.createExpressionStatement(assign); } } -- Gitee From 08778a552f630c0b62ead1e81a1d52cace900cd6 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Fri, 11 Apr 2025 17:51:34 +0800 Subject: [PATCH 049/123] develop provide and consume Signed-off-by: y00896775 Change-Id: I3a5d04bff0c6df6869a060ee5184d0fd8b87c806 --- arkui-plugins/common/predefines.ts | 6 +- .../property-translators/consume.ts | 61 ++++++------- .../property-translators/factory.ts | 66 +++++++++++++- .../property-translators/provide.ts | 91 +++++++------------ .../ui-plugins/property-translators/utils.ts | 63 ++++++++----- .../src/arkts-api/factory/nodeFactory.ts | 6 +- koala-wrapper/src/arkts-api/index.ts | 1 + 7 files changed, 175 insertions(+), 119 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 08ce2babe..d9daf0384 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -67,6 +67,8 @@ export const IMPORT_SOURCE_MAP: Map> = new Map = new Map(, "uuuutttt", initializers?.uuuutttt ?? 1.5, false, watch)`. + */ + static generateAddProvideVarCall( + originalName: string, + property: arkts.ClassProperty, + alias: string, + allowOverride: boolean = false + ): arkts.CallExpression { + const args: arkts.Expression[] = [ + arkts.factory.create1StringLiteral(originalName), + arkts.factory.create1StringLiteral(alias), + arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName + ), + property.value ?? arkts.factory.createIdentifier('undefined'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ), + arkts.factory.createBooleanLiteral(allowOverride), + ]; + judgeIfAddWatchFunc(args, property); + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('addProvidedVar'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + property.typeAnnotation ? [property.typeAnnotation.clone()] : undefined, + args + ); + } + + /* + * create `this.initConsume("uuuutttt", "uuuutttt", watchFunc)`. + */ + static generateInitConsumeCall( + originalName: string, + property: arkts.ClassProperty, + alias: string + ): arkts.CallExpression { + const args: arkts.Expression[] = [ + arkts.factory.create1StringLiteral(originalName), + arkts.factory.create1StringLiteral(alias), + ]; + judgeIfAddWatchFunc(args, property); + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('initConsume'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + property.typeAnnotation ? [property.typeAnnotation.clone()] : undefined, + args + ); + } } diff --git a/arkui-plugins/ui-plugins/property-translators/provide.ts b/arkui-plugins/ui-plugins/property-translators/provide.ts index ced49cefa..144d1239a 100644 --- a/arkui-plugins/ui-plugins/property-translators/provide.ts +++ b/arkui-plugins/ui-plugins/property-translators/provide.ts @@ -15,7 +15,15 @@ import * as arkts from '@koalaui/libarkts'; -import { createGetter, createSetter, generateThisBackingValue, getValueInAnnotation, DecoratorNames } from './utils'; +import { + generateToRecord, + createGetter, + createSetter2, + generateThisBacking, + generateGetOrSetCall, + getValueInProvideAnnotation, + ProvideOptions, +} from './utils'; import { PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; @@ -32,8 +40,12 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer cacheTranslatedInitializer(newName: string, originalName: string): void { const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); currentStructInfo.initializeBody.push(initializeStruct); + if (currentStructInfo.isReusable) { + const toRecord = generateToRecord(newName, originalName); + currentStructInfo.toRecordBody.push(toRecord); + } arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } @@ -41,19 +53,23 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer const field: arkts.ClassProperty = createOptionalClassProperty( newName, this.property, - 'MutableState', + 'ProvideDecoratedVariable', arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); - const thisValue: arkts.MemberExpression = generateThisBackingValue(newName, false, true); + const thisValue: arkts.Expression = generateThisBacking(newName, false, true); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( + generateGetOrSetCall(thisValue, 'set') + ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, this.property.typeAnnotation, - thisValue + thisGet ); const setter: arkts.MethodDefinition = this.translateSetter( originalName, this.property.typeAnnotation, - thisValue + thisSet ); return [field, getter, setter]; @@ -62,7 +78,7 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer translateGetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - returnValue: arkts.MemberExpression + returnValue: arkts.Expression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } @@ -70,59 +86,20 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - left: arkts.MemberExpression + statement: arkts.AstNode ): arkts.MethodDefinition { - const right: arkts.CallExpression = arkts.factory.createCallExpression( - arkts.factory.createIdentifier('observableProxy'), - undefined, - [arkts.factory.createIdentifier('value')] - ); - - return createSetter(originalName, typeAnnotation, left, right); + return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(newName: string, originName: string): arkts.AstNode { - let provideValueStr: string | undefined = getValueInAnnotation(this.property, DecoratorNames.PROVIDE); - if (!provideValueStr) { - provideValueStr = originName; - } - const memExp: arkts.Expression = factory.createDoubleBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - newName, - 'value' - ); - const body: arkts.BlockStatement = arkts.factory.createBlock([ - arkts.factory.createReturnStatement( - arkts.factory.createBinaryExpression( - memExp, - this.property.value, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING - ) - ), - ]); - const script = arkts.factory.createScriptFunction( - body, - arkts.FunctionSignature.createFunctionSignature(undefined, [], this.property.typeAnnotation, false), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ); - const right: arkts.CallExpression = arkts.factory.createCallExpression( - arkts.factory.createIdentifier('contextLocalStateOf'), - this.property.typeAnnotation ? [this.property.typeAnnotation] : undefined, - [arkts.factory.create1StringLiteral(provideValueStr), arkts.factory.createArrowFunction(script)] - ); - return arkts.factory.createExpressionStatement( - arkts.factory.createAssignmentExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(newName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - right - ) + generateInitializeStruct(originalName: string, newName: string): arkts.AstNode { + const options: undefined | ProvideOptions = getValueInProvideAnnotation(this.property); + const alias: string = options?.alias ?? originalName; + const allowOverride: boolean = options?.allowOverride ?? false; + const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( + generateThisBacking(newName), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + factory.generateAddProvideVarCall(originalName, this.property, alias, allowOverride) ); + return arkts.factory.createExpressionStatement(assign); } } diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 595aced52..c63db5406 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -71,6 +71,10 @@ export function getStateManagementType(node: arkts.ClassProperty): string { return 'StorageLinkDecoratedVariable'; } else if (hasDecorator(node, DecoratorNames.STORAGE_PROP)) { return 'StoragePropDecoratedVariable'; + } else if (hasDecorator(node, DecoratorNames.PROVIDE)) { + return 'ProvideDecoratedVariable'; + } else if (hasDecorator(node, DecoratorNames.CONSUME)) { + return 'ConsumeDecoratedVariable'; } else if ( hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP) || hasDecorator(node, DecoratorNames.OBJECT_LINK) @@ -223,40 +227,57 @@ export function getValueInAnnotation(node: arkts.ClassProperty, decoratorName: D return undefined; } -function getWatchValueStr(node: arkts.AstNode): string | undefined { - if (!arkts.isClassProperty(node) || !node.value) { - return undefined; - } - return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +export interface ProvideOptions { + alias: string; + allowOverride: boolean; } -function getWatchAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { - const isWatchAnnotation: boolean = - !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.WATCH; - - if (isWatchAnnotation && anno.properties.length === 1) { - return getWatchValueStr(anno.properties.at(0)!); - } - return undefined; -} - -function getWatchValueInAnnotation(node: arkts.ClassProperty): string | undefined { +export function getValueInProvideAnnotation(node: arkts.ClassProperty): ProvideOptions | undefined { const annotations: readonly arkts.AnnotationUsage[] = node.annotations; - for (let i = 0; i < annotations.length; i++) { const anno: arkts.AnnotationUsage = annotations[i]; - const str: string | undefined = getWatchAnnotationValue(anno); - if (!!str) { - return str; + const alias: string | undefined = getValueInObjectAnnotation(anno, DecoratorNames.PROVIDE, 'alias'); + const allowOverride: boolean = getValueInObjectAnnotation(anno, DecoratorNames.PROVIDE, 'allowOverride') + ? true + : false; + if (!!alias) { + return { alias, allowOverride }; } } + return undefined; +} +function getValueInObjectAnnotation(anno: arkts.AnnotationUsage, decoratorName: DecoratorNames, key: string): any { + const isSuitableAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === decoratorName; + if (!isSuitableAnnotation) { + return undefined; + } + const keyItem: arkts.AstNode | undefined = anno.properties.find( + (annoProp: arkts.AstNode) => + arkts.isClassProperty(annoProp) && + annoProp.key && + arkts.isIdentifier(annoProp.key) && + annoProp.key.name === key + ); + if (keyItem && arkts.isClassProperty(keyItem) && keyItem.value) { + return getDifferentAnnoTypeValue(keyItem.value); + } return undefined; } +function getDifferentAnnoTypeValue(value: arkts.Expression): string | boolean { + if (arkts.isBooleanLiteral(value)) { + return value.value; + } else if (arkts.isStringLiteral(value)) { + return value.str; + } + return value.dumpSrc(); +} + export function judgeIfAddWatchFunc(args: arkts.Expression[], property: arkts.ClassProperty): void { if (hasDecorator(property, DecoratorNames.WATCH)) { - const watchStr: string | undefined = getWatchValueInAnnotation(property); + const watchStr: string | undefined = getValueInAnnotation(property, DecoratorNames.WATCH); if (watchStr) { args.push(factory.createWatchCallback(watchStr)); } diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index 394dad37e..2593f1b83 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -69,7 +69,8 @@ import { TSTypeAliasDeclaration, ChainExpression, BlockExpression, - ETSNewClassInstanceExpression + ETSNewClassInstanceExpression, + BooleanLiteral } from "../../generated" import { Es2pandaModifierFlags @@ -561,6 +562,9 @@ export const factory = { get createETSStringLiteralType(){ return ETSStringLiteralType.create; }, + get createBooleanLiteral(): (value: boolean) => BooleanLiteral { + return BooleanLiteral.createBooleanLiteral; + }, /** @deprecated */ createTypeParameter1_(name: Identifier, constraint?: TypeNode, defaultType?: TypeNode) { return TSTypeParameter.createTSTypeParameter(Identifier.create1Identifier(name.name), constraint, defaultType) diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index 463ae2730..930427b68 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -56,6 +56,7 @@ export * from "../generated/peers/ETSNewClassInstanceExpression" export * from "../generated/peers/ObjectExpression" export * from "../generated/peers/Property" export * from "../generated/peers/BlockExpression" +export * from "../generated/peers/BooleanLiteral" export * from "./types" export * from "./utilities/private" -- Gitee From f994ae693fb1976d53af2593be81907ad7d774e9 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 16 Apr 2025 19:42:44 +0800 Subject: [PATCH 050/123] fix lsp failed to clean node cache Signed-off-by: Jiakai Shi Change-Id: I7deb770c23a9a36348c8c692c90ec319075f159d --- koala-wrapper/src/arkts-api/static/globalUtils.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/koala-wrapper/src/arkts-api/static/globalUtils.ts b/koala-wrapper/src/arkts-api/static/globalUtils.ts index 5d1b4b2dd..8e3a91074 100644 --- a/koala-wrapper/src/arkts-api/static/globalUtils.ts +++ b/koala-wrapper/src/arkts-api/static/globalUtils.ts @@ -16,9 +16,11 @@ import { KNativePointer } from "@koalaui/interop"; import { Context } from "../peers/Context"; import { global } from "./global"; +import { clearNodeCache } from "../class-by-peer"; export function getOrUpdateGlobalContext(peer: KNativePointer): Context { if (!global.compilerContext || global.context !== peer) { + clearNodeCache(); global.compilerContext = new Context(peer); } return global.compilerContext; -- Gitee From 0083845bd594a6cc8c1f2e32d9026dba23b22443 Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Tue, 15 Apr 2025 19:27:30 +0800 Subject: [PATCH 051/123] implement @Observed @Track transform Signed-off-by: fengyuxin Change-Id: If2dd0c23fed545d2ae803a3fe13c5cea63966dd0 --- arkui-plugins/common/predefines.ts | 11 +- .../ui-plugins/checked-transformer.ts | 108 +++++- .../ui-plugins/property-translators/index.ts | 9 + .../property-translators/observedTrack.ts | 336 ++++++++++++++++++ .../ui-plugins/property-translators/utils.ts | 1 + .../ui-plugins/struct-translators/factory.ts | 8 +- arkui-plugins/ui-plugins/utils.ts | 8 + koala-wrapper/src/arkts-api/index.ts | 1 + 8 files changed, 476 insertions(+), 6 deletions(-) create mode 100644 arkui-plugins/ui-plugins/property-translators/observedTrack.ts diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 7e705f511..65eb9e864 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -52,6 +52,8 @@ export const IMPORT_SOURCE_MAP: Map> = new Map> = new Map = new Map([ @@ -86,7 +93,9 @@ export const OUTPUT_DEPENDENCY_MAP: Map = new Map arkts.isClassProperty(member) && hasDecorator(member, DecoratorNames.TRACK) + ); + if (!isObserved && !classHasTrack) { return node; } + + const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( + node.definition, + node.definition.ident, + node.definition.typeParams, + node.definition.superTypeParams, + [ + ...node.definition.implements, + arkts.TSClassImplements.createTSClassImplements( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('IObservedObject')) + ) + ), + ], + undefined, + node.definition.super, + observedTrackPropertyMembers(classHasTrack, node.definition, isObserved), + node.definition.modifiers, + arkts.classDefinitionFlags(node.definition) + ); + return arkts.factory.updateClassDeclaration(node, updateClassDef); +} + +function observedTrackPropertyMembers( + classHasTrack: boolean, + definition: arkts.ClassDefinition, + isObserved: boolean +): arkts.AstNode[] { + const permissibleAddRefDepth: arkts.ClassProperty = arkts.factory.createClassProperty( + arkts.factory.createIdentifier('_permissibleAddRefDepth'), + arkts.factory.createNumericLiteral(2147483647), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('int32')) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + + const meta: arkts.ClassProperty = arkts.factory.createClassProperty( + arkts.factory.createIdentifier('__meta'), + arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) + ), + [arkts.factory.createStringLiteral('@Observe properties (no @Track)')] + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + + const getters: arkts.MethodDefinition[] = getGettersFromClassDecl(definition); + + const classScopeInfo: ClassScopeInfo = { + isObserved: isObserved, + classHasTrack: classHasTrack, + getters: getters, + }; + + const propertyTranslators: ObservedTrackTranslator[] = filterDefined( + definition.body.map((it) => classifyObservedTrack(it, classScopeInfo)) + ); + + const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); + + const nonClassPropertyOrGetter: arkts.AstNode[] = definition.body.filter( + (member) => + !arkts.isClassProperty(member) && + !( + arkts.isMethodDefinition(member) && + arkts.hasModifierFlag(member, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_GETTER) + ) + ); + + return [ + ...(classHasTrack ? [permissibleAddRefDepth] : [permissibleAddRefDepth, meta]), + ...collect(...propertyMembers), + ...nonClassPropertyOrGetter, + ...classScopeInfo.getters, + ]; } function tranformClassMembers( diff --git a/arkui-plugins/ui-plugins/property-translators/index.ts b/arkui-plugins/ui-plugins/property-translators/index.ts index c30ace4fc..013eaa286 100644 --- a/arkui-plugins/ui-plugins/property-translators/index.ts +++ b/arkui-plugins/ui-plugins/property-translators/index.ts @@ -31,6 +31,8 @@ import { StoragePropTranslator } from './storageProp'; import { ConsumeTranslator } from './consume'; import { ProvideTranslator } from './provide'; import { BuilderParamTranslator } from './builderParam'; +import { ObservedTrackTranslator } from './observedTrack'; +import { ClassScopeInfo } from 'ui-plugins/checked-transformer'; export { PropertyTranslator }; @@ -74,3 +76,10 @@ export function classifyProperty(member: arkts.AstNode, structName: string): Pro return new regularPropertyTranslator(member, structName); } + +export function classifyObservedTrack(member: arkts.AstNode, classScopeInfo: ClassScopeInfo): ObservedTrackTranslator | undefined { + if (!arkts.isClassProperty(member)) { + return undefined; + } + return new ObservedTrackTranslator(member, classScopeInfo); +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts new file mode 100644 index 000000000..9bea0c3d1 --- /dev/null +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, hasDecorator } from './utils'; +import { ClassScopeInfo } from 'ui-plugins/checked-transformer'; + +export class ObservedTrackTranslator { + constructor(protected property: arkts.ClassProperty, protected classScopeInfo: ClassScopeInfo) {} + + private hasImplement: boolean = expectName(this.property.key).startsWith(''); + private isTracked: boolean = hasDecorator(this.property, DecoratorNames.TRACK); + + translateMember(): arkts.AstNode[] { + if (!this.isTracked && (this.classScopeInfo.classHasTrack || !this.classScopeInfo.isObserved)) { + return [this.property]; + } + const originalName: string = this.hasImplement + ? this.removeImplementProperty(expectName(this.property.key)) + : expectName(this.property.key); + const newName: string = backingField(originalName); + let properyIsClass = false; + + if (this.property.typeAnnotation && arkts.isETSTypeReference(this.property.typeAnnotation)) { + const decl = arkts.getDecl(this.property.typeAnnotation.part?.name!); + if (arkts.isClassDefinition(decl!)) { + properyIsClass = true; + } + } + const field = this.createField(originalName, newName, properyIsClass); + + this.transformGetterSetter(originalName, newName, properyIsClass); + + return [...field]; + } + + createField(originalName: string, newName: string, properyIsClass: boolean): arkts.ClassProperty[] { + const backingField = properyIsClass + ? this.propertyIsClassField(newName) + : arkts.factory.createClassProperty( + arkts.factory.createIdentifier(newName), + this.property.value, + this.property.typeAnnotation, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + if (!this.isTracked) { + return [backingField]; + } + const metaField = this.metaField(originalName); + return [backingField, metaField]; + } + + createGetter(originalName: string, newName: string, properyIsClass: boolean): arkts.MethodDefinition { + const ifRefDepth: arkts.IfStatement = this.getterIfRefDepth(originalName); + const returnMember: arkts.ReturnStatement = this.getterReturnMember(properyIsClass, newName); + const setObservationDepth = this.getterSetObservationDepth(newName); + + const body = arkts.factory.createBlock([ + ifRefDepth, + ...(properyIsClass ? [setObservationDepth] : []), + returnMember, + ]); + + const scriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature(undefined, [], this.property.typeAnnotation, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_GETTER, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, + arkts.factory.createIdentifier(originalName), + arkts.factory.createFunctionExpression(scriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + } + + createSetter(originalName: string, newName: string, properyIsClass: boolean): arkts.MethodDefinition { + const ifEqualsNewValue: arkts.IfStatement = this.setterIfEqualsNewValue(properyIsClass, originalName, newName); + const body = arkts.factory.createBlock([ifEqualsNewValue]); + const param = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('newValue', this.property.typeAnnotation), + undefined + ); + + const scriptFunction = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature(undefined, [param], undefined, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_SETTER, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, + arkts.factory.createIdentifier(originalName), + arkts.factory.createFunctionExpression(scriptFunction), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + } + + genThisBacking(newName: string): arkts.MemberExpression { + return arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); + } + + genThisBackingValue(newName: string): arkts.MemberExpression { + return arkts.factory.createMemberExpression( + this.genThisBacking(newName), + arkts.factory.createIdentifier('value'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); + } + + metaIdentifier(originalName: string): arkts.Identifier { + return this.isTracked + ? arkts.factory.createIdentifier(`__meta_${originalName}`) + : arkts.factory.createIdentifier('__meta'); + } + + removeImplementProperty(originalName: string): string { + const prefix = ''; + return originalName.substring(prefix.length); + } + + transformGetterSetter(originalName: string, newName: string, properyIsClass: boolean): void { + const newGetter = this.createGetter(originalName, newName, properyIsClass); + const newSetter = this.createSetter(originalName, newName, properyIsClass); + if (this.hasImplement) { + { + const idx: number = this.classScopeInfo.getters.findIndex( + (getter) => getter.name.name === originalName + ); + const originGetter: arkts.MethodDefinition = this.classScopeInfo.getters[idx]; + const originSetter: arkts.MethodDefinition = originGetter.overloads[0]; + const updateGetter: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( + originGetter, + newGetter.kind, + newGetter.name, + arkts.factory.createFunctionExpression(newGetter.scriptFunction), + originGetter.modifiers, + false + ); + const updateSetter: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( + originSetter, + newSetter.kind, + newSetter.name, + arkts.factory.createFunctionExpression(newSetter.scriptFunction), + originSetter.modifiers, + false + ); + // updateGetter.setOverloads([updateSetter]) + this.classScopeInfo.getters[idx] = updateGetter; + this.classScopeInfo.getters.push(updateSetter); + } + } else { + this.classScopeInfo.getters.push(...[newGetter, newSetter]); + } + } + + propertyIsClassField(newName: string): arkts.ClassProperty { + return arkts.factory.createClassProperty( + arkts.factory.createIdentifier(newName), + arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('BackingValue'), + arkts.factory.createTSTypeParameterInstantiation( + this.property.typeAnnotation ? [this.property.typeAnnotation] : [] + ) + ) + ), + [arkts.factory.createETSNewClassInstanceExpression(this.property.typeAnnotation, [])] + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('BackingValue'), + arkts.factory.createTSTypeParameterInstantiation( + this.property.typeAnnotation ? [this.property.typeAnnotation] : [] + ) + ) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + } + + metaField(originalName: string): arkts.ClassProperty { + return arkts.factory.createClassProperty( + arkts.factory.createIdentifier(`__meta_${originalName}`), + arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) + ), + [arkts.factory.createStringLiteral('@Track')] + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + } + + getterIfRefDepth(originalName: string): arkts.IfStatement { + return arkts.factory.createIfStatement( + arkts.factory.createBinaryExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('_permissibleAddRefDepth'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.factory.createNumericLiteral(0), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_GREATER_THAN + ), + arkts.factory.createBlock([ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + this.metaIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.factory.createIdentifier('addRef'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined, + false, + false + ) + ), + ]) + ); + } + + getterSetObservationDepth(newName: string): arkts.ExpressionStatement { + return arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression(arkts.factory.createIdentifier('setObservationDepth'), undefined, [ + this.genThisBackingValue(newName), + arkts.factory.createBinaryExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('_permissibleAddRefDepth'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.factory.createNumericLiteral(1), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_MINUS + ), + ]) + ); + } + + getterReturnMember(properyIsClass: boolean, newName: string): arkts.ReturnStatement { + return arkts.factory.createReturnStatement( + arkts.factory.createTSNonNullExpression( + properyIsClass ? this.genThisBackingValue(newName) : this.genThisBacking(newName) + ) + ); + } + + setterIfEqualsNewValue(properyIsClass: boolean, originalName: string, newName: string): arkts.IfStatement { + const backingValue: arkts.MemberExpression = properyIsClass + ? this.genThisBackingValue(newName) + : this.genThisBacking(newName); + + const setNewValue = arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + backingValue, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + arkts.factory.createIdentifier('newValue') + ) + ); + + const fireChange = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + this.metaIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.factory.createIdentifier('fireChange'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined + ) + ); + + return arkts.factory.createIfStatement( + arkts.factory.createBinaryExpression( + backingValue, + arkts.factory.createIdentifier('newValue'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL + ), + arkts.factory.createBlock([setNewValue, fireChange]) + ); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 3448db493..70d3c9897 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -34,6 +34,7 @@ export enum DecoratorNames { LOCAL_STORAGE_PROP = 'LocalStorageProp', LOCAL_STORAGE_LINK = 'LocalStorageLink', REUSABLE = 'Reusable', + TRACK = 'Track' } export function collectPropertyDecorators(property: arkts.ClassProperty): string[] { diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index 4b2d08594..2f07870cd 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -33,7 +33,7 @@ export class factory { } /* - * create _build menthod. + * create _build method. */ static transformBuildMethodWithOriginBuild( method: arkts.MethodDefinition, @@ -92,7 +92,7 @@ export class factory { } /* - * create __initializeStruct menthod. + * create __initializeStruct method. */ static createInitializeStruct( structInfo: arkts.StructInfo, @@ -133,7 +133,7 @@ export class factory { } /* - * create __updateStruct menthod. + * create __updateStruct method. */ static createUpdateStruct( structInfo: arkts.StructInfo, @@ -175,7 +175,7 @@ export class factory { } /* - * create __toRecord menthod when the component is decorated with @Reusable. + * create __toRecord method when the component is decorated with @Reusable. */ static toRecord(optionsTypeName: string, toRecordBody: arkts.Property[]): arkts.MethodDefinition { const paramsCasted = factory.generateParamsCasted(optionsTypeName); diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index d4d6429f0..a50608fee 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -123,3 +123,11 @@ export function createStageManagementType( ) ); } + +export function getGettersFromClassDecl(definition: arkts.ClassDefinition): arkts.MethodDefinition[] { + return definition.body.filter( + (member) => + arkts.isMethodDefinition(member) && + arkts.hasModifierFlag(member, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_GETTER) + ) as arkts.MethodDefinition[]; +} diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index 463ae2730..a6906efad 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -56,6 +56,7 @@ export * from "../generated/peers/ETSNewClassInstanceExpression" export * from "../generated/peers/ObjectExpression" export * from "../generated/peers/Property" export * from "../generated/peers/BlockExpression" +export * from "../generated/peers/TSClassImplements" export * from "./types" export * from "./utilities/private" -- Gitee From 285a45c37a274fa7ddeb299055b8b6ab16ed3e7a Mon Sep 17 00:00:00 2001 From: l00913061 Date: Thu, 17 Apr 2025 15:19:45 +0800 Subject: [PATCH 052/123] update ut and SourceRange Signed-off-by: l00913061 Change-Id: I60dc0023a0ec169f69598463848c32b7553492cb --- arkui-plugins/jest-test.config.ts | 17 ++- arkui-plugins/package.json | 2 +- .../test/ut/common/annotation.test.ts | 4 +- .../instantiate-content.test.ts | 133 ----------------- .../instantiate-multi-content.test.ts | 140 ------------------ .../builder-lambda/instantiate.test.ts | 120 --------------- .../transform-struct-to-class.test.ts | 91 ------------ arkui-plugins/test/utils/artkts-config.ts | 3 +- arkui-plugins/test/utils/compile.ts | 11 +- arkui-plugins/test/utils/global.ts | 24 +-- arkui-plugins/test/utils/path-config.ts | 10 +- arkui-plugins/test/utils/plugin-driver.ts | 2 +- arkui-plugins/test/utils/plugin-tester.ts | 6 +- koala-wrapper/native/src/bridges.cc | 27 +++- koala-wrapper/native/src/generated/bridges.cc | 1 - koala-wrapper/src/Es2pandaNativeModule.ts | 16 ++ koala-wrapper/src/arkts-api/index.ts | 1 + .../src/arkts-api/peers/SourceRange.ts | 39 +++++ 18 files changed, 122 insertions(+), 525 deletions(-) delete mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts create mode 100644 koala-wrapper/src/arkts-api/peers/SourceRange.ts diff --git a/arkui-plugins/jest-test.config.ts b/arkui-plugins/jest-test.config.ts index 8295964bc..cb6202fc0 100644 --- a/arkui-plugins/jest-test.config.ts +++ b/arkui-plugins/jest-test.config.ts @@ -13,7 +13,16 @@ * limitations under the License. */ -export default { + +import * as path from 'path'; + +const rootPath = path.resolve(__dirname, '../../../'); + +const sdkPath = path.resolve(rootPath, './out/sdk/ohos-sdk/linux/ets/ets1.2'); + +const pandaSdkPath = path.resolve(sdkPath, './build-tools/ets2panda'); + +module.exports = { testEnvironment: 'node', transform: { '^.+\\.ts$': ['ts-jest', { isolatedModules: true }], @@ -23,4 +32,8 @@ export default { coverageDirectory: './test/report', collectCoverageFrom: ['common/**', 'memo-plugins/**', 'ui-plugins/**'], verbose: true, -}; + globals: { + SDK_PATH: sdkPath, + PANDA_SDK_PATH: pandaSdkPath + } +}; diff --git a/arkui-plugins/package.json b/arkui-plugins/package.json index 20078aeb0..1b839b9a6 100644 --- a/arkui-plugins/package.json +++ b/arkui-plugins/package.json @@ -10,7 +10,7 @@ "local:install": "chmod 777 ./npm_preinstall.sh && ./npm_preinstall.sh --init", "compile:plugins": "./node_modules/.bin/babel . --out-dir lib --extensions .ts", "compile:clean": "rm -rf lib", - "test": "jest --config ./jest-test.config.ts", + "test": "LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib jest --config ./jest-test.config.ts", "compile": "npm run compile:clean && npm run compile:plugins && cp -rf ./lib $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/" }, "devDependencies": { diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index 7091e7d52..81ef35c26 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -13,16 +13,16 @@ * limitations under the License. */ -import * as arkts from '@koalaui/libarkts'; import { PluginTestContext, PluginTester } from '../../utils/plugin-tester'; import { annotation } from '../../../common/arkts-utils'; +import * as arkts from '@koalaui/libarkts'; const pluginTester = new PluginTester('test arkts-utils'); function testAnnotation(this: PluginTestContext): void { const anno: arkts.AnnotationUsage = annotation('State'); expect(arkts.isAnnotationUsage(anno)).toBeTruthy(); - expect(anno.dumpSrc()).toBe('@State()'); + expect(anno.dumpSrc()).toBe('@State() '); } pluginTester.run( diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts deleted file mode 100644 index 0b4e71c2d..000000000 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-content.test.ts +++ /dev/null @@ -1,133 +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. - */ - -import * as path from 'path'; -import * as arkts from '@koalaui/libarkts'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { PluginContext, Plugins } from '../../../../common/plugin-context'; -import { ComponentTransformer } from '../../../../ui-plugins/component-transformer'; -import { BuilderLambdaTransformer } from '../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer'; - -const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda'); - -const instantiateTransform: Plugins = { - name: 'instantiate', - parsed(this: PluginContext) { - let program = this.getArkTSProgram(); - if (program) { - let script: arkts.EtsScript = program.astNode; - - const componentTransformer = new ComponentTransformer({ - arkui: '@koalaui.arkts-arkui.StructBase', - }); - script = componentTransformer.visitor(script) as arkts.EtsScript; - arkts.setAllParents(script); - return script; - } - }, - checked(this: PluginContext) { - let program = this.getArkTSProgram(); - if (program) { - let script: arkts.EtsScript = program.astNode; - - const builderLambdaTransformer = new BuilderLambdaTransformer(); - script = builderLambdaTransformer.visitor(script) as arkts.EtsScript; - arkts.setAllParents(script); - return script; - } - }, -}; - -const pluginTester = new PluginTester('test build-lambda transformer'); - -// Test single-content instantiateImpl transformation -function testSingleContent(this: PluginTestContext): void { - const script: arkts.EtsScript = this.script as arkts.EtsScript; - const expectedScript: string = ` -import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; - -import { Component as Component } from "@koalaui.arkts-arkui.Common"; - -import { Column as Column } from "@koalaui.arkts-arkui.Column"; - -import { Text as Text } from "@koalaui.arkts-arkui.Text"; - -abstract class ETSGLOBAL { - public static main() {} - - public static _$init$_() {} - - -} - -final class MyStateSample extends StructBase { - public build() { - Column.instantiateImpl(((instance: Column): Column => { - return instance; - }), ((): Column => { - return new Column(); - }), (() => { - Text.instantiateImpl(((instance: Text): Text => { - return instance; - }), ((): Text => { - return new Text(); - }), "Hello!"); - })); - } - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform $_instantiate for single component content', - [instantiateTransform], - { - 'checked:instantiate': [testSingleContent], - }, - { - stopAfter: 'checked', - buildConfig: { - ...mockBuildConfig(), - compileFiles: [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda', 'instantiate-content.ets'), - ], - moduleRootPath, - }, - }, - { - beforeEach: [ - () => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }, - ], - afterEach: [ - () => { - jest.spyOn(console, 'warn').mockRestore(); - }, - ], - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts deleted file mode 100644 index 34c169437..000000000 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate-multi-content.test.ts +++ /dev/null @@ -1,140 +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. - */ - -import * as path from 'path'; -import * as arkts from '@koalaui/libarkts'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { PluginContext, Plugins } from '../../../../common/plugin-context'; -import { ComponentTransformer } from '../../../../ui-plugins/component-transformer'; -import { BuilderLambdaTransformer } from '../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer'; - -const moduleRootPath: string = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda'); - -const instantiateTransform: Plugins = { - name: 'instantiate', - parsed(this: PluginContext) { - let program = this.getArkTSProgram(); - if (program) { - let script: arkts.EtsScript = program.astNode; - - const componentTransformer = new ComponentTransformer({ - arkui: '@koalaui.arkts-arkui.StructBase', - }); - script = componentTransformer.visitor(script) as arkts.EtsScript; - arkts.setAllParents(script); - return script; - } - }, - checked(this: PluginContext) { - let program = this.getArkTSProgram(); - if (program) { - let script: arkts.EtsScript = program.astNode; - - const builderLambdaTransformer = new BuilderLambdaTransformer(); - script = builderLambdaTransformer.visitor(script) as arkts.EtsScript; - arkts.setAllParents(script); - return script; - } - }, -}; - -const pluginTester = new PluginTester('test build-lambda transformer'); - -// Test multi-content instantiateImpl transformation -function testMultiContent(this: PluginTestContext): void { - const script: arkts.EtsScript = this.script as arkts.EtsScript; - const expectedScript: string = ` -import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; - -import { Component as Component } from "@koalaui.arkts-arkui.Common"; - -import { Column as Column } from "@koalaui.arkts-arkui.Column"; - -import { Text as Text } from "@koalaui.arkts-arkui.Text"; - -import { Button as Button } from "@koalaui.arkts-arkui.Button"; - -abstract class ETSGLOBAL { - public static main() {} - - public static _$init$_() {} - - -} - -final class MyStateSample extends StructBase { - public build() { - Column.instantiateImpl(((instance: Column): Column => { - return instance; - }), ((): Column => { - return new Column(); - }), (() => { - Text.instantiateImpl(((instance: Text): Text => { - return instance; - }), ((): Text => { - return new Text(); - }), "Hello!"); - Button.instantiateImpl(((instance: Button): Button => { - return instance; - }), ((): Button => { - return new Button(); - }), "click me"); - })); - } - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform $_instantiate for multiple component contents', - [instantiateTransform], - { - 'checked:instantiate': [testMultiContent], - }, - { - stopAfter: 'checked', - buildConfig: { - ...mockBuildConfig(), - compileFiles: [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda', 'instantiate-multi-content.ets'), - ], - moduleRootPath, - }, - }, - { - beforeEach: [ - () => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }, - ], - afterEach: [ - () => { - jest.spyOn(console, 'warn').mockRestore(); - }, - ], - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts deleted file mode 100644 index 3a54f332b..000000000 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/instantiate.test.ts +++ /dev/null @@ -1,120 +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. - */ - -import * as path from 'path'; -import * as arkts from '@koalaui/libarkts'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { PluginContext, Plugins } from '../../../../common/plugin-context'; -import { ComponentTransformer } from '../../../../ui-plugins/component-transformer'; -import { BuilderLambdaTransformer } from '../../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda', 'instantiate.ets')]; -buildConfig.moduleRootPath = path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'builder-lambda'); - -const instantiateTransform: Plugins = { - name: 'instantiate', - parsed(this: PluginContext) { - let program = this.getArkTSProgram(); - if (program) { - let script: arkts.EtsScript = program.astNode; - - const componentTransformer = new ComponentTransformer({ - arkui: '@koalaui.arkts-arkui.StructBase', - }); - script = componentTransformer.visitor(script) as arkts.EtsScript; - arkts.setAllParents(script); - return script; - } - }, - checked(this: PluginContext) { - let program = this.getArkTSProgram(); - if (program) { - let script: arkts.EtsScript = program.astNode; - - const builderLambdaTransformer = new BuilderLambdaTransformer(); - script = builderLambdaTransformer.visitor(script) as arkts.EtsScript; - - arkts.setAllParents(script); - return script; - } - }, -}; - -const pluginTester = new PluginTester('test build-lambda transformer', buildConfig); - -function testInstantiateImpl(this: PluginTestContext): void { - const script: arkts.EtsScript = this.script as arkts.EtsScript; - const expectedScript: string = ` -import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; - -import { Component as Component } from "@koalaui.arkts-arkui.Common"; - -import { Column as Column } from "@koalaui.arkts-arkui.Column"; - -abstract class ETSGLOBAL { - public static main() {} - - public static _$init$_() {} - - -} - -final class MyStateSample extends StructBase { - public build() { - Column.instantiateImpl(((instance: Column): Column => { - return instance; - }), ((): Column => { - return new Column(); - }), (() => {})); - } - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform $_instantiate for a single component', - [instantiateTransform], - { - 'checked:instantiate': [testInstantiateImpl], - }, - { - stopAfter: 'checked', - }, - { - beforeEach: [ - () => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }, - ], - afterEach: [ - () => { - jest.spyOn(console, 'warn').mockRestore(); - }, - ], - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts b/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts deleted file mode 100644 index 8cac48c6f..000000000 --- a/arkui-plugins/test/ut/ui-plugins/transform-struct-to-class.test.ts +++ /dev/null @@ -1,91 +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. - */ - -import * as path from 'path'; -import * as arkts from '@koalaui/libarkts'; -import { PluginTestContext, PluginTester } from '../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../utils/path-config'; -import { parseDumpSrc } from '../../utils/parse-string'; -import { PluginContext, Plugins } from '../../../common/plugin-context'; -import { ComponentTransformer } from '../../../ui-plugins/component-transformer'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, 'struct-to-class.ets')]; - -const componentTransform: Plugins = { - name: 'component', - parsed(this: PluginContext) { - let program = this.getArkTSProgram(); - if (program) { - let script: arkts.EtsScript = program.astNode; - - const componentTransformer = new ComponentTransformer({ - arkui: '@koalaui.arkts-arkui.StructBase', - }); - script = componentTransformer.visitor(script) as arkts.EtsScript; - arkts.setAllParents(script); - return script; - } - }, -}; - -const pluginTester = new PluginTester('test component transformer', buildConfig); - -function testComponentTransformer(this: PluginTestContext): void { - const script: arkts.EtsScript = this.script as arkts.EtsScript; - const expectedScript: string = ` -import { StructBase } from \"@koalaui.arkts-arkui.StructBase\"; - -import { Component as Component } from \"@koalaui.arkts-arkui.Common\"; - -final class MyStateSample extends StructBase { - - public build() {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - expect(parseDumpSrc(script.dumpSrc())).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform struct to class', - [componentTransform], - { - 'parsed:component': [testComponentTransformer], - }, - { - stopAfter: 'parsed', - }, - { - beforeEach: [ - () => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }, - ], - afterEach: [ - () => { - jest.spyOn(console, 'warn').mockRestore(); - }, - ], - } -); diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index db63f0e4b..f741bd104 100644 --- a/arkui-plugins/test/utils/artkts-config.ts +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -21,7 +21,6 @@ import { changeFileExtension, ensurePathExists, getFileName, - getPandaSDKPath, getRootPath, MOCK_ENTRY_DIR_PATH, MOCK_ENTRY_FILE_NAME, @@ -180,7 +179,7 @@ function mockBuildConfig(): BuildConfig { compileFiles: [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MOCK_ENTRY_FILE_NAME)], loaderOutPath: path.resolve(getRootPath(), MOCK_OUTPUT_DIR_PATH), cachePath: path.resolve(getRootPath(), MOCK_OUTPUT_CACHE_PATH), - pandaSdkPath: getPandaSDKPath(), + pandaSdkPath: global.PANDA_SDK_PATH, buildSdkPath: path.resolve(getRootPath(), MOCK_LOCAL_SDK_DIR_PATH), sourceRoots: [getRootPath()], moduleRootPath: path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH), diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index 7694eac9f..7ba64a49e 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -13,11 +13,10 @@ * limitations under the License. */ -import * as arkts from '@koalaui/libarkts'; -import { arktsGlobal } from '@koalaui/libarkts/build/lib/es2panda'; import { PluginDriver } from './plugin-driver'; import { PluginContext, PluginExecutor } from '../../common/plugin-context'; import { EtsglobalRemover } from '../../common/etsglobal-remover'; +import * as arkts from '@koalaui/libarkts'; function restartCompilerUptoState(state: arkts.Es2pandaContextState, restart: boolean): boolean { try { @@ -28,8 +27,8 @@ function restartCompilerUptoState(state: arkts.Es2pandaContextState, restart: bo if (restart) { const srcText = new EtsglobalRemover().visitor(ast).dumpSrc(); - arktsGlobal.es2panda._DestroyContext(arktsGlobal.context); - arktsGlobal.compilerContext = arkts.Context.createFromString(srcText); + arkts.arktsGlobal.es2panda._DestroyContext(arkts.arktsGlobal.context); + arkts.arktsGlobal.compilerContext = arkts.Context.createFromString(srcText); } arkts.proceedToState(state); @@ -54,7 +53,9 @@ function insertPlugin( if (plugin) { pluginContext.setArkTSAst(ast); - pluginContext.setArkTSProgram(arktsGlobal.compilerContext.program); + if (arkts.arktsGlobal.compilerContext) { + pluginContext.setArkTSProgram(arkts.arktsGlobal.compilerContext.program); + } plugin.handler.apply(pluginContext); } return true; diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index 4dc3d8511..df5e2794b 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -14,15 +14,14 @@ */ import * as fs from 'fs'; -import * as arkts from '@koalaui/libarkts'; -import { arktsGlobal } from '@koalaui/libarkts/build/lib/es2panda'; import { CompileFileInfo } from './artkts-config'; +import * as arkts from '@koalaui/libarkts'; function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { const config = [ '_', '--extension', - 'sts', + 'ets', '--arktsconfig', fileInfo.arktsConfigFile, '--output', @@ -34,7 +33,7 @@ function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { } config.push(fileInfo.filePath); - arktsGlobal.filePath = fileInfo.filePath; + arkts.arktsGlobal.filePath = fileInfo.filePath; resetConfig(config); const source: string = fs.readFileSync(fileInfo.filePath).toString(); @@ -43,47 +42,48 @@ function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { function resetContext(source: string): void { try { - arktsGlobal.context; + arkts.arktsGlobal.context; } catch (e) { // Do nothing } finally { const context: arkts.Context = arkts.Context.createFromString(source); - arktsGlobal.compilerContext = context; + arkts.arktsGlobal.compilerContext = context; } } function resetConfig(cmd: string[]): void { try { - arktsGlobal.config; + arkts.arktsGlobal.config; destroyConfig(); } catch (e) { // Do nothing } finally { const arkTSConfig: arkts.Config = arkts.Config.create(cmd); - arktsGlobal.config = arkTSConfig.peer; + arkts.arktsGlobal.config = arkTSConfig.peer; } } function destroyContext(): void { - arktsGlobal.es2panda._DestroyContext(arktsGlobal.context); + arkts.arktsGlobal.es2panda._DestroyContext(arkts.arktsGlobal.context); } function destroyConfig(): void { - arkts.destroyConfig(arktsGlobal.config); + arkts.destroyConfig(arkts.arktsGlobal.config); } function canProceedToState(state: arkts.Es2pandaContextState): boolean { const stateToSkip: arkts.Es2pandaContextState[] = [ arkts.Es2pandaContextState.ES2PANDA_STATE_SCOPE_INITED, + arkts.Es2pandaContextState.ES2PANDA_STATE_BOUND, + arkts.Es2pandaContextState.ES2PANDA_STATE_LOWERED, arkts.Es2pandaContextState.ES2PANDA_STATE_ASM_GENERATED, arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR, ]; - if (state in stateToSkip) { return false; } - const currState = arktsGlobal.es2panda._ContextState(arktsGlobal.context); + const currState = arkts.arktsGlobal.es2panda._ContextState(arkts.arktsGlobal.context); return currState < state; } diff --git a/arkui-plugins/test/utils/path-config.ts b/arkui-plugins/test/utils/path-config.ts index e322f28c8..608df6dee 100644 --- a/arkui-plugins/test/utils/path-config.ts +++ b/arkui-plugins/test/utils/path-config.ts @@ -36,14 +36,6 @@ function getRootPath(): string { return path.resolve(__dirname, '..'); } -function getPandaSDKPath(): string { - if (!process.env.ETS2PANDA_PATH) { - throw new Error('Environment Error: ets2panda path is not defined'); - } - - return path.resolve(process.env.ETS2PANDA_PATH); -} - function changeFileExtension(file: string, targetExt: string, originExt = ''): string { const currentExt: string = originExt.length === 0 ? path.extname(file) : originExt; const fileWithoutExt: string = file.substring(0, file.lastIndexOf(currentExt)); @@ -69,4 +61,4 @@ function ensurePathExists(filePath: string): void { } } -export { getRootPath, getPandaSDKPath, changeFileExtension, getFileName, ensurePathExists }; +export { getRootPath, changeFileExtension, getFileName, ensurePathExists }; diff --git a/arkui-plugins/test/utils/plugin-driver.ts b/arkui-plugins/test/utils/plugin-driver.ts index 74e60a414..46ce7f562 100644 --- a/arkui-plugins/test/utils/plugin-driver.ts +++ b/arkui-plugins/test/utils/plugin-driver.ts @@ -13,9 +13,9 @@ * limitations under the License. */ -import * as arkts from '@koalaui/libarkts'; import { isNumber } from './safe-types'; import { Plugins, PluginContext, PluginHandler, PluginState, PluginExecutor } from '../../common/plugin-context'; +import * as arkts from '@koalaui/libarkts'; export interface PluginDriver { initPlugins(plugins: Plugins[]): void; diff --git a/arkui-plugins/test/utils/plugin-tester.ts b/arkui-plugins/test/utils/plugin-tester.ts index c6b36d33d..e68711063 100644 --- a/arkui-plugins/test/utils/plugin-tester.ts +++ b/arkui-plugins/test/utils/plugin-tester.ts @@ -13,13 +13,13 @@ * limitations under the License. */ -import * as arkts from '@koalaui/libarkts'; import { ArktsConfigBuilder, BuildConfig, CompileFileInfo, MockArktsConfigBuilder, ModuleInfo } from './artkts-config'; import { MockPluginDriver, PluginDriver, stateName } from './plugin-driver'; import { isNumber } from './safe-types'; import { canProceedToState, initGlobal } from './global'; import { insertPlugin, restartCompilerUptoState } from './compile'; import { PluginExecutor, Plugins, PluginState } from '../../common/plugin-context'; +import * as arkts from '@koalaui/libarkts'; type TestParams = Parameters; @@ -77,10 +77,6 @@ class PluginTester { return; } if (canProceedToState(index)) { - // TODO: this is a bug from compiler. - if (index > arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) { - restartCompilerUptoState(index, true); - } arkts.proceedToState(index); } if (plugin) { diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index 3649b2858..5f7b6cbfd 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -386,4 +386,29 @@ KNativePointer impl_ETSParserGetGlobalProgramAbsName(KNativePointer contextPtr) auto result = GetImpl()->ETSParserGetGlobalProgramAbsName(context); return new std::string(result); } -KOALA_INTEROP_1(ETSParserGetGlobalProgramAbsName, KNativePointer, KNativePointer) \ No newline at end of file +KOALA_INTEROP_1(ETSParserGetGlobalProgramAbsName, KNativePointer, KNativePointer) + +KNativePointer impl_AstNodeRangeConst(KNativePointer context, KNativePointer node) +{ + const auto _context = reinterpret_cast(context); + const auto _node = reinterpret_cast(node); + auto result = GetImpl()->AstNodeRangeConst(_context, _node); + return (void*)result; +} +KOALA_INTEROP_2(AstNodeRangeConst, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_SourceRangeStart(KNativePointer context, KNativePointer range) { + const auto _context = reinterpret_cast(context); + const auto _range = reinterpret_cast(range); + auto result = GetImpl()->SourceRangeStart(_context, _range); + return result; +} +KOALA_INTEROP_2(SourceRangeStart, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_SourceRangeEnd(KNativePointer context, KNativePointer range) { + const auto _context = reinterpret_cast(context); + const auto _range = reinterpret_cast(range); + auto result = GetImpl()->SourceRangeEnd(_context, _range); + return result; +} +KOALA_INTEROP_2(SourceRangeEnd, KNativePointer, KNativePointer, KNativePointer) diff --git a/koala-wrapper/native/src/generated/bridges.cc b/koala-wrapper/native/src/generated/bridges.cc index f1ca609eb..f3dd3bdb4 100644 --- a/koala-wrapper/native/src/generated/bridges.cc +++ b/koala-wrapper/native/src/generated/bridges.cc @@ -11761,4 +11761,3 @@ KNativePointer impl_CreateFunctionDecl(KNativePointer context, KStringPtr& name, return result; } KOALA_INTEROP_3(CreateFunctionDecl, KNativePointer, KNativePointer, KStringPtr, KNativePointer); - diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 8d2fdd7bb..e95021c35 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -802,6 +802,22 @@ export class Es2pandaNativeModule { _ImportSpecifierSetRemovable(context: KNativePointer, instance: KNativePointer): void { throw new Error('Not implemented'); } + + _AstNodeRangeConst(context: KNativePointer, node: KNativePointer): KNativePointer { + throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + } + + _SourceRangeStart(context: KNativePointer, range: KNativePointer): KNativePointer { + throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + } + + _SourceRangeEnd(context: KNativePointer, range: KNativePointer): KNativePointer { + throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + } + + _CreateSourceRange(context: KNativePointer, start: KNativePointer, end: KNativePointer): KNativePointer { + throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + } } export function initEs2panda(): Es2pandaNativeModule { diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index 463ae2730..94b127f96 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -72,6 +72,7 @@ export * from "./peers/Context" export * from "./peers/Program" export * from "./peers/ImportPathManager" export * from "./peers/SourcePosition" +export * from "./peers/SourceRange" export * from "./to-be-generated/MemberExpression" export * from "./static/globalUtils" export { global as arktsGlobal } from "./static/global"; diff --git a/koala-wrapper/src/arkts-api/peers/SourceRange.ts b/koala-wrapper/src/arkts-api/peers/SourceRange.ts new file mode 100644 index 000000000..b63557cd1 --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/SourceRange.ts @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from "./ArktsObject" +import { global } from "../static/global" +import { KNativePointer } from "@koalaui/interop" +import { SourcePosition } from "./SourcePosition"; + +export class SourceRange extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer) + } + + static create(start: SourcePosition, end: SourcePosition): SourceRange { + return new SourceRange( + global.es2panda._CreateSourceRange(global.context, start.peer, end.peer) + ); + } + + start(): SourcePosition { + return new SourcePosition(global.es2panda._SourceRangeStart(global.context, this.peer)); + } + + end(): SourcePosition { + return new SourcePosition(global.es2panda._SourceRangeEnd(global.context, this.peer)); + } +} \ No newline at end of file -- Gitee From 03779594e222bc39fdcfa8ce1da39370acd854a2 Mon Sep 17 00:00:00 2001 From: s00912778 Date: Thu, 17 Apr 2025 16:38:21 +0800 Subject: [PATCH 053/123] change invalid undefined creation Signed-off-by: s00912778 Change-Id: I02fbfa2262641df6394c343733998cb35416bad0 --- .../ui-plugins/property-translators/localstoragelink.ts | 2 +- .../ui-plugins/property-translators/localstorageprop.ts | 4 ++-- arkui-plugins/ui-plugins/property-translators/prop.ts | 2 +- .../ui-plugins/property-translators/regularProperty.ts | 2 +- arkui-plugins/ui-plugins/property-translators/state.ts | 2 +- arkui-plugins/ui-plugins/property-translators/storageProp.ts | 2 +- arkui-plugins/ui-plugins/property-translators/storagelink.ts | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts index 9d43765eb..a050e9852 100755 --- a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts @@ -89,7 +89,7 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In false ), arkts.factory.createStringLiteral(localStorageLinkValueStr), - this.property.value ?? arkts.factory.createIdentifier('undefined'), + this.property.value ?? arkts.factory.createUndefinedLiteral(), ] ); diff --git a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts index 965e5fb2b..d20d982cd 100644 --- a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts @@ -91,7 +91,7 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In [ insideMember, arkts.factory.createStringLiteral(localStorageporpValueStr), - this.property.value ?? arkts.factory.createIdentifier('undefined'), + this.property.value ?? arkts.factory.createUndefinedLiteral(), ] ); const call = arkts.factory.createCallExpression( @@ -139,7 +139,7 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In false ), arkts.factory.createStringLiteral(localStorageporpValueStr), - this.property.value ?? arkts.factory.createIdentifier('undefined'), + this.property.value ?? arkts.factory.createUndefinedLiteral(), ] ), arkts.factory.createIdentifier('value'), diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts index 7745be3e6..b8bb3d991 100644 --- a/arkui-plugins/ui-plugins/property-translators/prop.ts +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -100,7 +100,7 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon arkts.factory.createIdentifier('initializers'), originalName ), - this.property.value ?? arkts.factory.createIdentifier('undefined'), + this.property.value ?? arkts.factory.createUndefinedLiteral(), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ); const args: arkts.Expression[] = [ diff --git a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts index 795ff6b46..630417d1c 100644 --- a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts +++ b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts @@ -92,7 +92,7 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini arkts.factory.createIdentifier('initializers'), originalName ), - this.property.value ?? arkts.factory.createIdentifier('undefined'), + this.property.value ?? arkts.factory.createUndefinedLiteral(), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts index 5a528df4c..667fabac7 100644 --- a/arkui-plugins/ui-plugins/property-translators/state.ts +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -96,7 +96,7 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo arkts.factory.createIdentifier('initializers'), originalName ), - this.property.value ?? arkts.factory.createIdentifier('undefined'), + this.property.value ?? arkts.factory.createUndefinedLiteral(), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ); const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), binaryItem]; diff --git a/arkui-plugins/ui-plugins/property-translators/storageProp.ts b/arkui-plugins/ui-plugins/property-translators/storageProp.ts index cea565a8b..2693f749d 100644 --- a/arkui-plugins/ui-plugins/property-translators/storageProp.ts +++ b/arkui-plugins/ui-plugins/property-translators/storageProp.ts @@ -89,7 +89,7 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial const args: arkts.Expression[] = [ arkts.factory.createStringLiteral(storagePropValueStr), arkts.factory.create1StringLiteral(originalName), - this.property.value ?? arkts.factory.createIdentifier('undefined'), + this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; judgeIfAddWatchFunc(args, this.property); diff --git a/arkui-plugins/ui-plugins/property-translators/storagelink.ts b/arkui-plugins/ui-plugins/property-translators/storagelink.ts index bde1a2adf..efd83e9d6 100644 --- a/arkui-plugins/ui-plugins/property-translators/storagelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/storagelink.ts @@ -89,7 +89,7 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial const args: arkts.Expression[] = [ arkts.factory.createStringLiteral(storageLinkValueStr), arkts.factory.create1StringLiteral(originalName), - this.property.value ?? arkts.factory.createIdentifier('undefined'), + this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; judgeIfAddWatchFunc(args, this.property); -- Gitee From b45501a639f9130ee1e9ae484ee1a5e7b870a3f2 Mon Sep 17 00:00:00 2001 From: s00912778 Date: Thu, 17 Apr 2025 16:57:21 +0800 Subject: [PATCH 054/123] create constructor to new class Signed-off-by: s00912778 Change-Id: I3df733bdb541939adb7ce50907bdd37f3ef5b617 --- .../ui-plugins/entry-translators/factory.ts | 60 +++++++++++++------ 1 file changed, 43 insertions(+), 17 deletions(-) diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index d1f0e33d4..e2d04b3d2 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -116,6 +116,29 @@ export class factory { return def; } + static generateConstructor(): arkts.MethodDefinition { + const key: arkts.Identifier = arkts.factory.createIdentifier('constructor'); + const block = arkts.factory.createBlock([]); + const entryScript = arkts.factory + .createScriptFunction( + block, + arkts.FunctionSignature.createFunctionSignature(undefined, [], undefined, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR | + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_IMPLICIT_SUPER_CALL_NEEDED, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR + ) + .setIdent(key); + const def = arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, + key, + arkts.factory.createFunctionExpression(entryScript), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + false + ); + return def; + } + /** * create `entry = (): void => { (); }` class property for the entry wrapper class, * which calls the struct within the arrow function. @@ -166,23 +189,26 @@ export class factory { * @param name class/struct name that has `@Entry` annotation. */ static generateEntryWrapper(name: string): arkts.ClassDeclaration { - const definition: arkts.ClassDefinition = arkts.factory.createClassDefinition( - arkts.factory.createIdentifier(EntryWrapperNames.WRAPPER_CLASS_NAME), - undefined, - undefined, - [], - undefined, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME) - ) - ), - [factory.generateEntryFunction(name)], - arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_CLASS_DECL | - arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_DECLARATION | - arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_ID_REQUIRED, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE - ); + const ctor = factory.generateConstructor(); + const definition: arkts.ClassDefinition = arkts.factory + .createClassDefinition( + arkts.factory.createIdentifier(EntryWrapperNames.WRAPPER_CLASS_NAME), + undefined, + undefined, + [], + undefined, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME) + ) + ), + [factory.generateEntryFunction(name), ctor], + arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_CLASS_DECL | + arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_DECLARATION | + arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_ID_REQUIRED, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ) + .setCtor(ctor as any); const newClass = arkts.factory.createClassDeclaration(definition); newClass.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE; return newClass; -- Gitee From b2880bac6498e04c4d67cbb2bf7a964640972abf Mon Sep 17 00:00:00 2001 From: y00896775 Date: Thu, 17 Apr 2025 21:26:48 +0800 Subject: [PATCH 055/123] modify invalid use of undefined Signed-off-by: y00896775 Change-Id: I86f945097d7bc04551e0d99951a91f22be0d2d12 --- arkui-plugins/ui-plugins/property-translators/factory.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts index f69fcda99..c1f610a4b 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -233,7 +233,7 @@ export class factory { } /* - * create `this.addProvidedVar(, "uuuutttt", initializers?.uuuutttt ?? 1.5, false, watch)`. + * create `this.addProvidedVar(, , initializers?. ?? , , watchFunc)`. */ static generateAddProvideVarCall( originalName: string, @@ -249,7 +249,7 @@ export class factory { arkts.factory.createIdentifier('initializers'), originalName ), - property.value ?? arkts.factory.createIdentifier('undefined'), + property.value ?? arkts.factory.createUndefinedLiteral(), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ), arkts.factory.createBooleanLiteral(allowOverride), @@ -269,7 +269,7 @@ export class factory { } /* - * create `this.initConsume("uuuutttt", "uuuutttt", watchFunc)`. + * create `this.initConsume(, , watchFunc)`. */ static generateInitConsumeCall( originalName: string, -- Gitee From de944ae302d52fbaf2af8b1c5b7c53f14150925a Mon Sep 17 00:00:00 2001 From: zenghang Date: Thu, 10 Apr 2025 22:35:21 +0800 Subject: [PATCH 056/123] adjust to oh_modules compile Issue: IC072W Signed-off-by: zenghang Change-Id: Idf12853eab729a9cbb4a2f2741510b61821eee62 --- compiler/main.js | 35 +++++++++++++++++-- compiler/src/ets_checker.ts | 11 +++--- .../ark_compiler/module/module_mode.ts | 15 ++++---- .../ark_compiler/module/module_source_file.ts | 2 +- compiler/src/process_arkts_evolution.ts | 33 ++++++++--------- .../common/process_arkts_evolution.test.ts | 2 +- 6 files changed, 64 insertions(+), 34 deletions(-) diff --git a/compiler/main.js b/compiler/main.js index 2f6fb867f..a8d7bc0a2 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -149,6 +149,7 @@ function loadEntryObj(projectConfig) { initProjectConfig(projectConfig); loadMemoryTrackingConfig(projectConfig); loadBuildJson(); + initMixCompileHar(projectConfig); if (process.env.aceManifestPath && aceCompileMode === 'page') { setEntryFile(projectConfig); setFaTestRunnerFile(projectConfig); @@ -159,7 +160,9 @@ function loadEntryObj(projectConfig) { setStageTestRunnerFile(projectConfig); loadNavigationConfig(aceBuildJson); } - + if (projectConfig.mixCompile) { + return; + } if (staticPreviewPage) { projectConfig.entryObj['./' + staticPreviewPage] = projectConfig.projectPath + path.sep + staticPreviewPage + '.ets?entry'; @@ -264,7 +267,23 @@ function buildManifest(manifest, aceConfigPath) { } function getPackageJsonEntryPath() { - const rootPackageJsonPath = path.resolve(projectConfig.projectPath, '../../../' + projectConfig.packageJson); + /** + * adapt to oh_modules compile + * origin local module => project/library/src/main/ets + * oh_module => project/library/src/main + * bcs some oh_module don't contain ets dir + */ + + const candidatePaths = [ + path.resolve(projectConfig.projectPath, '../../../', projectConfig.packageJson), + path.resolve(projectConfig.projectPath, '../../', projectConfig.packageJson), + ]; + + const rootPackageJsonPath = + candidatePaths.find(fs.existsSync) ?? + (() => { + throw new Error('package.json not found in ../../../ or ../../'); + })(); if (fs.existsSync(rootPackageJsonPath)) { let rootPackageJsonContent; try { @@ -393,6 +412,9 @@ function setIntentEntryPages(projectConfig) { } function setAbilityPages(projectConfig) { + if (projectConfig.isRemoteModule) { + return; + } let abilityPages = []; if (projectConfig.aceModuleJsonPath && fs.existsSync(projectConfig.aceModuleJsonPath)) { const moduleJson = JSON.parse(fs.readFileSync(projectConfig.aceModuleJsonPath).toString()); @@ -1145,6 +1167,15 @@ function initMain() { abilityConfig.abilityType = process.env.abilityType || 'page'; } +function initMixCompileHar(projectConfig) { + projectConfig.isRemoteModule = process.env.isRemoteModule === 'true'; + projectConfig.mixCompile = process.env.mixCompile === 'true'; + if (projectConfig.isRemoteModule && projectConfig.mixCompile) { + projectConfig.compileHar = true; + getPackageJsonEntryPath(); + } +} + exports.globalProgram = globalProgram; exports.projectConfig = projectConfig; exports.loadEntryObj = loadEntryObj; diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index 87e0b0ca8..e533e46d2 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -561,14 +561,13 @@ export function serviceChecker(rootFileNames: string[], newLogger: Object = null MemoryMonitor.stopRecordStage(runArkTSLinterRecordInfo); stopTimeStatisticsLocation(compilationTime ? compilationTime.runArkTSLinterTime : undefined); - if (process.env.watchMode !== 'true') { + if (process.env.watchMode !== 'true' && !projectConfig.isRemoteModule) { const processBuildHaprrecordInfo = MemoryMonitor.recordStage(MemoryDefine.PROCESS_BUILD_HAP); processBuildHap(cacheFile, rootFileNames, compilationTime, rollupShareObject); MemoryMonitor.stopRecordStage(processBuildHaprrecordInfo); } if (rollupShareObject?.projectConfig.mixCompile) { generateDeclarationFileForSTS(rootFileNames); - processInteropUI(projectConfig.dependentModuleMap?.get(projectConfig.moduleName)?.declgenV2OutPath); } if (globalProgram.program && (process.env.watchMode !== 'true' && !projectConfig.isPreview && @@ -1851,7 +1850,6 @@ export function generateDeclarationFileForSTS(rootFileNames: string[]) { return toUnixPath(path); }); - const regex = new RegExp(projectConfig.packageDir); const uniqueFiles = Array.from(new Set([ ...unixRootFileNames, /** @@ -1859,14 +1857,14 @@ export function generateDeclarationFileForSTS(rootFileNames: string[]) { * otherwise an error will be reported during the tsc compilation of declgen */ ...readDeaclareFiles() - ])).filter(file => !regex.test(file)); + ])); const config: RunnerParms = { inputDirs: [], inputFiles: uniqueFiles, - outDir: projectConfig.dependentModuleMap.get(projectConfig.moduleName).declgenV2OutPath, + outDir: projectConfig.dependentModuleMap.get(projectConfig.entryPackageName).declgenV2OutPath, // use package name as folder name - rootDir: projectConfig.moduleRootPath, + rootDir: projectConfig.modulePath, customResolveModuleNames: resolveModuleNames, customCompilerOptions: compilerOptions, includePaths: [projectConfig.modulePath] @@ -1876,4 +1874,5 @@ export function generateDeclarationFileForSTS(rootFileNames: string[]) { } fs.mkdirSync(config.outDir, { recursive: true }); generateInteropDecls(config); + processInteropUI(projectConfig.dependentModuleMap?.get(projectConfig.entryPackageName)?.declgenV2OutPath); } \ No newline at end of file diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts index 24fbbed14..01b5c1635 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_mode.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -252,7 +252,7 @@ export class ModuleMode extends CommonMode { } const isArkTSEvolution: boolean = metaInfo.language === ARKTS_1_2; const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(metaInfo.moduleName), metaInfo.moduleName) : metaInfo.pkgPath; + path.join(getDeclgenBridgeCodePath(metaInfo.pkgName), metaInfo.moduleName) : metaInfo.pkgPath; const pkgParams = { pkgName: metaInfo.pkgName, pkgPath, @@ -313,22 +313,21 @@ export class ModuleMode extends CommonMode { const eventPrepareForCompilation = createAndStartEvent(parentEvent, 'preparation for compilation'); this.collectModuleFileList(rollupObject, rollupObject.getModuleIds()); if (rollupObject.share.projectConfig.dependentModuleMap) { - this.writeDeclFilesConfigJson(rollupObject.share.projectConfig.entryModuleName); + this.writeDeclFilesConfigJson(rollupObject.share.projectConfig.entryPackageName); } this.removeCacheInfo(rollupObject); stopEvent(eventPrepareForCompilation); } // Write the declaration file information of the 1.1 module file to the disk of the corresponding module - writeDeclFilesConfigJson(moduleName: string): void { + writeDeclFilesConfigJson(pkgName: string): void { if (!arkTSModuleMap.size) { return; } - const arkTSEvolutionModuleInfo: ArkTSEvolutionModule = arkTSModuleMap.get(moduleName); + const arkTSEvolutionModuleInfo: ArkTSEvolutionModule = arkTSModuleMap.get(pkgName); const declFilesConfigFile: string = toUnixPath(arkTSEvolutionModuleInfo.declFilesPath); - const packageName: string = arkTSEvolutionModuleInfo.packageName; mkdirsSync(path.dirname(declFilesConfigFile)); - fs.writeFileSync(declFilesConfigFile, JSON.stringify(pkgDeclFilesConfig[packageName], null, 2), 'utf-8'); + fs.writeFileSync(declFilesConfigFile, JSON.stringify(pkgDeclFilesConfig[pkgName], null, 2), 'utf-8'); } collectModuleFileList(module: Object, fileList: IterableIterator): void { @@ -528,7 +527,7 @@ export class ModuleMode extends CommonMode { packageName = metaInfo.pkgName; const isArkTSEvolution: boolean = metaInfo.language === ARKTS_1_2; const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(metaInfo.moduleName), metaInfo.moduleName) : metaInfo.pkgPath; + path.join(getDeclgenBridgeCodePath(packageName), metaInfo.moduleName) : metaInfo.pkgPath; const pkgParams = { pkgName: packageName, pkgPath, @@ -536,7 +535,7 @@ export class ModuleMode extends CommonMode { }; recordName = getNormalizedOhmUrlByFilepath(filePath, this.projectConfig, this.logger, pkgParams, undefined); if (!isArkTSEvolution) { - addDeclFilesConfig(originalFilePath, metaInfo.moduleName, this.projectConfig, this.logger, pkgPath, packageName); + addDeclFilesConfig(originalFilePath, this.projectConfig, this.logger, pkgPath, packageName); } } else { recordName = getOhmUrlByFilepath(filePath, this.projectConfig, this.logger, moduleName); diff --git a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts index 2da04973d..fd3cd73f3 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts @@ -510,7 +510,7 @@ export class ModuleSourceFile { private static spliceNormalizedOhmurl(moduleInfo: Object, filePath: string, importerFile?: string): string { const isArkTSEvolution: boolean = moduleInfo.meta.language === ARKTS_1_2; const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(moduleInfo.meta.moduleName), moduleInfo.meta.moduleName) : moduleInfo.meta.pkgPath; + path.join(getDeclgenBridgeCodePath(moduleInfo.meta.pkgName), moduleInfo.meta.moduleName) : moduleInfo.meta.pkgPath; const pkgParams = { pkgName: moduleInfo.meta.pkgName, pkgPath, diff --git a/compiler/src/process_arkts_evolution.ts b/compiler/src/process_arkts_evolution.ts index 55cdc5556..79916f7cd 100644 --- a/compiler/src/process_arkts_evolution.ts +++ b/compiler/src/process_arkts_evolution.ts @@ -69,10 +69,10 @@ export let arkTSEvolutionModuleMap: Map = new Map( export let arkTSHybridModuleMap: Map = new Map(); -export function addDeclFilesConfig(filePath: string, moduleName: string, projectConfig: Object, - logger: Object, pkgPath: string, pkgName: string): void { +export function addDeclFilesConfig(filePath: string, projectConfig: Object, logger: Object, + pkgPath: string, pkgName: string): void { const { projectFilePath, pkgInfo } = getPkgInfo(filePath, projectConfig, logger, pkgPath, pkgName); - const declgenV2OutPath: string = getDeclgenV2OutPath(moduleName); + const declgenV2OutPath: string = getDeclgenV2OutPath(pkgName); if (!declgenV2OutPath) { return; } @@ -95,9 +95,10 @@ export function addDeclFilesConfig(filePath: string, moduleName: string, project export function getArkTSEvoDeclFilePath(resolvedFileInfo: ResolvedFileInfo): string { const { moduleRequest, resolvedFileName } = resolvedFileInfo; let arktsEvoDeclFilePath: string = moduleRequest; - for (const [moduleName, arkTSEvolutionModuleInfo] of arkTSEvolutionModuleMap) { + for (const [pkgName, arkTSEvolutionModuleInfo] of arkTSEvolutionModuleMap) { const declgenV1OutPath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenV1OutPath); const modulePath: string = toUnixPath(arkTSEvolutionModuleInfo.modulePath); + const moduleName: string = arkTSEvolutionModuleInfo.moduleName; const declgenBridgeCodePath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenBridgeCodePath); if (resolvedFileName && resolvedFileName.startsWith(modulePath + '/') && !resolvedFileName.startsWith(declgenBridgeCodePath + '/')) { @@ -130,23 +131,23 @@ export function collectArkTSEvolutionModuleInfo(share: Object): void { // dependentModuleMap Contents eg. // 1.2 hap -> 1.1 har: It contains the information of 1.1 har // 1.1 hap -> 1.2 har -> 1.1 har : There is information about 3 modules. - for (const [moduleName, dependentModuleInfo] of share.projectConfig.dependentModuleMap) { + for (const [pkgName, dependentModuleInfo] of share.projectConfig.dependentModuleMap) { if (dependentModuleInfo.language === ARKTS_1_2) { if (dependentModuleInfo.declgenV1OutPath && dependentModuleInfo.declgenBridgeCodePath) { - arkTSEvolutionModuleMap.set(moduleName, dependentModuleInfo); + arkTSEvolutionModuleMap.set(pkgName, dependentModuleInfo); } else { share.throwArkTsCompilerError(red, 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + - `Error Message: Failed to collect arkTs evolution module "${moduleName}" info from rollup.`, reset); + `Error Message: Failed to collect arkTs evolution module "${pkgName}" info from rollup.`, reset); } } else if (dependentModuleInfo.language === ARKTS_1_1) { if (dependentModuleInfo.declgenV2OutPath && dependentModuleInfo.declFilesPath) { - arkTSModuleMap.set(moduleName, dependentModuleInfo); + arkTSModuleMap.set(pkgName, dependentModuleInfo); } else { share.throwArkTsCompilerError(red, 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + - `Error Message: Failed to collect arkTs evolution module "${moduleName}" info from rollup.`, reset); + `Error Message: Failed to collect arkTs evolution module "${pkgName}" info from rollup.`, reset); } } else { - arkTSHybridModuleMap.set(moduleName, dependentModuleInfo); + arkTSHybridModuleMap.set(pkgName, dependentModuleInfo); } } } @@ -168,17 +169,17 @@ export async function writeBridgeCodeFileSyncByNode(node: ts.SourceFile, moduleI fs.writeFileSync(moduleId, writer.getText()); } -export function getDeclgenBridgeCodePath(moduleName: string): string { - if (arkTSEvolutionModuleMap.size && arkTSEvolutionModuleMap.get(moduleName)) { - const arkTSEvolutionModuleInfo: ArkTSEvolutionModule = arkTSEvolutionModuleMap.get(moduleName); +export function getDeclgenBridgeCodePath(pkgName: string): string { + if (arkTSEvolutionModuleMap.size && arkTSEvolutionModuleMap.get(pkgName)) { + const arkTSEvolutionModuleInfo: ArkTSEvolutionModule = arkTSEvolutionModuleMap.get(pkgName); return arkTSEvolutionModuleInfo.declgenBridgeCodePath; } return ''; } -function getDeclgenV2OutPath(moduleName: string): string { - if (arkTSModuleMap.size && arkTSModuleMap.get(moduleName)) { - const arkTsModuleInfo: ArkTSEvolutionModule = arkTSModuleMap.get(moduleName); +function getDeclgenV2OutPath(pkgName: string): string { + if (arkTSModuleMap.size && arkTSModuleMap.get(pkgName)) { + const arkTsModuleInfo: ArkTSEvolutionModule = arkTSModuleMap.get(pkgName); return arkTsModuleInfo.declgenV2OutPath; } return ''; diff --git a/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts b/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts index cde7e4eae..42a538d80 100644 --- a/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts +++ b/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts @@ -106,7 +106,7 @@ mocha.describe('process arkts evolution tests', function () { pkgName: 'har', declgenV2OutPath: HAR_DECLGENV2OUTPATH }) - addDeclFilesConfig(filePath, 'har', projectConfig, undefined, '/har', 'har'); + addDeclFilesConfig(filePath, projectConfig, undefined, '/har', 'har'); const expectDeclPath: string = `${HAR_DECLGENV2OUTPATH}/Index.d.ets`; const expectOhmUrl: string = `@normalized:N&entry&${BUNDLE_NAME_DEFAULT}&har/Index&1.0.0`; expect(pkgDeclFilesConfig['har'].files.length !== 0).to.be.true; -- Gitee From 4799cd6f5a08ea4e4f4a3479ef0b76e4345a1f79 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Fri, 18 Apr 2025 10:27:49 +0800 Subject: [PATCH 057/123] modify regular property Signed-off-by: y00896775 Change-Id: I64690e47416e6c7502fb73660af2c42e7463c1a8 --- .../ui-plugins/property-translators/regularProperty.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts index 630417d1c..d89b471e7 100644 --- a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts +++ b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts @@ -50,10 +50,10 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini ); const thisValue: arkts.Expression = generateThisBacking(newName, false, false); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - arkts.factory.createBinaryExpression( + arkts.factory.createAssignmentExpression( thisValue, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, arkts.factory.createIdentifier('value'), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_EQUAL ) ); const getter: arkts.MethodDefinition = this.translateGetter( -- Gitee From 9b838aaf8a7745dd48ec95fb9ac28682587cbec7 Mon Sep 17 00:00:00 2001 From: l00913061 Date: Fri, 18 Apr 2025 10:33:57 +0800 Subject: [PATCH 058/123] interopcode Signed-off-by: l00913061 Change-Id: Ib428a5447a0ea5c6025c54da88a2f83296cf0cb6 --- arkui-plugins/common/debug.ts | 2 +- arkui-plugins/common/predefines.ts | 34 ++- arkui-plugins/common/program-visitor.ts | 4 +- arkui-plugins/jest-test.config.ts | 2 +- .../test/demo/localtest/entry/new.ets | 69 +++--- .../ui-plugins/checked-transformer.ts | 20 -- arkui-plugins/ui-plugins/interop.ts | 229 +++++++++++++----- .../ui-plugins/legacy-transformer.ts | 14 +- arkui-plugins/ui-plugins/router.ts | 58 ----- .../ui-plugins/struct-translators/utils.ts | 15 -- arkui-plugins/ui-plugins/utils.ts | 5 - koala-wrapper/src/Es2pandaNativeModule.ts | 8 +- .../src/arkts-api/peers/SourceRange.ts | 11 +- 13 files changed, 250 insertions(+), 221 deletions(-) delete mode 100644 arkui-plugins/ui-plugins/router.ts diff --git a/arkui-plugins/common/debug.ts b/arkui-plugins/common/debug.ts index 9b5eca654..f39940e8f 100644 --- a/arkui-plugins/common/debug.ts +++ b/arkui-plugins/common/debug.ts @@ -16,7 +16,7 @@ import * as fs from 'fs'; import * as path from 'path'; import * as arkts from '@koalaui/libarkts'; -const isDebugLog: boolean = true; +const isDebugLog: boolean = false; const isDebugDump: boolean = false; const isPerformance: boolean = false; arkts.Performance.getInstance().skip(!isPerformance); diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 7e705f511..92270b16a 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -89,10 +89,30 @@ export const OUTPUT_DEPENDENCY_MAP: Map = new Map void, update: ((elmtId: number, instance: ESObject) => void)) { + +} + @Component struct MyStateSample { - @State stateVar: string = "state var"; - message: string = `click to change state variable, add **`; + @State stateVar: string = "Parent"; + message: string = "var"; changeValue() { - this.stateVar+="**" + this.stateVar+="~"; } build() { - Column() { - Button("clean variable").onClick((e: ClickEvent) => { this.stateVar = "state var" }) - Text("Hello World").fontSize(20) - Button(this.message).backgroundColor("#FFFF00FF") + Column(undefined) { + Button("ParentChange").backgroundColor("#FFFF00FF") .onClick((e: ClickEvent) => { hilog.info(0x0000, 'testTag', 'On Click'); - this.changeValue() + this.changeValue(); }) Text(this.stateVar).fontSize(20) - Child({linkVar: this.stateVar, propVar: this.stateVar}) - }.margin(10) + ChildLink({stateVar: this.stateVar, stateVar1: this.stateVar, stateVar2: ""} as __Options_ChildLink) + } } } @Component -struct Child { - @Link linkVar: string; - @Prop propVar: string = "Prop"; - - changeValue1() { - this.linkVar+="!!" +struct ChildLink { + @Link stateVar: string = "Child"; + @State stateVar1: string = "Child"; + @Link stateVar2: string = "Child"; + changeValue() { + this.stateVar+="~"; } - - changeValue2() { - this.propVar+="~~" + build() { + Button("ChildChange").backgroundColor("#FFFF00FF") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + this.changeValue(); + }) + Text(this.stateVar).fontSize(50) } +} - build() { - Column() { - Button(`click to change Link variable, add symbol !!`) - .backgroundColor("#4169E1") - .onClick((e: ClickEvent) => { - hilog.info(0x0000, 'testTag', 'On Click'); - this.changeValue1() - }) - Button(`click to change Prop variable, add symbol ~~`) - .backgroundColor("#3CB371") - .onClick((e: ClickEvent) => { - hilog.info(0x0000, 'testTag', 'On Click'); - this.changeValue2() - }) - Text(`Link variable in child: ${this.linkVar}`).fontSize(30) - Text(`Prop variable in child: ${this.propVar}`).fontSize(30) +export class ComExampleTrivialApplication extends UserView { + getBuilder() { + hilog.info(0x0000, 'testTag', 'getBuilder'); + let wrapper = @memo () => { + hilog.info(0x0000, 'testTag', 'MyStateSample'); + MyStateSample(undefined); } + return wrapper; } } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 14ba5bb50..e23a7f260 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -35,7 +35,6 @@ import { isKnownMethodDefinition, isEtsGlobalClass, isReourceNode, - isEntryClass, } from './struct-translators/utils'; import { isBuilderLambda, @@ -52,7 +51,6 @@ import { } from './builder-lambda-translators/utils'; import { isEntryWrapperClass } from './entry-translators/utils'; import { classifyProperty, PropertyTranslator } from './property-translators'; -import { createRegisterMethod } from './router'; export class CheckedTransformer extends AbstractVisitor { private scopeInfos: ScopeInfo[] = []; @@ -117,29 +115,11 @@ export class CheckedTransformer extends AbstractVisitor { return transformEtsGlobalClassMembers(node); } else if (arkts.isCallExpression(node) && isReourceNode(node)) { return transformResource(node, this.projectConfig); - } else if (arkts.isClassDeclaration(node) && isEntryClass(node)) { - const newNode = addRegisterRouterMethod(node); - return newNode; - } else if (arkts.isETSImportDeclaration(node)) { - const specifiers = node.specifiers; - for (const specifier of specifiers) { - const decl = arkts.getDecl(specifier); - console.log("print import decl:" + specifier.imported?.name) - console.log(decl?.dumpJson()); - } } return node; } } -function addRegisterRouterMethod( - node: arkts.ClassDeclaration -): arkts.ClassDeclaration { - const definition: arkts.ClassDefinition = node.definition!; - const registerMethod = createRegisterMethod() - return node; -} - function tranformClassMembers( node: arkts.ClassDeclaration, isDecl?: boolean, diff --git a/arkui-plugins/ui-plugins/interop.ts b/arkui-plugins/ui-plugins/interop.ts index 64faa6e59..5b75b3df2 100644 --- a/arkui-plugins/ui-plugins/interop.ts +++ b/arkui-plugins/ui-plugins/interop.ts @@ -16,102 +16,165 @@ import * as arkts from '@koalaui/libarkts'; -import { ARKUICOMPATIBLE, ESOBJECT, INITEMPTYOBJECT, NUMBER, SETPROPERTYBYNAME } from '../common/predefines'; +import { InteroperAbilityNames } from '../common/predefines'; +import { getCustomComponentOptionsName } from './utils'; -export function createEmptyESObject(node: arkts.Identifier): arkts.VariableDeclaration { +export function createEmptyESObject(name: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - node, - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(ESOBJECT), - arkts.factory.createIdentifier(INITEMPTYOBJECT), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - undefined - ) + arkts.factory.createIdentifier(name), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT), + arkts.factory.createIdentifier(InteroperAbilityNames.INITEMPTYOBJECT), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined ) ) ] ); } -export function setPropertyESObject(node: arkts.Identifier, key: arkts.StringLiteral, value: arkts.AstNode): arkts.ExpressionStatement { +export function getWrapValue(value: arkts.AstNode): arkts.AstNode { + let wrapMethod = InteroperAbilityNames.WRAP; + if (value instanceof arkts.StringLiteral) { + wrapMethod = InteroperAbilityNames.WRAPSTRING; + } else if (value instanceof arkts.NumberLiteral) { + wrapMethod = InteroperAbilityNames.WRAPINT; + } + + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT), + arkts.factory.createIdentifier(wrapMethod), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [value] + ); +} + +export function setPropertyESObject(name: string, key: arkts.StringLiteral, value: arkts.AstNode): arkts.ExpressionStatement { return arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(ESOBJECT), - arkts.factory.createIdentifier(SETPROPERTYBYNAME), + arkts.factory.createIdentifier(name), + arkts.factory.createIdentifier(InteroperAbilityNames.SETPROPERTY), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ), undefined, [ - node, key, - value + getWrapValue(value) ] ) ); } -function initialArgs(node: arkts.Identifier, args?: arkts.ObjectExpression): arkts.Statement[] { +export function getPropertyESObject(result: string, object: string, key: string): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier(result), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(object), + arkts.factory.createIdentifier(InteroperAbilityNames.GETPROPERTY), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [arkts.factory.create1StringLiteral(key)] + ) + ) + ] + ); +} + +function initialArgs(name: string, args?: arkts.ObjectExpression): arkts.Statement[] { if (!args) { return []; } const result: arkts.Statement[] = []; for (const property of args.properties) { + if (!(property instanceof arkts.Property)) { + continue; + } const key = property.key; const value = property.value; - //TODO: ident type of value - const key_result = arkts.factory.createStringLiteral(key?.name); - const value_result = value.value; - const setProperty = setPropertyESObject(node, key_result, value); + const key_string = arkts.factory.createStringLiteral(key.name); + const setProperty = setPropertyESObject(name, key_string, value); result.push(setProperty); } return result; } -function createLegacyStruct(name: string, param: arkts.Expression[]): arkts.Statement { +function getModule(moduleName: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier('component'), - arkts.factory.createTSAsExpression( - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(name) - ) - ), - param + arkts.factory.createIdentifier(InteroperAbilityNames.MODULE), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT), + arkts.factory.createIdentifier(InteroperAbilityNames.LOAD), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(ESOBJECT) - ) + undefined, + [arkts.factory.create1StringLiteral(moduleName)] + ) + ) + ] + ); +} + +function instantiateComonent(params: arkts.AstNode[]): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.STRUCTOBJECT), + arkts.factory.createIdentifier(InteroperAbilityNames.INSTANTIATE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false ), - false + undefined, + params ) ) ] ); } -function paramsLambdaDeclaration(args?: arkts.ObjectExpression): arkts.Statement[] { +function paramsLambdaDeclaration(name: string, args?: arkts.ObjectExpression): arkts.Statement[] { const result = []; result.push( arkts.factory.createVariableDeclaration( @@ -120,7 +183,7 @@ function paramsLambdaDeclaration(args?: arkts.ObjectExpression): arkts.Statement [ arkts.factory.createVariableDeclarator( arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier('paramLambda'), + arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA), arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( arkts.factory.createBlock([arkts.factory.createReturnStatement( @@ -128,12 +191,16 @@ function paramsLambdaDeclaration(args?: arkts.ObjectExpression): arkts.Statement arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, [], false - ) + ), )]), arkts.factory.createFunctionSignature( undefined, [], - undefined, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(getCustomComponentOptionsName(name)) + ) + ), false ), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, @@ -148,13 +215,32 @@ function paramsLambdaDeclaration(args?: arkts.ObjectExpression): arkts.Statement return result; } +function createInitReturn(componentName: string): arkts.ReturnStatement { + return arkts.factory.createReturnStatement( + arkts.ObjectExpression.createObjectExpression( + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + [ + arkts.Property.createProperty( + arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT), + arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT) + ), + arkts.Property.createProperty( + arkts.factory.createIdentifier('name'), + arkts.factory.createStringLiteral(componentName) + ) + ], + false + ), + ); +} + function createWrapperBlock(name: string, path: string, args?: arkts.ObjectExpression): arkts.BlockStatement { - const param = arkts.factory.createIdentifier('param'); - const extraInfo = arkts.factory.createIdentifier('extraInfo'); - const component = arkts.factory.createIdentifier('component'); - const parent = arkts.factory.createIdentifier('parent'); - const elmtId = arkts.factory.createIdentifier('elmtId'); - const lambda = arkts.factory.createArrowFunction( + const index = path.indexOf('/'); + if (index === -1) { + throw new Error('Error path of Legacy Component.'); + } + const moduleName = path.substring(0, index); + const blankLambda = arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( arkts.factory.createBlock([]), arkts.factory.createFunctionSignature( @@ -167,9 +253,30 @@ function createWrapperBlock(name: string, path: string, args?: arkts.ObjectExpre arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, ) ); - const initialArgsStatement = initialArgs(param, args); + const initialArgsStatement = initialArgs(InteroperAbilityNames.PARAM, args); return arkts.factory.createBlock( [ + createEmptyESObject(InteroperAbilityNames.PARAM), + ...initialArgsStatement, + createEmptyESObject(InteroperAbilityNames.EXTRAINFO), + setPropertyESObject(InteroperAbilityNames.EXTRAINFO, arkts.factory.create1StringLiteral('page'), arkts.factory.createStringLiteral(path)), + getModule(moduleName), + getPropertyESObject(InteroperAbilityNames.STRUCTOBJECT, InteroperAbilityNames.MODULE, name), + instantiateComonent([ + arkts.factory.createIdentifier(InteroperAbilityNames.PARENT), + arkts.factory.createIdentifier(InteroperAbilityNames.PARAM), + arkts.factory.createUndefinedLiteral(), + arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID), + blankLambda, + arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO) + ]), + ...paramsLambdaDeclaration(name, args), + setPropertyESObject( + InteroperAbilityNames.COMPONENT, + arkts.factory.create1StringLiteral('paramsGenerator_'), + arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA) + ), + createInitReturn(name) ] ); } @@ -184,11 +291,11 @@ function createInitializer(name: string, number: arkts.ETSTypeReference, esobjec undefined, [ arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('elmtId', number), + arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, number), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('instance', esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, esobject), undefined, ), ], @@ -213,11 +320,11 @@ function createUpdater(number: arkts.ETSTypeReference, esobject: arkts.ETSTypeRe undefined, [ arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('elmtId', number), + arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, number), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('instance', esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, esobject), undefined, ), ], @@ -233,18 +340,22 @@ function createUpdater(number: arkts.ETSTypeReference, esobject: arkts.ETSTypeRe export function processStructCall(node: arkts.CallExpression, path: string, args?: arkts.ObjectExpression): arkts.CallExpression { const number = arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(NUMBER) + arkts.factory.createIdentifier(InteroperAbilityNames.NUMBER) ) ); const esobject = arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(ESOBJECT) + arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT) ) ); - const initializer = createInitializer(node.expression.name, number, esobject, path, args); + const ident = node.expression; + if (!(ident instanceof arkts.Identifier)) { + throw new Error('Unexpected name of legacy component.'); + } + const initializer = createInitializer(ident.name, number, esobject, path, args); const updater = createUpdater(number, esobject); return arkts.factory.createCallExpression( - arkts.factory.createIdentifier(ARKUICOMPATIBLE), + arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), undefined, [ initializer, diff --git a/arkui-plugins/ui-plugins/legacy-transformer.ts b/arkui-plugins/ui-plugins/legacy-transformer.ts index 6719810bd..0bccdd7f8 100644 --- a/arkui-plugins/ui-plugins/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/legacy-transformer.ts @@ -15,7 +15,7 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; -import { ESOBJECT } from '../common/predefines'; +import { InteroperAbilityNames } from '../common/predefines'; interface LegacyTransformerOptions extends VisitorOptions { structList?: string[] @@ -69,7 +69,7 @@ export class LegacyTransformer extends AbstractVisitor { processConstructor(node: arkts.MethodDefinition): arkts.MethodDefinition { const esobject = arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(ESOBJECT) + arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT) ) ); const script = arkts.factory.createScriptFunction( @@ -78,11 +78,11 @@ export class LegacyTransformer extends AbstractVisitor { undefined, [ arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('parent', esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, esobject), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('params', esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.PARAM, esobject), undefined, ), arkts.factory.createParameterDeclaration( @@ -90,15 +90,15 @@ export class LegacyTransformer extends AbstractVisitor { undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('elmtId', esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, esobject), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('paramsLambda', esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA, esobject), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('extraInfo', esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO, esobject), undefined, ) ], undefined, false), diff --git a/arkui-plugins/ui-plugins/router.ts b/arkui-plugins/ui-plugins/router.ts deleted file mode 100644 index 202555f73..000000000 --- a/arkui-plugins/ui-plugins/router.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getCustomComponentOptionsName, Router } from './utils'; - - -export function addRegisterRouterMethod( - node: arkts.ClassDeclaration -): arkts.ClassDeclaration { - const definition: arkts.ClassDefinition = node.definition!; - const registerMethod = createRegisterMethod() - return node; -} - -export function createRegisterMethod(): arkts.MethodDefinition { - const script = arkts.factory.createScriptFunction( - arkts.factory.createBlock([createRegisterCall()]), - arkts.FunctionSignature.createFunctionSignature( - undefined, - [], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC - ); - - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - arkts.factory.createIdentifier(Router.REGISTERROUTER), - arkts.factory.createFunctionExpression(script), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, - false - ); -} - -export function createRegisterCall (): arkts.Statement { - return arkts.factory.createCallExpression( - arkts.factory.createIdentifier(Router.REGISTERPAGE), - undefined, - [ - - ] - ) -} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts index 1c3ebf9af..502917ecf 100644 --- a/arkui-plugins/ui-plugins/struct-translators/utils.ts +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -16,7 +16,6 @@ import * as arkts from '@koalaui/libarkts'; import { Dollars } from '../utils'; import { CustomComponentNames } from '../utils'; -import { isAnnotation } from '../../common/arkts-utils'; export type ScopeInfo = { name: string; @@ -78,17 +77,3 @@ export function isReourceNode(node: arkts.CallExpression): boolean { } return false; } - -/** - * Determine whether it is Entry class. - * - * @param node class declaration node - */ -export function isEntryClass(node: arkts.ClassDeclaration): boolean { - node.definition!.annotations.forEach((anno) => { - if (isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION_NAME)) { - return true; - } - }) - return false; -} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index d6432288a..c73d54b14 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -48,11 +48,6 @@ export enum Dollars { DOLLAR_DOLLAR = '$$', } -export enum Router { - REGISTERROUTER = 'registerRouter', - REGISTERPAGE = 'registerPage', -} - export function findLocalImport( node: arkts.ETSImportDeclaration, sourceName: string, diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index e95021c35..3a1805b6a 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -804,19 +804,19 @@ export class Es2pandaNativeModule { } _AstNodeRangeConst(context: KNativePointer, node: KNativePointer): KNativePointer { - throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); } _SourceRangeStart(context: KNativePointer, range: KNativePointer): KNativePointer { - throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); } _SourceRangeEnd(context: KNativePointer, range: KNativePointer): KNativePointer { - throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); } _CreateSourceRange(context: KNativePointer, start: KNativePointer, end: KNativePointer): KNativePointer { - throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") + throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); } } diff --git a/koala-wrapper/src/arkts-api/peers/SourceRange.ts b/koala-wrapper/src/arkts-api/peers/SourceRange.ts index b63557cd1..5ecee4ccb 100644 --- a/koala-wrapper/src/arkts-api/peers/SourceRange.ts +++ b/koala-wrapper/src/arkts-api/peers/SourceRange.ts @@ -12,15 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import { ArktsObject } from "./ArktsObject" -import { global } from "../static/global" -import { KNativePointer } from "@koalaui/interop" -import { SourcePosition } from "./SourcePosition"; +import { SourcePosition } from './SourcePosition'; +import { ArktsObject } from './ArktsObject'; +import { global } from '../static/global'; +import { KNativePointer } from '@koalaui/interop'; export class SourceRange extends ArktsObject { constructor(peer: KNativePointer) { - super(peer) + super(peer); } static create(start: SourcePosition, end: SourcePosition): SourceRange { -- Gitee From cfe1423dece67b7441a2f119b15c2df0694c105f Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Thu, 17 Apr 2025 22:42:23 +0800 Subject: [PATCH 059/123] implement @ObjectLink transform Signed-off-by: fengyuxin Change-Id: Ib00c492f4704a40149c79e9f211e5b3ab9196c68 --- arkui-plugins/common/predefines.ts | 15 +- .../ui-plugins/checked-transformer.ts | 113 ++++++++++++++- .../property-translators/objectlink.ts | 129 +++++++++++++----- .../property-translators/observedTrack.ts | 20 ++- .../ui-plugins/property-translators/utils.ts | 7 +- 5 files changed, 231 insertions(+), 53 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 65eb9e864..e13de5495 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -59,11 +59,9 @@ export const IMPORT_SOURCE_MAP: Map> = new Map> = new Map = new Map Date: Mon, 21 Apr 2025 21:26:56 +0800 Subject: [PATCH 060/123] import add Builder Signed-off-by: txzhang94 Change-Id: Ic9f0173a734ed0da147cba83af2af4281603276c --- compiler/src/process_interop_ui.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/compiler/src/process_interop_ui.ts b/compiler/src/process_interop_ui.ts index 355ddd1be..489f357da 100644 --- a/compiler/src/process_interop_ui.ts +++ b/compiler/src/process_interop_ui.ts @@ -131,6 +131,7 @@ class HandleUIImports { } } + this.handleImportBuilder(node); const result = ts.visitEachChild(node, this.visitNode.bind(this), this.context); if (ts.isIdentifier(result) && !this.shouldSkipIdentifier(result)) { @@ -142,6 +143,15 @@ class HandleUIImports { return result; } + private handleImportBuilder(node: ts.Node): void { + ts.getAllDecorators(node)?.forEach(element => { + if (element?.getText() === '@Builder') { + this.interfacesNeedToImport.add('Builder'); + return; + } + }); + } + private AddUIImports(node: ts.SourceFile): void { const compImportSpecifiers: ts.ImportSpecifier[] = []; const stateImportSpecifiers: ts.ImportSpecifier[] = []; -- Gitee From 7010dbd5bcb6a9e2135103a8038cfbeaf82fadea Mon Sep 17 00:00:00 2001 From: y00896775 Date: Thu, 17 Apr 2025 19:36:24 +0800 Subject: [PATCH 061/123] develop builderParam Signed-off-by: y00896775 Change-Id: I151d0c8d0e110dbb91e495ff3c1e9c33934d1b2f --- .../memo-plugins/function-transformer.ts | 10 +- .../ui-plugins/checked-transformer.ts | 36 +- .../property-translators/builderParam.ts | 25 +- .../struct-translators/struct-transformer.ts | 33 +- .../ui-plugins/struct-translators/utils.ts | 41 +- arkui-plugins/ui-plugins/utils.ts | 42 +- .../src/arkts-api/factory/nodeFactory.ts | 22 +- .../src/arkts-api/factory/nodeTests.ts | 5 + .../node-utilities/ObjectExpression.ts | 37 ++ .../src/arkts-api/node-utilities/Property.ts | 27 ++ koala-wrapper/src/arkts-api/visitor.ts | 378 +++++++++++------- 11 files changed, 443 insertions(+), 213 deletions(-) create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ObjectExpression.ts create mode 100644 koala-wrapper/src/arkts-api/node-utilities/Property.ts diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 1d9b5a3cf..7de7c86dd 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -360,10 +360,14 @@ export class FunctionTransformer extends AbstractVisitor { private updateCallExpression(node: arkts.CallExpression): arkts.CallExpression { const expr = node.expression; const decl = arkts.getDecl(expr); + if (!decl || !arkts.isMethodDefinition(decl)) { + return node; + } if ( - decl && - arkts.isMethodDefinition(decl) && - (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction)) + (decl.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET && + findMemoFromTypeAnnotation(decl.scriptFunction.returnTypeAnnotation)) || + hasMemoAnnotation(decl.scriptFunction) || + hasMemoIntrinsicAnnotation(decl.scriptFunction) ) { return this.updateDeclaredMemoCall(node, decl); } diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index e713e6be5..5518e9960 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -27,15 +27,19 @@ import { getTypeNameFromTypeParameter, getTypeParamsFromClassDecl, BuilderLambdaNames, - getGettersFromClassDecl + getGettersFromClassDecl, + addMemoAnnotation, } from './utils'; import { hasDecorator, DecoratorNames } from './property-translators/utils'; import { - ScopeInfo, isCustomComponentClass, isKnownMethodDefinition, isEtsGlobalClass, isReourceNode, + ScopeInfoCollection, + CustomComponentScopeInfo, + isMemoCall, + findCanAddMemoFromArrowFunction, } from './struct-translators/utils'; import { isBuilderLambda, @@ -56,36 +60,37 @@ import { ObservedTrackTranslator } from './property-translators/observedTrack'; import { nodeByType } from '@koalaui/libarkts/build/src/reexport-for-generated'; export class CheckedTransformer extends AbstractVisitor { - private scopeInfos: ScopeInfo[] = []; + private scopeInfoCollection: ScopeInfoCollection; projectConfig: ProjectConfig | undefined; constructor(projectConfig: ProjectConfig | undefined) { super(); this.projectConfig = projectConfig; + this.scopeInfoCollection = { customComponents: [] }; } reset(): void { super.reset(); - this.scopeInfos = []; + this.scopeInfoCollection = { customComponents: [] }; } enter(node: arkts.AstNode): void { if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfos.push({ name: node.definition!.ident!.name }); + this.scopeInfoCollection.customComponents.push({ name: node.definition!.ident!.name }); } - if (arkts.isMethodDefinition(node) && this.scopeInfos.length > 0) { + if (arkts.isMethodDefinition(node) && this.scopeInfoCollection.customComponents.length > 0) { const name = node.name.name; - const scopeInfo = this.scopeInfos.pop()!; + const scopeInfo = this.scopeInfoCollection.customComponents.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; - this.scopeInfos.push(scopeInfo); + this.scopeInfoCollection.customComponents.push(scopeInfo); } } exit(node: arkts.AstNode): void { if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfos.pop(); + this.scopeInfoCollection.customComponents.pop(); } } @@ -100,9 +105,10 @@ export class CheckedTransformer extends AbstractVisitor { } const node = this.visitEachChild(beforeChildren); if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - let scope: ScopeInfo | undefined; - if (this.scopeInfos.length > 0) { - scope = this.scopeInfos[this.scopeInfos.length - 1]; + let scope: CustomComponentScopeInfo | undefined; + const scopeInfos: CustomComponentScopeInfo[] = this.scopeInfoCollection.customComponents; + if (scopeInfos.length > 0) { + scope = scopeInfos[scopeInfos.length - 1]; } const newClass: arkts.ClassDeclaration = tranformClassMembers( node, @@ -118,6 +124,8 @@ export class CheckedTransformer extends AbstractVisitor { return transformEtsGlobalClassMembers(node); } else if (arkts.isCallExpression(node) && isReourceNode(node)) { return transformResource(node, this.projectConfig); + } else if (findCanAddMemoFromArrowFunction(node)) { + return addMemoAnnotation(node); } else if (arkts.isClassDeclaration(node)) { return transformObservedTracked(node); @@ -340,7 +348,7 @@ function thisSubscribedWatchesMember(member: string): arkts.MemberExpression { function tranformClassMembers( node: arkts.ClassDeclaration, isDecl?: boolean, - scope?: ScopeInfo + scope?: CustomComponentScopeInfo ): arkts.ClassDeclaration { if (!node.definition) { return node; @@ -416,7 +424,7 @@ function tranformPropertyMembers( propertyTranslators: PropertyTranslator[], optionsTypeName: string, isDecl?: boolean, - scope?: ScopeInfo + scope?: CustomComponentScopeInfo ): arkts.AstNode[] { const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts index bde4d63b9..5ae6fdf26 100644 --- a/arkui-plugins/ui-plugins/property-translators/builderParam.ts +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -85,25 +85,14 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia return arkts.factory.createAssignmentExpression( mutableThis, arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName + arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName + ), + this.property.value ?? arkts.factory.createUndefinedLiteral(), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ) ); } - - generateUpdateStruct(mutableThis: arkts.Expression, originalName: string): arkts.AstNode { - const right: arkts.MemberExpression = arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('initializers'), - arkts.factory.createIdentifier(originalName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - true - ); - return arkts.factory.createAssignmentExpression( - mutableThis, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - right - ); - } } diff --git a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts index b280b0ad5..be9ebdb11 100644 --- a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts +++ b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts @@ -19,25 +19,26 @@ import { annotation, collect, filterDefined } from '../../common/arkts-utils'; import { ProjectConfig } from '../../common/plugin-context'; import { classifyProperty, PropertyTranslator } from '../property-translators'; import { + addMemoAnnotation, CustomComponentNames, getCustomComponentOptionsName, getTypeNameFromTypeParameter, getTypeParamsFromClassDecl, } from '../utils'; -import { isCustomComponentClass, isKnownMethodDefinition, isEtsGlobalClass, isReourceNode } from './utils'; +import { isCustomComponentClass, isKnownMethodDefinition, isEtsGlobalClass, isReourceNode, CustomComponentScopeInfo, findCanAddMemoFromArrowFunction } from './utils'; import { factory as uiFactory } from '../ui-factory'; import { factory } from './factory'; import { isEntryWrapperClass } from '../entry-translators/utils'; import { factory as entryFactory } from '../entry-translators/factory'; import { DecoratorNames, hasDecorator } from '../property-translators/utils'; -import { ScopeInfo } from './utils'; +import { ScopeInfoCollection } from './utils'; function tranformPropertyMembers( className: string, propertyTranslators: PropertyTranslator[], optionsTypeName: string, isDecl?: boolean, - scope?: ScopeInfo + scope?: CustomComponentScopeInfo ): arkts.AstNode[] { const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); @@ -99,7 +100,7 @@ function transformOtherMembersInClass( function tranformClassMembers( node: arkts.ClassDeclaration, isDecl?: boolean, - scope?: ScopeInfo + scope?: CustomComponentScopeInfo ): arkts.ClassDeclaration { if (!node.definition) { return node; @@ -154,36 +155,37 @@ function transformResource( } export class StructTransformer extends AbstractVisitor { - private scopeInfos: ScopeInfo[] = []; + private scopeInfoCollection: ScopeInfoCollection; projectConfig: ProjectConfig | undefined; constructor(projectConfig: ProjectConfig | undefined) { super(); this.projectConfig = projectConfig; + this.scopeInfoCollection = { customComponents: [] }; } reset(): void { super.reset(); - this.scopeInfos = []; + this.scopeInfoCollection = { customComponents: [] }; } enter(node: arkts.AstNode): void { if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfos.push({ name: node.definition!.ident!.name }); + this.scopeInfoCollection.customComponents.push({ name: node.definition!.ident!.name }); } - if (arkts.isMethodDefinition(node) && this.scopeInfos.length > 0) { + if (arkts.isMethodDefinition(node) && this.scopeInfoCollection.customComponents.length > 0) { const name = node.name.name; - const scopeInfo = this.scopeInfos.pop()!; + const scopeInfo = this.scopeInfoCollection.customComponents.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; - this.scopeInfos.push(scopeInfo); + this.scopeInfoCollection.customComponents.push(scopeInfo); } } exit(node: arkts.AstNode): void { if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfos.pop(); + this.scopeInfoCollection.customComponents.pop(); } } @@ -191,9 +193,10 @@ export class StructTransformer extends AbstractVisitor { this.enter(beforeChildren); const node = this.visitEachChild(beforeChildren); if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - let scope: ScopeInfo | undefined; - if (this.scopeInfos.length > 0) { - scope = this.scopeInfos[this.scopeInfos.length - 1]; + let scope: CustomComponentScopeInfo | undefined; + const scopeInfos: CustomComponentScopeInfo[] = this.scopeInfoCollection.customComponents; + if (scopeInfos.length > 0) { + scope = scopeInfos[scopeInfos.length - 1]; } const newClass: arkts.ClassDeclaration = tranformClassMembers( node, @@ -209,6 +212,8 @@ export class StructTransformer extends AbstractVisitor { return transformEtsGlobalClassMembers(node); } else if (arkts.isCallExpression(node) && isReourceNode(node)) { return transformResource(node, this.projectConfig); + } else if (findCanAddMemoFromArrowFunction(node)) { + return addMemoAnnotation(node); } return node; } diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts index 502917ecf..2af217626 100644 --- a/arkui-plugins/ui-plugins/struct-translators/utils.ts +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -14,10 +14,15 @@ */ import * as arkts from '@koalaui/libarkts'; -import { Dollars } from '../utils'; +import { Dollars, isMemoAnnotation } from '../utils'; import { CustomComponentNames } from '../utils'; +import { DecoratorNames, isDecoratorAnnotation } from '../property-translators/utils'; -export type ScopeInfo = { +export type ScopeInfoCollection = { + customComponents: CustomComponentScopeInfo[]; +}; + +export type CustomComponentScopeInfo = { name: string; hasInitializeStruct?: boolean; hasUpdateStruct?: boolean; @@ -77,3 +82,35 @@ export function isReourceNode(node: arkts.CallExpression): boolean { } return false; } + +export function isMemoCall(node: arkts.AstNode): node is arkts.CallExpression { + if (!arkts.isCallExpression(node)) { + return false; + } + const expr: arkts.AstNode = node.expression; + const decl: arkts.AstNode | undefined = arkts.getDecl(expr); + + if (!decl) { + return false; + } + + if (arkts.isMethodDefinition(decl)) { + return decl.scriptFunction.annotations.some( + (anno) => isDecoratorAnnotation(anno, DecoratorNames.BUILDER) || isMemoAnnotation(anno, 'memo') + ); + } + return false; +} + +export function findCanAddMemoFromArrowFunction(node: arkts.AstNode): node is arkts.ArrowFunctionExpression { + if (!arkts.isArrowFunctionExpression(node)) { + return false; + } + const hasMemo: boolean = node.annotations.some((anno) => isMemoAnnotation(anno, 'memo')); + if (!hasMemo && !!node.scriptFunction.body && arkts.isBlockStatement(node.scriptFunction.body)) { + return node.scriptFunction.body.statements.some( + (st) => arkts.isExpressionStatement(st) && isMemoCall(st.expression) + ); + } + return false; +} diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index a50608fee..98a79be41 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -14,7 +14,7 @@ */ import * as arkts from '@koalaui/libarkts'; -import { annotation } from "../common/arkts-utils"; +import { annotation } from '../common/arkts-utils'; export enum CustomComponentNames { ENTRY_ANNOTATION_NAME = 'Entry', @@ -101,9 +101,7 @@ export function createOptionalClassProperty( const newProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier(name), undefined, - stageManagementIdent.length - ? createStageManagementType(stageManagementIdent, property) - : newType, + stageManagementIdent.length ? createStageManagementType(stageManagementIdent, property) : newType, modifiers, false ); @@ -131,3 +129,39 @@ export function getGettersFromClassDecl(definition: arkts.ClassDefinition): arkt arkts.hasModifierFlag(member, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_GETTER) ) as arkts.MethodDefinition[]; } + +export type MemoAstNode = + | arkts.ScriptFunction + | arkts.ETSParameterExpression + | arkts.ClassProperty + | arkts.TSTypeAliasDeclaration + | arkts.ETSFunctionType + | arkts.ArrowFunctionExpression + | arkts.ETSUnionType; + +export function isMemoAnnotation(node: arkts.AnnotationUsage, memoName: string): boolean { + if (!(node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === memoName)) { + return false; + } + return true; +} + +export function addMemoAnnotation(node: T, memoName: string = 'memo'): T { + if (arkts.isETSUnionType(node)) { + const functionType = node.types.find((type) => arkts.isETSFunctionType(type)); + if (!functionType) { + return node; + } + addMemoAnnotation(functionType, memoName); + return node; + } + const newAnnotations: arkts.AnnotationUsage[] = [ + ...node.annotations.filter((it) => !isMemoAnnotation(it, memoName)), + annotation(memoName), + ]; + if (arkts.isEtsParameterExpression(node)) { + node.annotations = newAnnotations; + return node; + } + return node.setAnnotations(newAnnotations) as T; +} diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index 2786562c2..c3e6cd06c 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -70,7 +70,9 @@ import { ChainExpression, BlockExpression, ETSNewClassInstanceExpression, - BooleanLiteral + BooleanLiteral, + ObjectExpression, + Property } from "../../generated" import { Es2pandaModifierFlags @@ -127,6 +129,8 @@ import { updateChainExpression } from "../node-utilities/ChainExpression" import { updateBlockExpression } from "../node-utilities/BlockExpression" import { updateNullLiteral } from "../node-utilities/NullLiteral" import { updateETSNewClassInstanceExpression } from "../node-utilities/ETSNewClassInstanceExpression" +import { updateObjectExpression } from "../node-utilities/ObjectExpression" +import { updateProperty } from "../node-utilities/Property" export const factory = { get createIdentifier() { @@ -432,12 +436,24 @@ export const factory = { get updateETSNewClassInstanceExpression() { return updateETSNewClassInstanceExpression }, - get createETSStringLiteralType(){ + get createETSStringLiteralType() { return ETSStringLiteralType.create; }, - get createBooleanLiteral(): (value: boolean) => BooleanLiteral { + get createBooleanLiteral(): (...args: Parameters) => BooleanLiteral { return BooleanLiteral.createBooleanLiteral; }, + get createObjectExpression(): (...args: Parameters) => ObjectExpression { + return ObjectExpression.createObjectExpression; + }, + get updateObjectExpression(): (...args: Parameters) => ObjectExpression { + return updateObjectExpression; + }, + get createProperty(): (...args: Parameters) => Property { + return Property.createProperty; + }, + get updateProperty(): (...args: Parameters) => Property { + return updateProperty; + }, /** @deprecated */ createTypeParameter1_(name: Identifier, constraint?: TypeNode, defaultType?: TypeNode) { return TSTypeParameter.createTSTypeParameter(Identifier.create1Identifier(name.name), constraint, defaultType) diff --git a/koala-wrapper/src/arkts-api/factory/nodeTests.ts b/koala-wrapper/src/arkts-api/factory/nodeTests.ts index b40a1a353..6f2d9590f 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeTests.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeTests.ts @@ -28,6 +28,7 @@ import { StructDeclaration, VariableDeclaration, VariableDeclarator, + AssignmentExpression } from "../types" import { MemberExpression } from "../to-be-generated/MemberExpression" import { AstNode } from "../peers/AstNode" @@ -87,3 +88,7 @@ export function isIfStatement(node: AstNode): node is IfStatement { export function isVariableDeclarator(node: AstNode): node is VariableDeclarator { return node instanceof VariableDeclarator } + +export function isAssignmentExpression(node: AstNode): node is AssignmentExpression { + return node instanceof AssignmentExpression; +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/node-utilities/ObjectExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ObjectExpression.ts new file mode 100644 index 000000000..ac7a9d6b6 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ObjectExpression.ts @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ObjectExpression, Property } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { Es2pandaAstNodeType } from '../../Es2pandaEnums'; + +export function updateObjectExpression( + original: ObjectExpression, + nodeType: Es2pandaAstNodeType, + properties: Property[], + trailingComma: boolean +): ObjectExpression { + if ( + isSameNativeObject(properties, original.properties) + /* TODO: no getter for nodeType */ + /* TODO: no getter for trailingComma */ + ) { + return original; + } + + const update = updateThenAttach(ObjectExpression.updateObjectExpression, attachModifiers); + return update(original, nodeType, properties, trailingComma); +} diff --git a/koala-wrapper/src/arkts-api/node-utilities/Property.ts b/koala-wrapper/src/arkts-api/node-utilities/Property.ts new file mode 100644 index 000000000..4b0a33c5b --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/Property.ts @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Expression, Property } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateProperty(original: Property, key?: Expression, value?: Expression): Property { + if (isSameNativeObject(key, original.key) && isSameNativeObject(value, original.value)) { + return original; + } + + const update = updateThenAttach(Property.updateProperty, attachModifiers); + return update(original, key, value); +} diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index 2d62b5a42..aa097976e 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -13,21 +13,21 @@ * limitations under the License. */ -import { global } from "./static/global" -import { factory } from "./factory/nodeFactory" +import { global } from './static/global'; +import { factory } from './factory/nodeFactory'; import { Es2pandaClassDefinitionModifiers, Es2pandaImportKinds, Es2pandaModifierFlags, - Es2pandaVariableDeclaratorFlag -} from "../generated/Es2pandaEnums" -import { AstNode } from "./peers/AstNode" -import { - isBlockStatement, - isConditionalExpression, - isTSInterfaceBody, - isTSInterfaceDeclaration, - isClassDeclaration, + Es2pandaVariableDeclaratorFlag, +} from '../generated/Es2pandaEnums'; +import { AstNode } from './peers/AstNode'; +import { + isBlockStatement, + isConditionalExpression, + isTSInterfaceBody, + isTSInterfaceDeclaration, + isClassDeclaration, isClassDefinition, isTSAsExpression, isETSImportDeclaration, @@ -36,8 +36,12 @@ import { FunctionSignature, Property, isClassProperty, - isImportDeclaration -} from "../generated" + isImportDeclaration, + isObjectExpression, + ObjectExpression, + isProperty, + Expression, +} from '../generated'; import { isEtsScript, isCallExpression, @@ -50,21 +54,19 @@ import { isIfStatement, isVariableDeclaration, isVariableDeclarator, - isArrowFunctionExpression -} from "./factory/nodeTests" -import { - classDefinitionFlags, - hasModifierFlag, - classPropertySetOptional - } from "./utilities/public" + isArrowFunctionExpression, + isAssignmentExpression, +} from './factory/nodeTests'; +import { classDefinitionFlags } from './utilities/public'; +import { Es2pandaAstNodeType } from '../Es2pandaEnums'; -type Visitor = (node: AstNode) => AstNode +type Visitor = (node: AstNode) => AstNode; export interface StructVariableMetadata { - name: string, - properties: string[], - modifiers: Es2pandaModifierFlags, - hasStateManagementType?: boolean + name: string; + properties: string[]; + modifiers: Es2pandaModifierFlags; + hasStateManagementType?: boolean; } export class StructInfo { @@ -121,41 +123,44 @@ export class GlobalInfo { // TODO: rethink (remove as) function nodeVisitor(node: T, visitor: Visitor): T { if (node === undefined) { - return node + return node; } - return visitor(node) as T + return visitor(node) as T; } // TODO: rethink (remove as) -function nodesVisitor(nodes: TIn, visitor: Visitor): T[] | TIn { +function nodesVisitor( + nodes: TIn, + visitor: Visitor +): T[] | TIn { if (nodes === undefined) { - return nodes + return nodes; } - return nodes.map(node => visitor(node) as T) + return nodes.map((node) => visitor(node) as T); } -// TODO: apply this to all nodes that does not require updating -function visitWithoutUpdate( - node: T, - visitor: Visitor -): T { - if (isImportDeclaration(node)) { - nodesVisitor(node.specifiers, visitor); - } - return node; +let updated: boolean = false; + +export function visitEachChild(node: AstNode, visitor: Visitor): AstNode { + updated = false; + let script: AstNode = node; + script = visitETSModule(script, visitor); + script = visitDeclaration(script, visitor); + script = visitDefinition(script, visitor); + script = visitDefinitionBody(script, visitor); + script = visitStatement(script, visitor); + script = visitOuterExpression(script, visitor); + script = visitInnerExpression(script, visitor); + // TODO + return visitWithoutUpdate(script, visitor); } -export function visitEachChild( - node: AstNode, - visitor: Visitor -): AstNode { - if (isEtsScript(node)) { - return factory.updateEtsScript( - node, - nodesVisitor(node.statements, visitor) - ); +function visitOuterExpression(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; } if (isCallExpression(node)) { + updated = true; const call = factory.updateCallExpression( node, nodeVisitor(node.expression, visitor), @@ -167,40 +172,126 @@ export function visitEachChild( } return call; } - if (isFunctionDeclaration(node)) { - return factory.updateFunctionDeclaration( + if (isArrowFunctionExpression(node)) { + updated = true; + return factory.updateArrowFunction(node, nodeVisitor(node.scriptFunction, visitor)); + } + if (isAssignmentExpression(node)) { + updated = true; + return factory.updateAssignmentExpression( node, - nodeVisitor(node.scriptFunction, visitor), - node.isAnon, - node.annotations, + nodeVisitor(node.left as Expression, visitor), + node.operatorType, + nodeVisitor(node.right as Expression, visitor) ); } - if (isBlockStatement(node)) { - return factory.updateBlock( + // TODO + return node; +} + +function visitInnerExpression(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; + } + if (isMemberExpression(node)) { + updated = true; + return factory.updateMemberExpression( node, - nodesVisitor(node.statements, visitor), + nodeVisitor(node.object, visitor), + nodeVisitor(node.property, visitor), + node.kind, + node.computed, + node.optional ); } - if (isExpressionStatement(node)) { - return factory.updateExpressionStatement( + if (isConditionalExpression(node)) { + updated = true; + return factory.updateConditionalExpression( + node, + nodeVisitor(node.test, visitor), + nodeVisitor(node.consequent, visitor), + nodeVisitor(node.alternate, visitor) + ); + } + if (isTSAsExpression(node)) { + updated = true; + return factory.updateTSAsExpression( node, - nodeVisitor(node.expression, visitor) + nodeVisitor(node.expr, visitor), + nodeVisitor(node.typeAnnotation, visitor), + node.isConst ); } - if (isClassDeclaration(node)) { - return factory.updateClassDeclaration( + if (isObjectExpression(node)) { + updated = true; + return factory.updateObjectExpression( + node, + Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + nodesVisitor(node.properties as Property[], visitor), + false + ); + } + if (isProperty(node)) { + updated = true; + return factory.updateProperty(node, node.key, nodeVisitor(node.value, visitor)); + } + // TODO + return node; +} + +function visitDeclaration(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; + } + if (isFunctionDeclaration(node)) { + updated = true; + return factory.updateFunctionDeclaration( node, - nodeVisitor(node.definition, visitor) + nodeVisitor(node.scriptFunction, visitor), + node.isAnon, + node.annotations ); } + if (isClassDeclaration(node)) { + updated = true; + return factory.updateClassDeclaration(node, nodeVisitor(node.definition, visitor)); + } if (isStructDeclaration(node)) { - return factory.updateStructDeclaration( + updated = true; + return factory.updateStructDeclaration(node, nodeVisitor(node.definition, visitor)); + } + if (isTSInterfaceDeclaration(node)) { + updated = true; + return factory.updateInterfaceDeclaration( node, - nodeVisitor(node.definition, visitor) + nodesVisitor(node.extends, visitor), + nodeVisitor(node.id, visitor), + nodeVisitor(node.typeParams, visitor), + nodeVisitor(node.body, visitor), + node.isStatic, + // TODO: how do I get it? + true ); } + if (isVariableDeclaration(node)) { + updated = true; + return factory.updateVariableDeclaration( + node, + 0, + node.declarationKind, + nodesVisitor(node.declarators, visitor) + ); + } + // TODO + return node; +} + +function visitDefinition(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; + } if (isClassDefinition(node)) { - // TODO: fix + updated = true; return factory.updateClassDefinition( node, node.ident, @@ -215,108 +306,89 @@ export function visitEachChild( ); } if (isMethodDefinition(node)) { - // TODO: fix + updated = true; return factory.updateMethodDefinition( node, node.kind, node.name, - factory.createFunctionExpression( - // TODO: maybe fix - nodeVisitor(node.scriptFunction, visitor) - ), + factory.createFunctionExpression(nodeVisitor(node.scriptFunction, visitor)), node.modifiers, false ); } - if (isScriptFunction(node)) { - return factory.updateScriptFunction( - node, - nodeVisitor(node.body, visitor), - FunctionSignature.createFunctionSignature( - nodeVisitor(node.typeParams, visitor), - nodesVisitor(node.params, visitor), - nodeVisitor(node.returnTypeAnnotation, visitor), - node.hasReceiver - ), - node.flags, - node.modifiers - ); + if (isTSInterfaceBody(node)) { + updated = true; + return factory.updateInterfaceBody(node, nodesVisitor(node.body, visitor)); } - if (isMemberExpression(node)) { - return factory.updateMemberExpression( + if (isVariableDeclarator(node)) { + updated = true; + return factory.updateVariableDeclarator( node, - nodeVisitor(node.object, visitor), - nodeVisitor(node.property, visitor), - node.kind, - node.computed, - node.optional + global.generatedEs2panda._VariableDeclaratorFlag(global.context, node.peer), + nodeVisitor(node.name, visitor), + nodeVisitor(node.initializer, visitor) ); } - if (isTSInterfaceDeclaration(node)) { - return factory.updateInterfaceDeclaration( - node, - nodesVisitor(node.extends, visitor), - nodeVisitor(node.id, visitor), - nodeVisitor(node.typeParams, visitor), - nodeVisitor(node.body, visitor), - node.isStatic, - // TODO: how do I get it? - true - ); + return node; +} + +function visitStatement(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; } - if (isTSInterfaceBody(node)) { - return factory.updateInterfaceBody( - node, - nodesVisitor(node.body, visitor) - ); + if (isBlockStatement(node)) { + updated = true; + return factory.updateBlock(node, nodesVisitor(node.statements, visitor)); + } + if (isExpressionStatement(node)) { + updated = true; + return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor)); } if (isIfStatement(node)) { + updated = true; return factory.updateIfStatement( node, nodeVisitor(node.test, visitor), nodeVisitor(node.consequent, visitor), - nodeVisitor(node.alternate, visitor), - ); - } - if (isConditionalExpression(node)) { - return factory.updateConditionalExpression( - node, - nodeVisitor(node.test, visitor), - nodeVisitor(node.consequent, visitor), - nodeVisitor(node.alternate, visitor), + nodeVisitor(node.alternate, visitor) ); } - if (isVariableDeclaration(node)) { - return factory.updateVariableDeclaration( - node, - 0, - node.declarationKind, - nodesVisitor(node.declarators, visitor), - ); + // TODO + return node; +} + +function visitETSModule(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; } - if (isVariableDeclarator(node)) { - return factory.updateVariableDeclarator( - node, - global.generatedEs2panda._VariableDeclaratorFlag(global.context, node.peer), - nodeVisitor(node.name, visitor), - nodeVisitor(node.initializer, visitor), - ); + if (isEtsScript(node)) { + updated = true; + return factory.updateEtsScript(node, nodesVisitor(node.statements, visitor)); } - if (isArrowFunctionExpression(node)) { - return factory.updateArrowFunction( - node, - nodeVisitor(node.scriptFunction, visitor), - ); + return node; +} + +function visitDefinitionBody(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; } - if (isTSAsExpression(node)) { - return factory.updateTSAsExpression( + if (isScriptFunction(node)) { + updated = true; + return factory.updateScriptFunction( node, - nodeVisitor(node.expr, visitor), - nodeVisitor(node.typeAnnotation, visitor), - node.isConst + nodeVisitor(node.body, visitor), + factory.createFunctionSignature( + nodeVisitor(node.typeParams, visitor), + nodesVisitor(node.params, visitor), + nodeVisitor(node.returnTypeAnnotation, visitor), + node.hasReceiver + ), + node.flags, + node.modifiers ); } if (isClassProperty(node)) { + updated = true; return factory.updateClassProperty( node, node.key, @@ -326,21 +398,17 @@ export function visitEachChild( node.isComputed ); } - if (isClassProperty(node)) { - const _node = factory.updateClassProperty( - node, - node.key, - nodeVisitor(node.value, visitor), - node.typeAnnotation, - node.modifiers, - node.isComputed - ); - if (hasModifierFlag(node, Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL)) { - classPropertySetOptional(_node, true); - } - _node.setAnnotations(node.annotations); - return _node; - } // TODO - return visitWithoutUpdate(node, visitor); + return node; +} + +// TODO: apply this to all nodes that does not require updating +function visitWithoutUpdate(node: T, visitor: Visitor): T { + if (updated) { + return node; + } + if (isImportDeclaration(node)) { + nodesVisitor(node.specifiers, visitor); + } + return node; } -- Gitee From 6ec91437a0a7d15d7152adc334817c3b5d722c55 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 16 Apr 2025 11:07:06 +0800 Subject: [PATCH 062/123] enable builder lambda transform arrow functions in chain expression Signed-off-by: Jiakai Shi Change-Id: I1cfd34c7d19761adccc7a7ef8af05b35d19953aa --- .../builder-lambda-transformer.ts | 257 +--------------- .../builder-lambda-translators/factory.ts | 282 +++++++++++++++++- .../builder-lambda-translators/utils.ts | 8 +- .../ui-plugins/checked-transformer.ts | 256 ++-------------- 4 files changed, 316 insertions(+), 487 deletions(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts index a0d1134c5..5e4dc8331 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts @@ -12,263 +12,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../../common/abstract-visitor'; -import { BuilderLambdaNames } from '../utils'; -import { filterDefined, removeAnnotationByName, backingField } from '../../common/arkts-utils'; -import { DecoratorNames } from '../property-translators/utils'; -import { - BuilderLambdaDeclInfo, - isBuilderLambda, - builderLambdaFunctionName, - findBuilderLambdaDeclInfo, - isBuilderLambdaMethodDecl, - replaceBuilderLambdaDeclMethodName, - isBuilderLambdaFunctionCall, - callIsGoodForBuilderLambda, - builderLambdaTypeName, - builderLambdaMethodDeclType, - builderLambdaType, -} from './utils'; +import { isBuilderLambda, isBuilderLambdaMethodDecl } from './utils'; import { factory } from './factory'; -// TODO: very time-consuming... -function updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, isExternal?: boolean): arkts.AstNode { - if (arkts.isIfStatement(statement)) { - const alternate = !!statement.alternate - ? updateIfElseContentBodyInBuilderLambda(statement.alternate, isExternal) - : statement.alternate; - const consequence = updateIfElseContentBodyInBuilderLambda(statement.consequent, isExternal); - return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); - } - if (arkts.isBlockStatement(statement)) { - return arkts.factory.updateBlock( - statement, - statement.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) - ); - } - return statement; -} - -function updateContentBodyInBuilderLambda(statement: arkts.Statement, isExternal?: boolean): arkts.Statement { - if ( - arkts.isExpressionStatement(statement) && - arkts.isCallExpression(statement.expression) && - isBuilderLambda(statement.expression, isExternal) - ) { - return arkts.factory.updateExpressionStatement(statement, transformBuilderLambda(statement.expression)); - } - // TODO: very time-consuming... - if (arkts.isIfStatement(statement)) { - return updateIfElseContentBodyInBuilderLambda(statement, isExternal); - } - - return statement; -} - -function builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { - if (!callIsGoodForBuilderLambda(leaf)) { - return undefined; - } - const node = leaf.expression; - const funcName = builderLambdaFunctionName(leaf); - if (!funcName) { - return undefined; - } - if (arkts.isIdentifier(node)) { - return arkts.factory.createIdentifier(funcName); - } - if (arkts.isMemberExpression(node)) { - return arkts.factory.createMemberExpression( - node.object, - arkts.factory.createIdentifier(funcName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - node.computed, - node.optional - ); - } - return undefined; -} - -function createOrUpdateArgInBuilderLambda( - arg: arkts.Expression | undefined, - isExternal?: boolean, - typeName?: string, - fallback?: arkts.AstNode -): arkts.AstNode { - if (!arg) { - return fallback ?? arkts.factory.createUndefinedLiteral(); - } - if (arkts.isArrowFunctionExpression(arg)) { - return processArgArrowFunction(arg, isExternal); - } - if (arkts.isTSAsExpression(arg)) { - return processArgTSAsExpression(arg, typeName!); - } - return arg; -} - -function processArgArrowFunction( - arg: arkts.ArrowFunctionExpression, - isExternal?: boolean -): arkts.ArrowFunctionExpression { - const func: arkts.ScriptFunction = arg.scriptFunction; - const updateFunc = arkts.factory.updateScriptFunction( - func, - !!func.body && arkts.isBlockStatement(func.body) - ? arkts.factory.updateBlock( - func.body, - func.body.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) - ) - : undefined, - arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), - func.flags, - func.modifiers - ); - return arkts.factory.updateArrowFunction(arg, updateFunc); -} - -function updateParameterPassing( - prop: arkts.Property, - index: number, - currentStructInfo: arkts.StructInfo, - properties: arkts.Property[] -): void { - if ( - prop.key && - prop.value && - arkts.isIdentifier(prop.key) && - arkts.isMemberExpression(prop.value) && - arkts.isThisExpression(prop.value.object) && - arkts.isIdentifier(prop.value.property) - ) { - const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; - if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { - properties[index] = arkts.Property.updateProperty( - prop, - arkts.factory.createIdentifier(backingField(prop.key.name)), - factory.updateBackingMember(prop.value, prop.value.property.name) - ); - } - } -} - -function processArgTSAsExpression(arg: arkts.TSAsExpression, typeName: string): arkts.TSAsExpression { - if (!arg.expr || !arkts.isObjectExpression(arg.expr)) { - return arg; - } - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); - const properties = arg.expr.properties as arkts.Property[]; - properties.forEach((prop, index) => { - updateParameterPassing(prop, index, currentStructInfo, properties); - }); - const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( - arg.expr, - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - properties, - false - ); - return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); -} - -function generateArgsInBuilderLambda( - leaf: arkts.CallExpression, - lambdaBody: arkts.Identifier | arkts.CallExpression, - declInfo: BuilderLambdaDeclInfo, - isExternal?: boolean -): (arkts.AstNode | undefined)[] { - const { params } = declInfo; - const typeNode: arkts.TypeNode | undefined = builderLambdaType(leaf); - const typeName: string | undefined = builderLambdaTypeName(leaf); - const args: (arkts.AstNode | undefined)[] = [factory.createStyleArgInBuilderLambda(lambdaBody, typeNode)]; - let index = 0; - while (index < params.length) { - const isReusable: boolean = typeName - ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable - : false; - if (isReusable && index === params.length - 1) { - const reuseId = arkts.factory.createStringLiteral(typeName!); - args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName, reuseId)); - } else { - args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName)); - } - index++; - } - return args; -} - -function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { - let instanceCalls: arkts.CallExpression[] = []; - let leaf: arkts.CallExpression = node; - - while ( - true && - arkts.isMemberExpression(leaf.expression) && - arkts.isIdentifier(leaf.expression.property) && - arkts.isCallExpression(leaf.expression.object) - ) { - instanceCalls.push(arkts.factory.createCallExpression(leaf.expression.property, undefined, leaf.arguments)); - leaf = leaf.expression.object; - } - - const replace: arkts.Identifier | arkts.MemberExpression | undefined = builderLambdaReplace(leaf); - const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(leaf); - if (!replace || !declInfo) { - return node; - } - let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; - if (instanceCalls.length > 0) { - instanceCalls = instanceCalls.reverse(); - lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); - instanceCalls.forEach((call) => { - if (!arkts.isIdentifier(call.expression)) { - throw new Error('call expression should be identifier'); - } - lambdaBody = factory.createStyleLambdaBody(lambdaBody!, call); - }); - } - const args: (arkts.AstNode | undefined)[] = generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, isExternal); - return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); -} - -function transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { - const func: arkts.ScriptFunction = node.scriptFunction; - const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); - const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); - const styleArg: arkts.ETSParameterExpression = factory.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall); - return factory.updateBuilderLambdaMethodDecl( - node, - styleArg, - removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), - replaceBuilderLambdaDeclMethodName(node.name.name) - ); -} - export class BuilderLambdaTransformer extends AbstractVisitor { - visitEachChild(node: arkts.AstNode): arkts.AstNode { - if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { - return node; - } - if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { - return node; - } - - return super.visitEachChild(node); + reset(): void { + super.reset(); } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - const node = this.visitEachChild(beforeChildren); - - if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { - const lambda = transformBuilderLambda(node, this.isExternal); - return lambda; + if (arkts.isCallExpression(beforeChildren) && isBuilderLambda(beforeChildren)) { + const lambda = factory.transformBuilderLambda(beforeChildren); + return this.visitEachChild(lambda); } - if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { - const lambda = transformBuilderLambdaMethodDecl(node); - return lambda; + if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren)) { + const lambda = factory.transformBuilderLambdaMethodDecl(beforeChildren); + return this.visitEachChild(lambda); } - + const node = this.visitEachChild(beforeChildren); return node; } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 5cf2d1240..02ef7fcc2 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -15,7 +15,20 @@ import * as arkts from '@koalaui/libarkts'; import { BuilderLambdaNames } from '../utils'; -import { annotation, backingField } from '../../common/arkts-utils'; +import { annotation, backingField, filterDefined, removeAnnotationByName } from '../../common/arkts-utils'; +import { + BuilderLambdaDeclInfo, + builderLambdaFunctionName, + builderLambdaMethodDeclType, + builderLambdaTypeName, + callIsGoodForBuilderLambda, + findBuilderLambdaDecl, + findBuilderLambdaDeclInfo, + isBuilderLambda, + isBuilderLambdaFunctionCall, + replaceBuilderLambdaDeclMethodName, +} from './utils'; +import { DecoratorNames } from '../property-translators/utils'; export class factory { /* @@ -66,7 +79,12 @@ export class factory { false ), undefined, - call.arguments + call.arguments.map((arg) => { + if (arkts.isArrowFunctionExpression(arg)) { + return this.processArgArrowFunction(arg); + } + return arg; + }) ); } @@ -159,4 +177,264 @@ export class factory { parameter.annotations = [annotation('memo')]; return parameter; } + + /** + * If a builder lambda's argument is an arrow function, + * then transform any builder lambda in the function body. + */ + static processArgArrowFunction(arg: arkts.ArrowFunctionExpression): arkts.ArrowFunctionExpression { + const func: arkts.ScriptFunction = arg.scriptFunction; + const updateFunc = arkts.factory.updateScriptFunction( + func, + !!func.body && arkts.isBlockStatement(func.body) + ? arkts.factory.updateBlock( + func.body, + func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st)) + ) + : undefined, + arkts.FunctionSignature.createFunctionSignature( + func.typeParams, + func.params, + func.returnTypeAnnotation, + false + ), + func.flags, + func.modifiers + ); + return arkts.factory.updateArrowFunction(arg, updateFunc); + } + + /** + * transform options argument in a builder lambda call. + */ + static processOptionsArg(arg: T, typeName: string): T { + let expr: arkts.ObjectExpression | undefined; + if (arkts.isTSAsExpression(arg) && !!arg.expr && arkts.isObjectExpression(arg.expr)) { + expr = arg.expr; + } else if (arkts.isObjectExpression(arg)) { + expr = arg; + } + + if (!expr) { + return arg; + } + + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); + const properties = expr.properties as arkts.Property[]; + properties.forEach((prop, index) => { + this.updateParameterPassingInLinkedProperties(prop, index, currentStructInfo, properties); + }); + const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( + expr, + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + properties, + false + ); + if (arkts.isTSAsExpression(arg)) { + return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst) as T; + } + return updatedExpr as T; + } + + /** + * update any `@Link` parameter passing to the custom-component child. + */ + static updateParameterPassingInLinkedProperties( + prop: arkts.Property, + index: number, + currentStructInfo: arkts.StructInfo, + properties: arkts.Property[] + ): void { + if ( + !!prop.key && + !!prop.value && + arkts.isIdentifier(prop.key) && + arkts.isMemberExpression(prop.value) && + arkts.isThisExpression(prop.value.object) && + arkts.isIdentifier(prop.value.property) + ) { + const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; + if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { + properties[index] = arkts.Property.updateProperty( + prop, + arkts.factory.createIdentifier(backingField(prop.key.name)), + this.updateBackingMember(prop.value, prop.value.property.name) + ); + } + } + } + + /** + * create or update arguments in a builder lambda call. + * If the corresponding argument is not provided, fill-in an `undefined` to it. + */ + static createOrUpdateArgInBuilderLambda( + arg: arkts.Expression | undefined, + typeName?: string, + fallback?: arkts.AstNode + ): arkts.AstNode { + if (!arg) { + return fallback ?? arkts.factory.createUndefinedLiteral(); + } + if (arkts.isArrowFunctionExpression(arg)) { + return this.processArgArrowFunction(arg); + } + // this is too optimistic to check if this is an options argument... + if (arkts.isTSAsExpression(arg) || arkts.isObjectExpression(arg)) { + return this.processOptionsArg(arg, typeName!); + } + return arg; + } + + /** + * transform arguments in a builder lambda call. + */ + static generateArgsInBuilderLambda( + leaf: arkts.CallExpression, + lambdaBody: arkts.Identifier | arkts.CallExpression, + declInfo: BuilderLambdaDeclInfo + ): (arkts.AstNode | undefined)[] { + const { params, returnType } = declInfo; + const typeName: string | undefined = builderLambdaTypeName(leaf); + const args: (arkts.AstNode | undefined)[] = [this.createStyleArgInBuilderLambda(lambdaBody, returnType)]; + let index = 0; + while (index < params.length) { + const isReusable: boolean = typeName + ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable + : false; + if (isReusable && index === params.length - 1) { + const reuseId = arkts.factory.createStringLiteral(typeName!); + args.push(this.createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), typeName, reuseId)); + } else { + args.push(this.createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), typeName)); + } + index++; + } + return args; + } + + /** + * update if-else in trailing lambda contents in a builder lambda call. + */ + static updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode): arkts.AstNode { + if (arkts.isIfStatement(statement)) { + const alternate = !!statement.alternate + ? this.updateIfElseContentBodyInBuilderLambda(statement.alternate) + : statement.alternate; + const consequence = this.updateIfElseContentBodyInBuilderLambda(statement.consequent); + return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); + } + if (arkts.isBlockStatement(statement)) { + return arkts.factory.updateBlock( + statement, + statement.statements.map((st) => this.updateContentBodyInBuilderLambda(st)) + ); + } + return statement; + } + + /** + * update trailing lambda contents in a builder lambda call. + */ + static updateContentBodyInBuilderLambda(statement: arkts.Statement): arkts.Statement { + if ( + arkts.isExpressionStatement(statement) && + arkts.isCallExpression(statement.expression) && + isBuilderLambda(statement.expression) + ) { + return arkts.factory.updateExpressionStatement( + statement, + this.transformBuilderLambda(statement.expression) + ); + } + + if (arkts.isIfStatement(statement)) { + return this.updateIfElseContentBodyInBuilderLambda(statement); + } + + return statement; + } + + /** + * replace function call's name to the corresponding transformed name. + */ + static builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { + if (!callIsGoodForBuilderLambda(leaf)) { + return undefined; + } + const node = leaf.expression; + const funcName = builderLambdaFunctionName(leaf); + if (!funcName) { + return undefined; + } + if (arkts.isIdentifier(node)) { + return arkts.factory.createIdentifier(funcName); + } + if (arkts.isMemberExpression(node)) { + return arkts.factory.createMemberExpression( + node.object, + arkts.factory.createIdentifier(funcName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + node.computed, + node.optional + ); + } + return undefined; + } + + /** + * transform `@ComponentBuilder` in declared methods. + */ + static transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { + const func: arkts.ScriptFunction = node.scriptFunction; + const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); + const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); + const styleArg: arkts.ETSParameterExpression = this.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall); + return this.updateBuilderLambdaMethodDecl( + node, + styleArg, + removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), + replaceBuilderLambdaDeclMethodName(node.name.name) + ); + } + + /** + * transform `@ComponentBuilder` in non-declared calls. + */ + static transformBuilderLambda(node: arkts.CallExpression): arkts.AstNode { + let instanceCalls: arkts.CallExpression[] = []; + let leaf: arkts.CallExpression = node; + + while ( + arkts.isMemberExpression(leaf.expression) && + arkts.isIdentifier(leaf.expression.property) && + arkts.isCallExpression(leaf.expression.object) + ) { + instanceCalls.push(arkts.factory.createCallExpression(leaf.expression.property, undefined, leaf.arguments)); + leaf = leaf.expression.object; + } + + const decl: arkts.AstNode | undefined = findBuilderLambdaDecl(leaf); + if (!decl) { + return node; + } + + const replace: arkts.Identifier | arkts.MemberExpression | undefined = this.builderLambdaReplace(leaf); + const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(decl); + if (!replace || !declInfo) { + return node; + } + + let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; + if (instanceCalls.length > 0) { + instanceCalls = instanceCalls.reverse(); + lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); + instanceCalls.forEach((call) => { + lambdaBody = this.createStyleLambdaBody(lambdaBody!, call); + }); + } + + const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo); + return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); + } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index b31f6e284..0f3f2fa92 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -20,6 +20,7 @@ import { BuilderLambdaNames } from '../utils'; export type BuilderLambdaDeclInfo = { isFunctionCall: boolean; // isFunctionCall means it is from $_instantiate. params: readonly arkts.Expression[]; + returnType: arkts.TypeNode | undefined; }; export type BuilderLambdaAstNode = arkts.ScriptFunction | arkts.ETSParameterExpression | arkts.FunctionDeclaration; @@ -225,15 +226,16 @@ export function isParameterPassing(prop: arkts.Property): boolean | undefined { ); } -export function findBuilderLambdaDeclInfo(node: arkts.CallExpression): BuilderLambdaDeclInfo | undefined { - const decl = findBuilderLambdaDecl(node); +export function findBuilderLambdaDeclInfo(decl: arkts.AstNode | undefined): BuilderLambdaDeclInfo | undefined { if (!decl) { return undefined; } + if (arkts.isMethodDefinition(decl)) { const params = decl.scriptFunction.params.map((p) => p.clone()); + const returnType = decl.scriptFunction.returnTypeAnnotation?.clone(); const isFunctionCall = isBuilderLambdaFunctionCall(decl); - return { isFunctionCall, params }; + return { isFunctionCall, params, returnType }; } return undefined; diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index e713e6be5..8a50df19b 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -20,7 +20,7 @@ import { factory as builderLambdaFactory } from './builder-lambda-translators/fa import { factory as uiFactory } from './ui-factory'; import { factory as entryFactory } from './entry-translators/factory'; import { AbstractVisitor } from '../common/abstract-visitor'; -import { annotation, collect, filterDefined, removeAnnotationByName, backingField } from '../common/arkts-utils'; +import { annotation, collect, filterDefined } from '../common/arkts-utils'; import { CustomComponentNames, getCustomComponentOptionsName, @@ -37,19 +37,7 @@ import { isEtsGlobalClass, isReourceNode, } from './struct-translators/utils'; -import { - isBuilderLambda, - isBuilderLambdaMethodDecl, - isBuilderLambdaFunctionCall, - builderLambdaMethodDeclType, - replaceBuilderLambdaDeclMethodName, - findBuilderLambdaDeclInfo, - callIsGoodForBuilderLambda, - builderLambdaFunctionName, - BuilderLambdaDeclInfo, - builderLambdaType, - builderLambdaTypeName, -} from './builder-lambda-translators/utils'; +import { isBuilderLambda, isBuilderLambdaMethodDecl } from './builder-lambda-translators/utils'; import { isEntryWrapperClass } from './entry-translators/utils'; import { classifyObservedTrack, classifyProperty, PropertyTranslator } from './property-translators'; import { ObservedTrackTranslator } from './property-translators/observedTrack'; @@ -91,11 +79,11 @@ export class CheckedTransformer extends AbstractVisitor { visitor(beforeChildren: arkts.AstNode): arkts.AstNode { this.enter(beforeChildren); - if (arkts.isCallExpression(beforeChildren) && isBuilderLambda(beforeChildren, this.isExternal)) { - const lambda = transformBuilderLambda(beforeChildren, this.isExternal); + if (arkts.isCallExpression(beforeChildren) && isBuilderLambda(beforeChildren)) { + const lambda = builderLambdaFactory.transformBuilderLambda(beforeChildren); return this.visitEachChild(lambda); - } else if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren, this.isExternal)) { - const lambda = transformBuilderLambdaMethodDecl(beforeChildren); + } else if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren)) { + const lambda = builderLambdaFactory.transformBuilderLambdaMethodDecl(beforeChildren); return this.visitEachChild(lambda); } const node = this.visitEachChild(beforeChildren); @@ -337,6 +325,9 @@ function thisSubscribedWatchesMember(member: string): arkts.MemberExpression { ); } +/** + * @deprecated + */ function tranformClassMembers( node: arkts.ClassDeclaration, isDecl?: boolean, @@ -382,6 +373,9 @@ function tranformClassMembers( return arkts.factory.updateClassDeclaration(node, updateClassDef); } +/** + * @deprecated + */ function transformOtherMembersInClass( member: arkts.AstNode, classTypeName: string | undefined, @@ -411,6 +405,9 @@ function transformOtherMembersInClass( return member; } +/** + * @deprecated + */ function tranformPropertyMembers( className: string, propertyTranslators: PropertyTranslator[], @@ -433,22 +430,9 @@ function tranformPropertyMembers( return collect(...collections, ...propertyMembers); } -function transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { - const func: arkts.ScriptFunction = node.scriptFunction; - const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); - const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); - const styleArg: arkts.ETSParameterExpression = builderLambdaFactory.createStyleArgInBuilderLambdaDecl( - typeNode, - isFunctionCall - ); - return builderLambdaFactory.updateBuilderLambdaMethodDecl( - node, - styleArg, - removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), - replaceBuilderLambdaDeclMethodName(node.name.name) - ); -} - +/** + * @deprecated + */ function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.ClassDeclaration { if (!node.definition) { return node; @@ -462,6 +446,9 @@ function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.Cla return node; } +/** + * @deprecated + */ function transformResource( resourceNode: arkts.CallExpression, projectConfig: ProjectConfig | undefined @@ -473,204 +460,3 @@ function transformResource( ]; return structFactory.generateTransformedResource(resourceNode, newArgs); } - -function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { - let instanceCalls: arkts.CallExpression[] = []; - let leaf: arkts.CallExpression = node; - - while ( - true && - arkts.isMemberExpression(leaf.expression) && - arkts.isIdentifier(leaf.expression.property) && - arkts.isCallExpression(leaf.expression.object) - ) { - instanceCalls.push(arkts.factory.createCallExpression(leaf.expression.property, undefined, leaf.arguments)); - leaf = leaf.expression.object; - } - - const replace: arkts.Identifier | arkts.MemberExpression | undefined = builderLambdaReplace(leaf); - const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(leaf); - if (!replace || !declInfo) { - return node; - } - let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; - if (instanceCalls.length > 0) { - instanceCalls = instanceCalls.reverse(); - lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); - instanceCalls.forEach((call) => { - if (!arkts.isIdentifier(call.expression)) { - throw new Error('call expression should be identifier'); - } - lambdaBody = builderLambdaFactory.createStyleLambdaBody(lambdaBody!, call); - }); - } - const args: (arkts.AstNode | undefined)[] = generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, isExternal); - return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); -} - -function builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { - if (!callIsGoodForBuilderLambda(leaf)) { - return undefined; - } - const node = leaf.expression; - const funcName = builderLambdaFunctionName(leaf); - if (!funcName) { - return undefined; - } - if (arkts.isIdentifier(node)) { - return arkts.factory.createIdentifier(funcName); - } - if (arkts.isMemberExpression(node)) { - return arkts.factory.createMemberExpression( - node.object, - arkts.factory.createIdentifier(funcName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - node.computed, - node.optional - ); - } - return undefined; -} - -function generateArgsInBuilderLambda( - leaf: arkts.CallExpression, - lambdaBody: arkts.Identifier | arkts.CallExpression, - declInfo: BuilderLambdaDeclInfo, - isExternal?: boolean -): (arkts.AstNode | undefined)[] { - const { params } = declInfo; - const typeNode: arkts.TypeNode | undefined = builderLambdaType(leaf); - const typeName: string | undefined = builderLambdaTypeName(leaf); - const args: (arkts.AstNode | undefined)[] = [ - builderLambdaFactory.createStyleArgInBuilderLambda(lambdaBody, typeNode), - ]; - let index = 0; - while (index < params.length) { - const isReusable: boolean = typeName - ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable - : false; - if (isReusable && index === params.length - 1) { - const reuseId = arkts.factory.createStringLiteral(typeName!); - args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName, reuseId)); - } else { - args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName)); - } - index++; - } - return args; -} - -function createOrUpdateArgInBuilderLambda( - arg: arkts.Expression | undefined, - isExternal?: boolean, - typeName?: string, - fallback?: arkts.AstNode -): arkts.AstNode { - if (!arg) { - return fallback ?? arkts.factory.createUndefinedLiteral(); - } - if (arkts.isArrowFunctionExpression(arg)) { - return processArgArrowFunction(arg, isExternal); - } - if (arkts.isTSAsExpression(arg)) { - return processArgTSAsExpression(arg, typeName!); - } - return arg; -} - -function processArgArrowFunction( - arg: arkts.ArrowFunctionExpression, - isExternal?: boolean -): arkts.ArrowFunctionExpression { - const func: arkts.ScriptFunction = arg.scriptFunction; - const updateFunc = arkts.factory.updateScriptFunction( - func, - !!func.body && arkts.isBlockStatement(func.body) - ? arkts.factory.updateBlock( - func.body, - func.body.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) - ) - : undefined, - arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), - func.flags, - func.modifiers - ); - return arkts.factory.updateArrowFunction(arg, updateFunc); -} - -function processArgTSAsExpression(arg: arkts.TSAsExpression, typeName: string): arkts.TSAsExpression { - if (!arg.expr || !arkts.isObjectExpression(arg.expr)) { - return arg; - } - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); - const properties = arg.expr.properties as arkts.Property[]; - properties.forEach((prop, index) => { - updateParameterPassing(prop, index, currentStructInfo, properties); - }); - const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( - arg.expr, - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - properties, - false - ); - return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); -} - -function updateContentBodyInBuilderLambda(statement: arkts.Statement, isExternal?: boolean): arkts.Statement { - if ( - arkts.isExpressionStatement(statement) && - arkts.isCallExpression(statement.expression) && - isBuilderLambda(statement.expression, isExternal) - ) { - return arkts.factory.updateExpressionStatement(statement, transformBuilderLambda(statement.expression)); - } - // TODO: very time-consuming... - if (arkts.isIfStatement(statement)) { - return updateIfElseContentBodyInBuilderLambda(statement, isExternal); - } - - return statement; -} - -function updateParameterPassing( - prop: arkts.Property, - index: number, - currentStructInfo: arkts.StructInfo, - properties: arkts.Property[] -): void { - if ( - prop.key && - prop.value && - arkts.isIdentifier(prop.key) && - arkts.isMemberExpression(prop.value) && - arkts.isThisExpression(prop.value.object) && - arkts.isIdentifier(prop.value.property) - ) { - const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; - if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { - properties[index] = arkts.Property.updateProperty( - prop, - arkts.factory.createIdentifier(backingField(prop.key.name)), - builderLambdaFactory.updateBackingMember(prop.value, prop.value.property.name) - ); - } - } -} - -// TODO: very time-consuming... -function updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, isExternal?: boolean): arkts.AstNode { - if (arkts.isIfStatement(statement)) { - const alternate = !!statement.alternate - ? updateIfElseContentBodyInBuilderLambda(statement.alternate, isExternal) - : statement.alternate; - const consequence = updateIfElseContentBodyInBuilderLambda(statement.consequent, isExternal); - return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); - } - if (arkts.isBlockStatement(statement)) { - return arkts.factory.updateBlock( - statement, - statement.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) - ); - } - return statement; -} -- Gitee From b5451eaaef3ac65ff432d743db559aed10c431b8 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 16 Apr 2025 11:07:06 +0800 Subject: [PATCH 063/123] enable builder lambda transform arrow functions in chain expression Signed-off-by: Jiakai Shi Change-Id: I1cfd34c7d19761adccc7a7ef8af05b35d19953aa --- arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 02ef7fcc2..8f54d216e 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -347,7 +347,6 @@ export class factory { this.transformBuilderLambda(statement.expression) ); } - if (arkts.isIfStatement(statement)) { return this.updateIfElseContentBodyInBuilderLambda(statement); } -- Gitee From fa26d8810bd830be272a6d67f305dbc86419e846 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Fri, 18 Apr 2025 14:40:06 +0800 Subject: [PATCH 064/123] enable builder-lambda overloads transform Signed-off-by: Jiakai Shi Change-Id: I9033566cf6b19e6ebdb17066a9a62b974ee643f6 --- .../ui-plugins/builder-lambda-translators/factory.ts | 10 +++++++--- arkui-plugins/ui-plugins/preprocessor-transform.ts | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 8f54d216e..e80906d2d 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -39,7 +39,7 @@ export class factory { styleArg: arkts.ETSParameterExpression, newAnno: arkts.AnnotationUsage[], newName: string | undefined - ): arkts.AstNode { + ): arkts.MethodDefinition { const func: arkts.ScriptFunction = node.scriptFunction; const updateFunc = arkts.factory .updateScriptFunction( @@ -384,17 +384,21 @@ export class factory { /** * transform `@ComponentBuilder` in declared methods. */ - static transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { + static transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.MethodDefinition { const func: arkts.ScriptFunction = node.scriptFunction; const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); const styleArg: arkts.ETSParameterExpression = this.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall); + const newOverloads: arkts.MethodDefinition[] = node.overloads.map((method) => + factory.transformBuilderLambdaMethodDecl(method) + ); + return this.updateBuilderLambdaMethodDecl( node, styleArg, removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), replaceBuilderLambdaDeclMethodName(node.name.name) - ); + ).setOverloads(newOverloads); } /** diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 394b2327b..cfc3e8b9a 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -180,7 +180,7 @@ export class PreprocessorTransformer extends AbstractVisitor { const importName: string = node.imported.name; const sourceName: string = source.str; if (this.nameCollector.getComponents().includes(importName) && sourceName === ARKUI_COMPONENT_IMPORT_NAME) { - const newDependencies = [`${importName}Attribute`]; + const newDependencies = [`UI${importName}Attribute`]; this.updateOutDependencyMap(importName, newDependencies); this.updateSourceDependencyMap(sourceName, newDependencies); } -- Gitee From 0d68dabc3a79c1011d6a8f14854c5e4f129d5135 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Thu, 24 Apr 2025 10:13:17 +0800 Subject: [PATCH 065/123] fix memo scope is not exiting correctly Signed-off-by: Jiakai Shi Change-Id: Ica02686702da48fc6f2dccfbaeb5332d930276d4 --- .../memo-plugins/function-transformer.ts | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 7de7c86dd..9c4027dd4 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -334,15 +334,19 @@ export class FunctionTransformer extends AbstractVisitor { ]); } - private udpateAnonymousMemoCall( + private updateAnonymousMemoCall( node: arkts.CallExpression, expression: arkts.ArrowFunctionExpression ): arkts.CallExpression { const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== expression.scriptFunction.id?.name) { + const isValidScope = !!scope && scope.name === expression.scriptFunction.id?.name; + if (!isValidScope) { return node; } this.exitAnonymousScope(); + if (!scope.isMemo) { + return node; + } this.checkMemoCallInFunction(); this.enterAnonymousScope(expression.scriptFunction); @@ -372,17 +376,21 @@ export class FunctionTransformer extends AbstractVisitor { return this.updateDeclaredMemoCall(node, decl); } if (isStandaloneArrowFunction(node.expression)) { - return this.udpateAnonymousMemoCall(node, node.expression); + return this.updateAnonymousMemoCall(node, node.expression); } return node; } private updateClassProperty(node: arkts.ClassProperty, key: arkts.Identifier): arkts.ClassProperty { const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== key.name) { + const isValidScope = !!scope && scope.name === key.name; + if (!isValidScope) { return node; } this.exitAnonymousScope(); + if (!scope.isMemo) { + return node; + } let res: arkts.ScriptFunction | undefined; if (!!node.value && arkts.isArrowFunctionExpression(node.value)) { @@ -409,10 +417,14 @@ export class FunctionTransformer extends AbstractVisitor { private updateTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration): arkts.TSTypeAliasDeclaration { const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.id?.name) { + const isValidScope = !!scope && scope.name === node.id?.name; + if (!isValidScope) { return node; } this.exitAnonymousScope(); + if (!scope.isMemo) { + return node; + } let typeAnnotation: arkts.TypeNode | undefined; if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { @@ -425,10 +437,14 @@ export class FunctionTransformer extends AbstractVisitor { private updateStandaloneArrowFunction(node: arkts.ArrowFunctionExpression): arkts.ArrowFunctionExpression { const scope = this.scopes[this.scopes.length - 1]; - if (!scope || !scope.isMemo || scope.name !== node.scriptFunction.id?.name) { + const isValidScope = !!scope && scope.name === node.scriptFunction.id?.name; + if (!isValidScope) { return node; } this.exitAnonymousScope(); + if (!scope.isMemo) { + return node; + } this.enterAnonymousScope(node.scriptFunction); const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); -- Gitee From fa35f96634bbe699272fef4f9fb687bbcc41027e Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Tue, 22 Apr 2025 21:37:48 +0800 Subject: [PATCH 066/123] enable plugin tester Signed-off-by: Jiakai Shi Change-Id: I99aae8f615cb2b730a7d6a966da62348c3566a5f --- ...est-test.config.ts => jest-test.config.js} | 15 ++-- arkui-plugins/package.json | 3 +- .../{instantiate.ets => simple-component.ets} | 11 ++- .../mock/memo/functions/void-return-type.ets | 21 +++++ arkui-plugins/test/package.json | 6 +- .../test/ut/common/annotation.test.ts | 12 --- .../void-return-type.test.ts | 62 +++++++++++++ .../builder-lambda/simple-component.test.ts | 87 +++++++++++++++++++ arkui-plugins/test/utils/artkts-config.ts | 38 +++++--- arkui-plugins/test/utils/cache.ts | 59 +++++++++++++ arkui-plugins/test/utils/compile.ts | 4 - arkui-plugins/test/utils/global.ts | 14 ++- arkui-plugins/test/utils/parse-string.ts | 15 +++- arkui-plugins/test/utils/plugin-tester.ts | 68 +++++++++++---- .../plugins/builder-lambda-no-recheck.ts | 48 ++++++++++ arkui-plugins/test/utils/plugins/index.ts | 24 +++++ .../test/utils/plugins/memo-no-recheck.ts | 60 +++++++++++++ arkui-plugins/test/utils/plugins/recheck.ts | 35 ++++++++ .../test/utils/plugins/struct-no-recheck.ts | 48 ++++++++++ .../test/utils/plugins/struct-to-component.ts | 47 ++++++++++ .../test/utils/plugins/ui-no-recheck.ts | 48 ++++++++++ arkui-plugins/tsconfig.json | 3 +- 22 files changed, 658 insertions(+), 70 deletions(-) rename arkui-plugins/{jest-test.config.ts => jest-test.config.js} (86%) rename arkui-plugins/test/demo/mock/builder-lambda/{instantiate.ets => simple-component.ets} (73%) create mode 100644 arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets create mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts create mode 100644 arkui-plugins/test/utils/cache.ts create mode 100644 arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts create mode 100644 arkui-plugins/test/utils/plugins/index.ts create mode 100644 arkui-plugins/test/utils/plugins/memo-no-recheck.ts create mode 100644 arkui-plugins/test/utils/plugins/recheck.ts create mode 100644 arkui-plugins/test/utils/plugins/struct-no-recheck.ts create mode 100644 arkui-plugins/test/utils/plugins/struct-to-component.ts create mode 100644 arkui-plugins/test/utils/plugins/ui-no-recheck.ts diff --git a/arkui-plugins/jest-test.config.ts b/arkui-plugins/jest-test.config.js similarity index 86% rename from arkui-plugins/jest-test.config.ts rename to arkui-plugins/jest-test.config.js index 8fe8cb301..4094af6dd 100644 --- a/arkui-plugins/jest-test.config.ts +++ b/arkui-plugins/jest-test.config.js @@ -13,19 +13,17 @@ * limitations under the License. */ - -import * as path from 'path'; +const path = require('path'); const rootPath = path.resolve(__dirname, '../../../'); - const sdkPath = path.resolve(rootPath, './out/sdk/ohos-sdk/linux/ets/ets1.2'); - const pandaSdkPath = path.resolve(sdkPath, './build-tools/ets2panda'); +const apiPath = path.resolve(sdkPath, './api'); module.exports = { testEnvironment: 'node', transform: { - '^.+\\.ts$': ['ts-jest', { isolatedModules: true }], + '^.+\\.ts$': ['ts-jest'], }, testRegex: './test/ut/.+\\.test\\.ts$', moduleFileExtensions: ['ts', 'js', 'json', 'node'], @@ -34,6 +32,7 @@ module.exports = { verbose: true, globals: { SDK_PATH: sdkPath, - PANDA_SDK_PATH: pandaSdkPath - } -}; + PANDA_SDK_PATH: pandaSdkPath, + API_PATH: apiPath, + }, +}; diff --git a/arkui-plugins/package.json b/arkui-plugins/package.json index 1b839b9a6..b82e4b40f 100644 --- a/arkui-plugins/package.json +++ b/arkui-plugins/package.json @@ -10,7 +10,8 @@ "local:install": "chmod 777 ./npm_preinstall.sh && ./npm_preinstall.sh --init", "compile:plugins": "./node_modules/.bin/babel . --out-dir lib --extensions .ts", "compile:clean": "rm -rf lib", - "test": "LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib jest --config ./jest-test.config.ts", + "prepare:test": "cp -rf $INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/koala-wrapper/build/native/ ../koala-wrapper/build/", + "test": "npm run prepare:test && LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib jest --config ./jest-test.config.js --silent", "compile": "npm run compile:clean && npm run compile:plugins && cp -rf ./lib $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/" }, "devDependencies": { diff --git a/arkui-plugins/test/demo/mock/builder-lambda/instantiate.ets b/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets similarity index 73% rename from arkui-plugins/test/demo/mock/builder-lambda/instantiate.ets rename to arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets index 1b05c1e8a..86801284d 100644 --- a/arkui-plugins/test/demo/mock/builder-lambda/instantiate.ets +++ b/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets @@ -13,12 +13,11 @@ * limitations under the License. */ -import { Component } from "@koalaui.arkts-arkui.Common" -import { Column } from "@koalaui.arkts-arkui.Column" +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { Column, ColumnAttribute } from "@ohos.arkui.component" -@Component -struct MyStateSample { - build() { - Column() {} +class MyStateSample { + @memo build() { + Column(undefined) {} } } \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets b/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets new file mode 100644 index 000000000..7ac6d38e6 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo } from "@ohos.arkui.stateManagement" + +@memo +function func(): void { + return; +} diff --git a/arkui-plugins/test/package.json b/arkui-plugins/test/package.json index 51154bd39..07123fbd7 100644 --- a/arkui-plugins/test/package.json +++ b/arkui-plugins/test/package.json @@ -6,7 +6,11 @@ "scripts": { "compile:ohos": "node $INIT_CWD/../../../../arkcompiler/ets_frontend/ets2panda/driver/build-system/dist/entry.js ./demo/hello_world/build_config.json", "compile:gdb": "gdb --args node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/hello_world/build_config.json", - "compile:plugins": "npm run compile --prefix .. ", + "compile:plugins": "npm run compile --prefix ..", + "clean:localtest": "rm -rf dist", + "clean:test": "rm -rf generated", + "clean:all": "npm run clean:localtest && npm run clean:test", + "test": "npm run clean:all && npm run compile:plugins && cd .. && npm run test", "localtest": "rm -rf dist && node localtest_config.js && npm run compile:plugins && LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_config.json", "localtest_gdb": "LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib gdb --args node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_config.json", "localtest_decl": "rm -rf dist && node localtest_decl_config.js && npm run compile:plugins && LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_decl_config.json", diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index 81ef35c26..cf9f7d191 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -34,17 +34,5 @@ pluginTester.run( }, { stopAfter: 'checked', - }, - { - beforeEach: [ - () => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - }, - ], - afterEach: [ - () => { - jest.spyOn(console, 'warn').mockRestore(); - }, - ], } ); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts new file mode 100644 index 000000000..72555dd78 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const FUNCTION_DIR_PATH: string = 'memo/functions'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'void-return-type.ets'), +]; + +const pluginTester = new PluginTester('test memo function', buildConfig); + +function testMemoTransformer(this: PluginTestContext): void { + const expectedScript: string = ` +import { memo as memo } from \"@ohos.arkui.stateManagement\"; + +function main() {} + +function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + (7245993)), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } +} +`; + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform functions with void return type', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts new file mode 100644 index 000000000..3c8f13a7d --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { builderLambdaNoRecheck, memoNoRecheck, recheck } from '../../../utils/plugins'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'builder-lambda'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'simple-component.ets'), +]; + +const pluginTester = new PluginTester('test builder-lambda simple component', buildConfig); + +function testBuilderLambdaTransformer(this: PluginTestContext): void { + const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { Column as Column, ColumnAttribute as ColumnAttribute } from \"@ohos.arkui.component\"; +function main() {} +class MyStateSample { + @memo() public build() { + Column(undefined, undefined, (() => {})); + } + public constructor() {} +} +`; + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +function testMemoTransformer(this: PluginTestContext): void { + const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { Column as Column, ColumnAttribute as ColumnAttribute } from \"@ohos.arkui.component\"; +function main() {} +class MyStateSample { + public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type) { + const __memo_scope = __memo_context.scope(((__memo_id) + (263357132)), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + Column(__memo_context, ((__memo_id) + (65509320)), undefined, undefined, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { + const __memo_scope = __memo_context.scope(((__memo_id) + (147296800)), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + })); + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform simple component', + [builderLambdaNoRecheck, recheck, memoNoRecheck], + { + 'checked:builder-lambda-no-recheck': [testBuilderLambdaTransformer], + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index f741bd104..3474c59a2 100644 --- a/arkui-plugins/test/utils/artkts-config.ts +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -173,6 +173,29 @@ function traverse(currentDir: string, pathSection: Record) { } } +function traverseSDK(currentDir: string, pathSection: Record, prefix?: string) { + const items = fs.readdirSync(currentDir); + + for (const item of items) { + const itemPath = path.join(currentDir, item); + const stat = fs.statSync(itemPath); + + if (stat.isFile() && !itemPath.endsWith('.d.ets')) { + continue; + } + + if (stat.isFile() && itemPath.endsWith('.d.ets')) { + const basename = path.basename(item, '.d.ets'); + const name = prefix && prefix !== 'arkui.runtime-api' ? `${prefix}.${basename}` : basename; + pathSection[name] = [changeFileExtension(itemPath, '', '.d.ets')]; + } else if (stat.isDirectory()) { + const basename = path.basename(itemPath); + const name = prefix && prefix !== 'arkui.runtime-api' ? `${prefix}.${basename}` : basename; + traverseSDK(itemPath, pathSection, name); + } + } +} + function mockBuildConfig(): BuildConfig { return { packageName: 'mock', @@ -180,19 +203,10 @@ function mockBuildConfig(): BuildConfig { loaderOutPath: path.resolve(getRootPath(), MOCK_OUTPUT_DIR_PATH), cachePath: path.resolve(getRootPath(), MOCK_OUTPUT_CACHE_PATH), pandaSdkPath: global.PANDA_SDK_PATH, - buildSdkPath: path.resolve(getRootPath(), MOCK_LOCAL_SDK_DIR_PATH), + buildSdkPath: global.API_PATH, sourceRoots: [getRootPath()], moduleRootPath: path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH), - dependentModuleList: [ - { - packageName: '@koalaui/runtime', - moduleName: '@koalaui/runtime', - moduleType: 'har', - modulePath: path.resolve(getRootPath(), RUNTIME_API_PATH), - sourceRoots: ['./'], - entryFile: 'index.sts', - }, - ], + dependentModuleList: [], }; } @@ -293,7 +307,7 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { const pathSection: Record = {}; pathSection['std'] = [path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_STD_PATH)]; pathSection['escompat'] = [path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_ESCOMPAT_PATH)]; - traverse(this.buildSdkPath, pathSection); + traverseSDK(this.buildSdkPath, pathSection); this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { pathSection[moduleInfo.packageName] = [path.resolve(moduleRootPath, moduleInfo.sourceRoots[0])]; diff --git a/arkui-plugins/test/utils/cache.ts b/arkui-plugins/test/utils/cache.ts new file mode 100644 index 000000000..b24fcdf64 --- /dev/null +++ b/arkui-plugins/test/utils/cache.ts @@ -0,0 +1,59 @@ +/* + * 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. + */ + +class TesterCache { + private cacheInfo: Map; + private static instance: TesterCache; + + private constructor() { + this.cacheInfo = new Map(); + } + + static getInstance(): TesterCache { + if (!this.instance) { + this.instance = new TesterCache(); + } + return this.instance; + } + + public delete(key: string) { + if (this.cacheInfo.has(key)) { + this.cacheInfo.delete(key); + } + } + + public get(key: string) { + if (this.cacheInfo.has(key)) { + return this.cacheInfo.get(key); + } + return undefined; + } + + public has(key: string) { + return this.cacheInfo.has(key); + } + + public set(key: string, value: T) { + if (!this.cacheInfo.has(key)) { + this.cacheInfo.set(key, value); + } + } + + public clear() { + this.cacheInfo.clear(); + } +} + +export { TesterCache }; diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index 7ba64a49e..f893dae3b 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -52,10 +52,6 @@ function insertPlugin( } if (plugin) { - pluginContext.setArkTSAst(ast); - if (arkts.arktsGlobal.compilerContext) { - pluginContext.setArkTSProgram(arkts.arktsGlobal.compilerContext.program); - } plugin.handler.apply(pluginContext); } return true; diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index df5e2794b..cbccd4afa 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -64,11 +64,19 @@ function resetConfig(cmd: string[]): void { } function destroyContext(): void { - arkts.arktsGlobal.es2panda._DestroyContext(arkts.arktsGlobal.context); + try { + arkts.arktsGlobal.clearContext(); + } catch (e) { + // Do nothing + } } function destroyConfig(): void { - arkts.destroyConfig(arkts.arktsGlobal.config); + try { + arkts.destroyConfig(arkts.arktsGlobal.config); + } catch (e) { + // Do nothing + } } function canProceedToState(state: arkts.Es2pandaContextState): boolean { @@ -87,4 +95,4 @@ function canProceedToState(state: arkts.Es2pandaContextState): boolean { return currState < state; } -export { initGlobal, resetContext, resetConfig, canProceedToState }; +export { initGlobal, resetContext, resetConfig, destroyContext, destroyConfig, canProceedToState }; diff --git a/arkui-plugins/test/utils/parse-string.ts b/arkui-plugins/test/utils/parse-string.ts index 58430ca1d..2db07c21f 100644 --- a/arkui-plugins/test/utils/parse-string.ts +++ b/arkui-plugins/test/utils/parse-string.ts @@ -14,9 +14,10 @@ */ function parseDumpSrc(str: string): string { - let _str: string = filterSource(str); + let _str: string = str; _str = cleanCopyRight(_str); _str = removeSpaceAndReturn(_str); + _str = replaceWithRandomNumber(_str); return _str; } @@ -28,7 +29,7 @@ function filterSource(text: string): string { } function cleanCopyRight(str: string): string { - const copyrightBlockRegex = /(?:\/\*.*Copyright \(c\) [- \d]+ Huawei Device Co\., Ltd\..*\*\/)/gs; + const copyrightBlockRegex = /(?:\/\*.*Copyright \([c|C]\) [- \d]+ [\w ]+\., Ltd\..*\*\/)/gs; return str.replace(copyrightBlockRegex, ''); } @@ -36,7 +37,13 @@ function cleanCopyRight(str: string): string { function removeSpaceAndReturn(str: string): string { const spaceAndReturnRegex = /^[\s\r]+/gm; - return str.replace(spaceAndReturnRegex, ''); + return str.replace(spaceAndReturnRegex, '').trim(); } -export { parseDumpSrc, filterSource, cleanCopyRight, removeSpaceAndReturn }; +function replaceWithRandomNumber(text: string): string { + return text + .replace(/(?<=__memo_id[\)+]?\s?\+\s?[\(+]?)\d+/g, () => '') + .replace(/(?<=gensym[_%]+)\d+/g, () => ''); +} + +export { parseDumpSrc, filterSource, cleanCopyRight, removeSpaceAndReturn, replaceWithRandomNumber }; diff --git a/arkui-plugins/test/utils/plugin-tester.ts b/arkui-plugins/test/utils/plugin-tester.ts index e68711063..710456e21 100644 --- a/arkui-plugins/test/utils/plugin-tester.ts +++ b/arkui-plugins/test/utils/plugin-tester.ts @@ -16,10 +16,19 @@ import { ArktsConfigBuilder, BuildConfig, CompileFileInfo, MockArktsConfigBuilder, ModuleInfo } from './artkts-config'; import { MockPluginDriver, PluginDriver, stateName } from './plugin-driver'; import { isNumber } from './safe-types'; -import { canProceedToState, initGlobal } from './global'; -import { insertPlugin, restartCompilerUptoState } from './compile'; +import { + canProceedToState, + destroyConfig, + destroyContext, + initGlobal, + resetConfig, + resetContext, +} from './global'; +import { insertPlugin } from './compile'; import { PluginExecutor, Plugins, PluginState } from '../../common/plugin-context'; +import { TesterCache } from './cache'; import * as arkts from '@koalaui/libarkts'; +import * as fs from 'fs'; type TestParams = Parameters; @@ -31,13 +40,12 @@ type PluginTestHooks = { type TestHooks = { beforeAll?: Parameters; - afterAll?: Parameters; beforeEach?: Parameters; afterEach?: Parameters; }; export interface PluginTestContext { - script?: arkts.AstNode; + scriptSnapshot?: string; errors?: string[]; warnings?: string[]; } @@ -51,12 +59,13 @@ class PluginTester { private configBuilder: ArktsConfigBuilder; private pluginDriver: PluginDriver; private describe: string; - private cache?: PluginTestContext; + private cache: TesterCache; constructor(describe: string, buildConfig?: BuildConfig) { this.describe = describe; this.configBuilder = new MockArktsConfigBuilder(buildConfig); this.pluginDriver = new MockPluginDriver(); + this.cache = TesterCache.getInstance(); } private loadPluginDriver(plugins: Plugins[]): void { @@ -70,9 +79,8 @@ class PluginTester { pluginHooks: PluginTestHooks, plugin?: PluginExecutor ): void { - if (!this.cache) { - this.cache = {}; - } + let cached: boolean = false; + const cacheKey: string = `${testName}-${key}`; if (index > arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) { return; } @@ -81,12 +89,25 @@ class PluginTester { } if (plugin) { insertPlugin(this.pluginDriver, plugin, index); - // TODO: add error/warning handling after plugin - this.cache.script = arkts.EtsScript.fromContext(); + this.captureContext(cacheKey); + cached = true; } const hook: SkipFirstParam | undefined = pluginHooks[key]; if (!!hook) { - test(testName, hook[0]?.bind(this.cache), hook[1]); + if (!cached) this.captureContext(cacheKey); + test(testName, hook[0]?.bind(this.cache.get(cacheKey)), hook[1]); + } + } + + private captureContext(cacheKey: string): void { + try { + // TODO: add error/warning handling after plugin + const context: PluginTestContext = this.cache.get(cacheKey) ?? {}; + const script: arkts.EtsScript = arkts.EtsScript.fromContext(); + context.scriptSnapshot = script.dumpSrc(); + this.cache.set(cacheKey, context); + } catch (e) { + // Do nothing } } @@ -116,12 +137,12 @@ class PluginTester { ): void { let shouldStop: boolean = false; - initGlobal(fileInfo, this.configBuilder.isDebug); - Object.values(arkts.Es2pandaContextState) .filter(isNumber) .forEach((it) => { - if (shouldStop) return; + if (shouldStop) { + return; + } const state: PluginState = stateName(it); const plugins: PluginExecutor[] | undefined = this.pluginDriver.getSortedPlugins(it); this.proceedToState( @@ -136,8 +157,16 @@ class PluginTester { } private traverseFile(testName: string, pluginHooks: PluginTestHooks, stopAfter: PluginState): void { + let once: boolean = false; this.configBuilder.moduleInfos.forEach((moduleInfo) => { moduleInfo.compileFileInfos.forEach((fileInfo) => { + if (!once) { + initGlobal(fileInfo, this.configBuilder.isDebug); + once = true; + } else { + const source: string = fs.readFileSync(fileInfo.filePath).toString(); + resetContext(source); + } this.singleFileCompile(fileInfo, moduleInfo, testName, pluginHooks, stopAfter); }); }); @@ -154,22 +183,25 @@ class PluginTester { this.configBuilder = new MockArktsConfigBuilder(options.buildConfig); } + this.cache.clear(); this.loadPluginDriver(plugins); + const that = this; describe(this.describe, () => { if (testHooks?.beforeAll) { beforeAll(...testHooks.beforeAll); } - if (testHooks?.afterAll) { - afterAll(...testHooks.afterAll); - } if (testHooks?.beforeEach) { beforeEach(...testHooks.beforeEach); } if (testHooks?.afterEach) { afterEach(...testHooks.afterEach); } - this.traverseFile(testName, pluginHooks, options.stopAfter); + afterAll(() => { + destroyContext(); + destroyConfig(); + }); + that.traverseFile(testName, pluginHooks, options.stopAfter); }); } } diff --git a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts new file mode 100644 index 000000000..69e2b23ad --- /dev/null +++ b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PluginContext, Plugins } from '../../../common/plugin-context'; +import { ProgramVisitor } from '../../../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; +import { BuilderLambdaTransformer } from '../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer'; + +/** + * AfterCheck builder-lambda transform with no recheck AST. + */ +export const builderLambdaNoRecheck: Plugins = { + name: 'builder-lambda-no-recheck', + checked(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + const builderLambdaTransformer = new BuilderLambdaTransformer(); + const programVisitor = new ProgramVisitor({ + pluginName: builderLambdaNoRecheck.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [builderLambdaTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); + script = program.astNode; + arkts.GlobalInfo.getInfoInstance().reset(); + return script; + } + return script; + }, +}; diff --git a/arkui-plugins/test/utils/plugins/index.ts b/arkui-plugins/test/utils/plugins/index.ts new file mode 100644 index 000000000..4858b84b2 --- /dev/null +++ b/arkui-plugins/test/utils/plugins/index.ts @@ -0,0 +1,24 @@ +/* + * 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. + */ + +// AfterParse +export * from './struct-to-component'; + +// AfterCheck +export * from './builder-lambda-no-recheck'; +export * from './memo-no-recheck'; +export * from './struct-no-recheck'; +export * from './ui-no-recheck'; +export * from './recheck'; diff --git a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts new file mode 100644 index 000000000..ff018cec5 --- /dev/null +++ b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PluginContext, Plugins } from '../../../common/plugin-context'; +import { ProgramVisitor } from '../../../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; +import { PositionalIdTracker } from '../../../memo-plugins/utils'; +import { ParameterTransformer } from '../../../memo-plugins/parameter-transformer'; +import { ReturnTransformer } from '../../../memo-plugins/return-transformer'; +import { SignatureTransformer } from '../../../memo-plugins/signature-transformer'; +import { FunctionTransformer } from '../../../memo-plugins/function-transformer'; + +/** + * AfterCheck unmemoizeTransform with no recheck AST. + */ +export const memoNoRecheck: Plugins = { + name: 'memo-no-recheck', + checked(this: PluginContext): arkts.EtsScript | undefined { + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + let script = program.astNode; + const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); + const parameterTransformer = new ParameterTransformer({ + positionalIdTracker, + }); + const returnTransformer = new ReturnTransformer(); + const signatureTransformer = new SignatureTransformer(); + const functionTransformer = new FunctionTransformer({ + positionalIdTracker, + parameterTransformer, + returnTransformer, + signatureTransformer, + }); + const programVisitor = new ProgramVisitor({ + pluginName: memoNoRecheck.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [functionTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); + script = program.astNode; + return script; + } + }, +}; diff --git a/arkui-plugins/test/utils/plugins/recheck.ts b/arkui-plugins/test/utils/plugins/recheck.ts new file mode 100644 index 000000000..085d3731e --- /dev/null +++ b/arkui-plugins/test/utils/plugins/recheck.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PluginContext, Plugins } from '../../../common/plugin-context'; + +/** + * Recheck the current AST. This plugin can ONLY be used at afterCheck. + */ +export const recheck: Plugins = { + name: 'recheck', + checked(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + arkts.recheckSubtree(script); + return script; + } + return script; + }, +}; diff --git a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts new file mode 100644 index 000000000..c564b71c7 --- /dev/null +++ b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PluginContext, Plugins } from '../../../common/plugin-context'; +import { ProgramVisitor } from '../../../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; +import { StructTransformer } from '../../../ui-plugins/struct-translators/struct-transformer'; + +/** + * AfterCheck struct transform with no recheck AST. + */ +export const structNoRecheck: Plugins = { + name: 'struct-no-recheck', + checked(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + const structTransformer = new StructTransformer(this.getProjectConfig()); + const programVisitor = new ProgramVisitor({ + pluginName: structNoRecheck.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [structTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); + script = program.astNode; + arkts.GlobalInfo.getInfoInstance().reset(); + return script; + } + return script; + }, +}; diff --git a/arkui-plugins/test/utils/plugins/struct-to-component.ts b/arkui-plugins/test/utils/plugins/struct-to-component.ts new file mode 100644 index 000000000..14d494c05 --- /dev/null +++ b/arkui-plugins/test/utils/plugins/struct-to-component.ts @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PluginContext, Plugins } from '../../../common/plugin-context'; +import { ProgramVisitor } from '../../../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; +import { ComponentTransformer } from '../../../ui-plugins/component-transformer'; + +/** + * AfterParse transform struct to component. + */ +export const structToComponent: Plugins = { + name: 'struct-to-component', + parsed(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + const componentTransformer = new ComponentTransformer(); + const programVisitor = new ProgramVisitor({ + pluginName: structToComponent.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + visitors: [componentTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); + script = program.astNode; + return script; + } + return script; + }, +}; diff --git a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts new file mode 100644 index 000000000..dec4b5296 --- /dev/null +++ b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PluginContext, Plugins } from '../../../common/plugin-context'; +import { ProgramVisitor } from '../../../common/program-visitor'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; +import { CheckedTransformer } from '../../../ui-plugins/checked-transformer'; + +/** + * AfterCheck uiTransform with no recheck AST. + */ +export const uiNoRecheck: Plugins = { + name: 'ui-no-recheck', + checked(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + script = program.astNode; + const checkedTransformer = new CheckedTransformer(this.getProjectConfig()); + const programVisitor = new ProgramVisitor({ + pluginName: uiNoRecheck.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [checkedTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); + script = program.astNode; + arkts.GlobalInfo.getInfoInstance().reset(); + return script; + } + return script; + }, +}; diff --git a/arkui-plugins/tsconfig.json b/arkui-plugins/tsconfig.json index eab872848..ad638506a 100644 --- a/arkui-plugins/tsconfig.json +++ b/arkui-plugins/tsconfig.json @@ -15,7 +15,8 @@ "noEmitOnError": true, "strict": true, "skipLibCheck": true, - "removeComments": false + "removeComments": false, + "isolatedModules": true }, "include": [ "./common/**/*.ts", -- Gitee From d5b2a1b8f59774953a78f320178a1c0fc90594ea Mon Sep 17 00:00:00 2001 From: y00896775 Date: Fri, 25 Apr 2025 15:51:14 +0800 Subject: [PATCH 067/123] modify link bug Signed-off-by: y00896775 Change-Id: I8b7f2db26479cfcd90536d2fb4bb10625c7dcb2f --- .../mock/decorators/link/link-basic-type.ets | 29 ++ .../decorators/link/link-complex-type.ets | 49 +++ .../link/link-to-link-prop-state.ets | 41 +++ .../mock/decorators/link/state-to-link.ets | 70 ++++ .../decorators/link/link-basic-type.test.ts | 151 +++++++++ .../decorators/link/link-complex-type.test.ts | 314 ++++++++++++++++++ .../link/link-to-link-prop-state.test.ts | 186 +++++++++++ .../decorators/link/state-to-link.test.ts | 175 ++++++++++ .../builder-lambda-translators/factory.ts | 6 +- 9 files changed, 1020 insertions(+), 1 deletion(-) create mode 100644 arkui-plugins/test/demo/mock/decorators/link/link-basic-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/link/link-complex-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/link/link-to-link-prop-state.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts diff --git a/arkui-plugins/test/demo/mock/decorators/link/link-basic-type.ets b/arkui-plugins/test/demo/mock/decorators/link/link-basic-type.ets new file mode 100644 index 000000000..9c97005bc --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/link/link-basic-type.ets @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { Link } from "@ohos.arkui.stateManagement" + +@Component +struct LinkParent { + @Link linkVar1: string; + @Link linkVar2: number; + @Link linkVar3: boolean; + @Link linkVar4: undefined; + @Link linkVar5: null; + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/link/link-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/link/link-complex-type.ets new file mode 100644 index 000000000..512968ab3 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/link/link-complex-type.ets @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { Link } from "@ohos.arkui.stateManagement" + +class Per { + num: number; + constructor(num: number) { + this.num = num; + } +} + +enum LinkType { + TYPE1 = 0, + TYPE2 = 1, + TYPE3 = 3 +} + +@Component +struct Parent { + @Link linkVar1: Per; + @Link linkVar2: Array; + @Link linkVar3: LinkType; + @Link linkVar4: Set; + @Link linkVar5: boolean[]; + @Link linkVar6: Array; + @Link linkVar7: Per[]; + @Link linkVar8: (sr: string)=>void; + @Link linkVar9: Date; + @Link linkVar10: Map; + @Link linkVar11: string | number; + @Link linkVar12: Set | Per; + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/link/link-to-link-prop-state.ets b/arkui-plugins/test/demo/mock/decorators/link/link-to-link-prop-state.ets new file mode 100644 index 000000000..b04d84e93 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/link/link-to-link-prop-state.ets @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Column, TextInput } from "@ohos.arkui.component" +import { Link, State, Prop } from "@ohos.arkui.stateManagement" + +@Component +struct Parant { + @Link text1: string; + + build() { + Column() { + TextInput({ text: this.text1 }) + Child({ childText: this.text1, childText2: this.text1, childText3: this.text1, childText4: this.text1 }) + } + } +} + +@Component +struct Child { + @Link childText: string; + @State childText2: string = 'sss'; + @Prop childText3: string; + @Prop childText4: string = 'cc'; + + build() { + TextInput({ text: this.childText }) + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets b/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets new file mode 100644 index 000000000..b2aaf247a --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Entry, Column, Button, DatePicker } from "@ohos.arkui.component" +import { Link, State } from "@ohos.arkui.stateManagement" + +@Component +struct DateComponent { + @Link selectedDate: Date; + + build() { + Column() { + Button('child increase the year by 1') + .onClick(() => { + this.selectedDate.setFullYear(this.selectedDate.getFullYear() + 1); + }) + Button('child update the new date') + .margin(10) + .onClick(() => { + this.selectedDate = new Date('2023-09-09'); + }) + DatePicker({ + start: new Date('1970-1-1'), + end: new Date('2100-1-1'), + selected: this.selectedDate + }) + } + + } +} + +@Entry +@Component +struct ParentComponent { + @State parentSelectedDate: Date = new Date('2021-08-08'); + + build() { + Column() { + Button('parent increase the month by 1') + .margin(10) + .onClick(() => { + this.parentSelectedDate.setMonth(this.parentSelectedDate.getMonth() + 1); + }) + Button('parent update the new date') + .margin(10) + .onClick(() => { + this.parentSelectedDate = new Date('2023-07-07'); + }) + DatePicker({ + start: new Date('1970-1-1'), + end: new Date('2100-1-1'), + selected: this.parentSelectedDate + }) + + DateComponent({ selectedDate:this.parentSelectedDate }) + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts new file mode 100644 index 000000000..5a798dab0 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/link'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'link-basic-type.ets'), +]; + +const pluginTester = new PluginTester('test basic type @Link decorated variables transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'link-basic-type', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { Link as Link } from "@ohos.arkui.stateManagement"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class LinkParent extends CustomComponent { + public __initializeStruct(initializers: __Options_LinkParent | undefined, @memo() content: (()=> void) | undefined): void { + if (({let gensym___11910109 = initializers; + (((gensym___11910109) == (null)) ? undefined : gensym___11910109.__backing_linkVar1)})) { + (this).__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); + }; + if (({let gensym___181684045 = initializers; + (((gensym___181684045) == (null)) ? undefined : gensym___181684045.__backing_linkVar2)})) { + (this).__backing_linkVar2 = new LinkDecoratedVariable("linkVar2", initializers!.__backing_linkVar2!); + }; + if (({let gensym___24446313 = initializers; + (((gensym___24446313) == (null)) ? undefined : gensym___24446313.__backing_linkVar3)})) { + (this).__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); + }; + if (({let gensym___167989826 = initializers; + (((gensym___167989826) == (null)) ? undefined : gensym___167989826.__backing_linkVar4)})) { + (this).__backing_linkVar4 = new LinkDecoratedVariable("linkVar4", initializers!.__backing_linkVar4!); + }; + if (({let gensym___157566097 = initializers; + (((gensym___157566097) == (null)) ? undefined : gensym___157566097.__backing_linkVar5)})) { + (this).__backing_linkVar5 = new LinkDecoratedVariable("linkVar5", initializers!.__backing_linkVar5!); + }; + } + public __updateStruct(initializers: __Options_LinkParent | undefined): void {} + private __backing_linkVar1?: LinkDecoratedVariable; + public get linkVar1(): string { + return (this).__backing_linkVar1!.get(); + } + public set linkVar1(value: string) { + (this).__backing_linkVar1!.set(value); + } + private __backing_linkVar2?: LinkDecoratedVariable; + public get linkVar2(): number { + return (this).__backing_linkVar2!.get(); + } + public set linkVar2(value: number) { + (this).__backing_linkVar2!.set(value); + } + private __backing_linkVar3?: LinkDecoratedVariable; + public get linkVar3(): boolean { + return (this).__backing_linkVar3!.get(); + } + public set linkVar3(value: boolean) { + (this).__backing_linkVar3!.set(value); + } + private __backing_linkVar4?: LinkDecoratedVariable; + public get linkVar4(): undefined { + return (this).__backing_linkVar4!.get(); + } + public set linkVar4(value: undefined) { + (this).__backing_linkVar4!.set(value); + } + private __backing_linkVar5?: LinkDecoratedVariable; + public get linkVar5(): null { + return (this).__backing_linkVar5!.get(); + } + public set linkVar5(value: null) { + (this).__backing_linkVar5!.set(value); + } + @memo() public _build(@memo() style: ((instance: LinkParent)=> LinkParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_LinkParent | undefined): void {} + public constructor() {} +} + +interface __Options_LinkParent { + abstract set linkVar1(linkVar1: string | undefined) + abstract get linkVar1(): string | undefined + abstract set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar1(): DecoratedV1VariableBase | undefined + abstract set linkVar2(linkVar2: number | undefined) + abstract get linkVar2(): number | undefined + abstract set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar2(): DecoratedV1VariableBase | undefined + abstract set linkVar3(linkVar3: boolean | undefined) + abstract get linkVar3(): boolean | undefined + abstract set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar3(): DecoratedV1VariableBase | undefined + abstract set linkVar4(linkVar4: undefined | undefined) + abstract get linkVar4(): undefined | undefined + abstract set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar4(): DecoratedV1VariableBase | undefined + abstract set linkVar5(linkVar5: null | undefined) + abstract get linkVar5(): null | undefined + abstract set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar5(): DecoratedV1VariableBase | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test basic type @Link decorated variables transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts new file mode 100644 index 000000000..927e91220 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/link'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'link-complex-type.ets'), +]; + +const pluginTester = new PluginTester('test complex type @Link decorated variables transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'link-complex-type', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { Link as Link } from "@ohos.arkui.stateManagement"; + +function main() {} + +class Per { + public num: number; + public constructor(num: number) { + (this).num = num; + } +} + +final class LinkType extends BaseEnum { + private readonly #ordinal: int; + private static () {} + public constructor(ordinal: int, value: int) { + super(value); + (this).#ordinal = ordinal; + } + public static readonly TYPE1: LinkType = new LinkType(0, 0); + public static readonly TYPE2: LinkType = new LinkType(1, 1); + public static readonly TYPE3: LinkType = new LinkType(2, 3); + private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; + private static readonly #ValuesArray: int[] = [0, 1, 3]; + private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; + private static readonly #ItemsArray: LinkType[] = [LinkType.TYPE1, LinkType.TYPE2, LinkType.TYPE3]; + public getName(): String { + return LinkType.#NamesArray[(this).#ordinal]; + } + public static getValueOf(name: String): LinkType { + for (let i = 0;((i) < (LinkType.#NamesArray.length));(++i)) { + if (((name) == (LinkType.#NamesArray[i]))) { + return LinkType.#ItemsArray[i]; + } + } + throw new Error((("No enum constant LinkType.") + (name))); + } + + public static fromValue(value: int): LinkType { + for (let i = 0;((i) < (LinkType.#ValuesArray.length));(++i)) { + if (((value) == (LinkType.#ValuesArray[i]))) { + return LinkType.#ItemsArray[i]; + } + } + throw new Error((("No enum LinkType with value ") + (value))); + } + public valueOf(): int { + return LinkType.#ValuesArray[(this).#ordinal]; + } + public toString(): String { + return LinkType.#StringValuesArray[(this).#ordinal]; + } + public static values(): LinkType[] { + return LinkType.#ItemsArray; + } + public getOrdinal(): int { + return (this).#ordinal; + } + public static $_get(e: LinkType): String { + return e.getName(); + } +} + +@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { + public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { + if (({let gensym___11910109 = initializers; + (((gensym___11910109) == (null)) ? undefined : gensym___11910109.__backing_linkVar1)})) { + (this).__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); + }; + if (({let gensym___181684045 = initializers; + (((gensym___181684045) == (null)) ? undefined : gensym___181684045.__backing_linkVar2)})) { + (this).__backing_linkVar2 = new LinkDecoratedVariable>("linkVar2", initializers!.__backing_linkVar2!); + }; + if (({let gensym___24446313 = initializers; + (((gensym___24446313) == (null)) ? undefined : gensym___24446313.__backing_linkVar3)})) { + (this).__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); + }; + if (({let gensym___167989826 = initializers; + (((gensym___167989826) == (null)) ? undefined : gensym___167989826.__backing_linkVar4)})) { + (this).__backing_linkVar4 = new LinkDecoratedVariable>("linkVar4", initializers!.__backing_linkVar4!); + }; + if (({let gensym___157566097 = initializers; + (((gensym___157566097) == (null)) ? undefined : gensym___157566097.__backing_linkVar5)})) { + (this).__backing_linkVar5 = new LinkDecoratedVariable>("linkVar5", initializers!.__backing_linkVar5!); + }; + if (({let gensym___60105491 = initializers; + (((gensym___60105491) == (null)) ? undefined : gensym___60105491.__backing_linkVar6)})) { + (this).__backing_linkVar6 = new LinkDecoratedVariable>("linkVar6", initializers!.__backing_linkVar6!); + }; + if (({let gensym___3429048 = initializers; + (((gensym___3429048) == (null)) ? undefined : gensym___3429048.__backing_linkVar7)})) { + (this).__backing_linkVar7 = new LinkDecoratedVariable>("linkVar7", initializers!.__backing_linkVar7!); + }; + if (({let gensym___139916435 = initializers; + (((gensym___139916435) == (null)) ? undefined : gensym___139916435.__backing_linkVar8)})) { + (this).__backing_linkVar8 = new LinkDecoratedVariable<((sr: string)=> void)>("linkVar8", initializers!.__backing_linkVar8!); + }; + if (({let gensym___145003260 = initializers; + (((gensym___145003260) == (null)) ? undefined : gensym___145003260.__backing_linkVar9)})) { + (this).__backing_linkVar9 = new LinkDecoratedVariable("linkVar9", initializers!.__backing_linkVar9!); + }; + if (({let gensym___122643185 = initializers; + (((gensym___122643185) == (null)) ? undefined : gensym___122643185.__backing_linkVar10)})) { + (this).__backing_linkVar10 = new LinkDecoratedVariable>("linkVar10", initializers!.__backing_linkVar10!); + }; + if (({let gensym___222468503 = initializers; + (((gensym___222468503) == (null)) ? undefined : gensym___222468503.__backing_linkVar11)})) { + (this).__backing_linkVar11 = new LinkDecoratedVariable("linkVar11", initializers!.__backing_linkVar11!); + }; + if (({let gensym___243301539 = initializers; + (((gensym___243301539) == (null)) ? undefined : gensym___243301539.__backing_linkVar12)})) { + (this).__backing_linkVar12 = new LinkDecoratedVariable | Per>("linkVar12", initializers!.__backing_linkVar12!); + }; + } + public __updateStruct(initializers: __Options_Parent | undefined): void {} + private __backing_linkVar1?: LinkDecoratedVariable; + public get linkVar1(): Per { + return (this).__backing_linkVar1!.get(); + } + public set linkVar1(value: Per) { + (this).__backing_linkVar1!.set(value); + } + private __backing_linkVar2?: LinkDecoratedVariable>; + public get linkVar2(): Array { + return (this).__backing_linkVar2!.get(); + } + public set linkVar2(value: Array) { + (this).__backing_linkVar2!.set(value); + } + private __backing_linkVar3?: LinkDecoratedVariable; + public get linkVar3(): LinkType { + return (this).__backing_linkVar3!.get(); + } + public set linkVar3(value: LinkType) { + (this).__backing_linkVar3!.set(value); + } + private __backing_linkVar4?: LinkDecoratedVariable>; + public get linkVar4(): Set { + return (this).__backing_linkVar4!.get(); + } + public set linkVar4(value: Set) { + (this).__backing_linkVar4!.set(value); + } + private __backing_linkVar5?: LinkDecoratedVariable>; + public get linkVar5(): Array { + return (this).__backing_linkVar5!.get(); + } + public set linkVar5(value: Array) { + (this).__backing_linkVar5!.set(value); + } + private __backing_linkVar6?: LinkDecoratedVariable>; + public get linkVar6(): Array { + return (this).__backing_linkVar6!.get(); + } + public set linkVar6(value: Array) { + (this).__backing_linkVar6!.set(value); + } + private __backing_linkVar7?: LinkDecoratedVariable>; + public get linkVar7(): Array { + return (this).__backing_linkVar7!.get(); + } + public set linkVar7(value: Array) { + (this).__backing_linkVar7!.set(value); + } + private __backing_linkVar8?: LinkDecoratedVariable<((sr: string)=> void)>; + public get linkVar8(): ((sr: string)=> void) { + return (this).__backing_linkVar8!.get(); + } + public set linkVar8(value: ((sr: string)=> void)) { + (this).__backing_linkVar8!.set(value); + } + private __backing_linkVar9?: LinkDecoratedVariable; + public get linkVar9(): Date { + return (this).__backing_linkVar9!.get(); + } + public set linkVar9(value: Date) { + (this).__backing_linkVar9!.set(value); + } + private __backing_linkVar10?: LinkDecoratedVariable>; + public get linkVar10(): Map { + return (this).__backing_linkVar10!.get(); + } + public set linkVar10(value: Map) { + (this).__backing_linkVar10!.set(value); + } + private __backing_linkVar11?: LinkDecoratedVariable; + public get linkVar11(): string | number { + return (this).__backing_linkVar11!.get(); + } + public set linkVar11(value: string | number) { + (this).__backing_linkVar11!.set(value); + } + private __backing_linkVar12?: LinkDecoratedVariable | Per>; + public get linkVar12(): Set | Per { + return (this).__backing_linkVar12!.get(); + } + public set linkVar12(value: Set | Per) { + (this).__backing_linkVar12!.set(value); + } + @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} + public constructor() {} +} + +interface __Options_Parent { + abstract set linkVar1(linkVar1: Per | undefined) + abstract get linkVar1(): Per | undefined + abstract set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar1(): DecoratedV1VariableBase | undefined + abstract set linkVar2(linkVar2: Array | undefined) + abstract get linkVar2(): Array | undefined + abstract set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase> | undefined) + abstract get __backing_linkVar2(): DecoratedV1VariableBase> | undefined + abstract set linkVar3(linkVar3: LinkType | undefined) + abstract get linkVar3(): LinkType | undefined + abstract set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar3(): DecoratedV1VariableBase | undefined + abstract set linkVar4(linkVar4: Set | undefined) + abstract get linkVar4(): Set | undefined + abstract set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase> | undefined) + abstract get __backing_linkVar4(): DecoratedV1VariableBase> | undefined + abstract set linkVar5(linkVar5: Array | undefined) + abstract get linkVar5(): Array | undefined + abstract set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase> | undefined) + abstract get __backing_linkVar5(): DecoratedV1VariableBase> | undefined + abstract set linkVar6(linkVar6: Array | undefined) + abstract get linkVar6(): Array | undefined + abstract set __backing_linkVar6(__backing_linkVar6: DecoratedV1VariableBase> | undefined) + abstract get __backing_linkVar6(): DecoratedV1VariableBase> | undefined + abstract set linkVar7(linkVar7: Array | undefined) + abstract get linkVar7(): Array | undefined + abstract set __backing_linkVar7(__backing_linkVar7: DecoratedV1VariableBase> | undefined) + abstract get __backing_linkVar7(): DecoratedV1VariableBase> | undefined + abstract set linkVar8(linkVar8: ((sr: string)=> void) | undefined) + abstract get linkVar8(): ((sr: string)=> void) | undefined + abstract set __backing_linkVar8(__backing_linkVar8: DecoratedV1VariableBase<((sr: string)=> void)> | undefined) + abstract get __backing_linkVar8(): DecoratedV1VariableBase<((sr: string)=> void)> | undefined + abstract set linkVar9(linkVar9: Date | undefined) + abstract get linkVar9(): Date | undefined + abstract set __backing_linkVar9(__backing_linkVar9: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar9(): DecoratedV1VariableBase | undefined + abstract set linkVar10(linkVar10: Map | undefined) + abstract get linkVar10(): Map | undefined + abstract set __backing_linkVar10(__backing_linkVar10: DecoratedV1VariableBase> | undefined) + abstract get __backing_linkVar10(): DecoratedV1VariableBase> | undefined + abstract set linkVar11(linkVar11: string | number | undefined) + abstract get linkVar11(): string | number | undefined + abstract set __backing_linkVar11(__backing_linkVar11: DecoratedV1VariableBase | undefined) + abstract get __backing_linkVar11(): DecoratedV1VariableBase | undefined + abstract set linkVar12(linkVar12: Set | Per | undefined) + abstract get linkVar12(): Set | Per | undefined + abstract set __backing_linkVar12(__backing_linkVar12: DecoratedV1VariableBase | Per> | undefined) + abstract get __backing_linkVar12(): DecoratedV1VariableBase | Per> | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test complex type @Link decorated variables transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts new file mode 100644 index 000000000..6e903b659 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/link'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'link-to-link-prop-state.ets'), +]; + +const pluginTester = new PluginTester('test @Link decorated variables passing to other variables', buildConfig); + +const parsedTransform: Plugins = { + name: 'link-to-link-prop-state', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { TextInputAttribute as TextInputAttribute } from "@ohos.arkui.component"; +import { ColumnAttribute as ColumnAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, Column as Column, TextInput as TextInput } from "@ohos.arkui.component"; +import { Link as Link, State as State, Prop as Prop } from "@ohos.arkui.stateManagement"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class Parant extends CustomComponent { + public __initializeStruct(initializers: __Options_Parant | undefined, @memo() content: (()=> void) | undefined): void { + if (({let gensym___10127521 = initializers; + (((gensym___10127521) == (null)) ? undefined : gensym___10127521.__backing_text1)})) { + (this).__backing_text1 = new LinkDecoratedVariable("text1", initializers!.__backing_text1!); + }; + } + public __updateStruct(initializers: __Options_Parant | undefined): void {} + private __backing_text1?: LinkDecoratedVariable; + public get text1(): string { + return (this).__backing_text1!.get(); + } + public set text1(value: string) { + (this).__backing_text1!.set(value); + } + @memo() public _build(@memo() style: ((instance: Parant)=> Parant) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parant | undefined): void { + Column(undefined, undefined, (() => { + TextInput(undefined, { + text: (this).text1, + }, undefined); + Child._instantiateImpl(undefined, (() => { + return new Child(); + }), ({ + __backing_childText: (this).__backing_text1, + childText2: (this).text1, + childText3: (this).text1, + childText4: (this).text1, + } as __Options_Child), undefined, undefined); + })); + } + public constructor() {} +} + +@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { + public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { + if (({let gensym___161337494 = initializers; + (((gensym___161337494) == (null)) ? undefined : gensym___161337494.__backing_childText)})) { + (this).__backing_childText = new LinkDecoratedVariable("childText", initializers!.__backing_childText!); + }; + (this).__backing_childText2 = new StateDecoratedVariable("childText2", ((({let gensym___95513066 = initializers; + (((gensym___95513066) == (null)) ? undefined : gensym___95513066.childText2)})) ?? ("sss"))); + (this).__backing_childText3 = new PropDecoratedVariable("childText3", (initializers!.childText3 as string)); + (this).__backing_childText4 = new PropDecoratedVariable("childText4", ((({let gensym___162028107 = initializers; + (((gensym___162028107) == (null)) ? undefined : gensym___162028107.childText4)})) ?? ("cc"))); + } + public __updateStruct(initializers: __Options_Child | undefined): void { + if (((({let gensym___77632518 = initializers; + (((gensym___77632518) == (null)) ? undefined : gensym___77632518.childText3)})) !== (undefined))) { + (this).__backing_childText3!.update((initializers!.childText3 as string)); + } + if (((({let gensym___250510741 = initializers; + (((gensym___250510741) == (null)) ? undefined : gensym___250510741.childText4)})) !== (undefined))) { + (this).__backing_childText4!.update((initializers!.childText4 as string)); + } + } + private __backing_childText?: LinkDecoratedVariable; + public get childText(): string { + return (this).__backing_childText!.get(); + } + public set childText(value: string) { + (this).__backing_childText!.set(value); + } + private __backing_childText2?: StateDecoratedVariable; + public get childText2(): string { + return (this).__backing_childText2!.get(); + } + public set childText2(value: string) { + (this).__backing_childText2!.set(value); + } + private __backing_childText3?: PropDecoratedVariable; + public get childText3(): string { + return (this).__backing_childText3!.get(); + } + public set childText3(value: string) { + (this).__backing_childText3!.set(value); + } + private __backing_childText4?: PropDecoratedVariable; + public get childText4(): string { + return (this).__backing_childText4!.get(); + } + public set childText4(value: string) { + (this).__backing_childText4!.set(value); + } + @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { + TextInput(undefined, { + text: (this).childText, + }, undefined); + } + public constructor() {} +} + +interface __Options_Parant { + abstract set text1(text1: string | undefined) + abstract get text1(): string | undefined + abstract set __backing_text1(__backing_text1: DecoratedV1VariableBase | undefined) + abstract get __backing_text1(): DecoratedV1VariableBase | undefined +} + +interface __Options_Child { + abstract set childText(childText: string | undefined) + abstract get childText(): string | undefined + abstract set __backing_childText(__backing_childText: DecoratedV1VariableBase | undefined) + abstract get __backing_childText(): DecoratedV1VariableBase | undefined + abstract set childText2(childText2: string | undefined) + abstract get childText2(): string | undefined + abstract set __backing_childText2(__backing_childText2: StateDecoratedVariable | undefined) + abstract get __backing_childText2(): StateDecoratedVariable | undefined + abstract set childText3(childText3: string | undefined) + abstract get childText3(): string | undefined + abstract set __backing_childText3(__backing_childText3: PropDecoratedVariable | undefined) + abstract get __backing_childText3(): PropDecoratedVariable | undefined + abstract set childText4(childText4: string | undefined) + abstract get childText4(): string | undefined + abstract set __backing_childText4(__backing_childText4: PropDecoratedVariable | undefined) + abstract get __backing_childText4(): PropDecoratedVariable | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test @Link decorated variables passing to other variables', + [parsedTransform, uiNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts new file mode 100644 index 000000000..300ebc5a9 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/link'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-to-link.ets'), +]; + +const pluginTester = new PluginTester('test @Link decorated variables passing', buildConfig); + +const parsedTransform: Plugins = { + name: 'state-to-link', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { DatePickerAttribute as DatePickerAttribute } from "@ohos.arkui.component"; +import { ButtonAttribute as ButtonAttribute } from "@ohos.arkui.component"; +import { ColumnAttribute as ColumnAttribute } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, Entry as Entry, Column as Column, Button as Button, DatePicker as DatePicker } from "@ohos.arkui.component"; +import { Link as Link, State as State } from "@ohos.arkui.stateManagement"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class DateComponent extends CustomComponent { + public __initializeStruct(initializers: __Options_DateComponent | undefined, @memo() content: (()=> void) | undefined): void { + if (({let gensym___164314175 = initializers; + (((gensym___164314175) == (null)) ? undefined : gensym___164314175.__backing_selectedDate)})) { + (this).__backing_selectedDate = new LinkDecoratedVariable("selectedDate", initializers!.__backing_selectedDate!); + }; + } + public __updateStruct(initializers: __Options_DateComponent | undefined): void {} + private __backing_selectedDate?: LinkDecoratedVariable; + public get selectedDate(): Date { + return (this).__backing_selectedDate!.get(); + } + public set selectedDate(value: Date) { + (this).__backing_selectedDate!.set(value); + } + @memo() public _build(@memo() style: ((instance: DateComponent)=> DateComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_DateComponent | undefined): void { + Column(undefined, undefined, (() => { + Button(((instance: ButtonAttribute): void => { + instance.onClick((() => { + (this).selectedDate.setFullYear((((this).selectedDate.getFullYear()) + (1))); + })); + return; + }), "child increase the year by 1", undefined, undefined); + Button(((instance: ButtonAttribute): void => { + instance.margin(10).onClick((() => { + (this).selectedDate = new Date("2023-09-09"); + })); + return; + }), "child update the new date", undefined, undefined); + DatePicker(undefined, { + start: new Date("1970-1-1"), + end: new Date("2100-1-1"), + selected: (this).selectedDate, + }, undefined); + })); + } + public constructor() {} + +} + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class ParentComponent extends CustomComponent { + public __initializeStruct(initializers: __Options_ParentComponent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_parentSelectedDate = new StateDecoratedVariable("parentSelectedDate", ((({let gensym___80922148 = initializers; + (((gensym___80922148) == (null)) ? undefined : gensym___80922148.parentSelectedDate)})) ?? (new Date("2021-08-08")))); + } + public __updateStruct(initializers: __Options_ParentComponent | undefined): void {} + private __backing_parentSelectedDate?: StateDecoratedVariable; + public get parentSelectedDate(): Date { + return (this).__backing_parentSelectedDate!.get(); + } + public set parentSelectedDate(value: Date) { + (this).__backing_parentSelectedDate!.set(value); + } + @memo() public _build(@memo() style: ((instance: ParentComponent)=> ParentComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ParentComponent | undefined): void { + Column(undefined, undefined, (() => { + Button(((instance: ButtonAttribute): void => { + instance.margin(10).onClick((() => { + (this).parentSelectedDate.setMonth((((this).parentSelectedDate.getMonth()) + (1))); + })); + return; + }), "parent increase the month by 1", undefined, undefined); + Button(((instance: ButtonAttribute): void => { + instance.margin(10).onClick((() => { + (this).parentSelectedDate = new Date("2023-07-07"); + })); + return; + }), "parent update the new date", undefined, undefined); + DatePicker(undefined, { + start: new Date("1970-1-1"), + end: new Date("2100-1-1"), + selected: (this).parentSelectedDate, + }, undefined); + DateComponent._instantiateImpl(undefined, (() => { + return new DateComponent(); + }), ({ + __backing_selectedDate: (this).__backing_parentSelectedDate, + } as __Options_DateComponent), undefined, undefined); + })); + } + public constructor() {} +} + +interface __Options_DateComponent { + abstract set selectedDate(selectedDate: Date | undefined) + abstract get selectedDate(): Date | undefined + abstract set __backing_selectedDate(__backing_selectedDate: DecoratedV1VariableBase | undefined) + abstract get __backing_selectedDate(): DecoratedV1VariableBase | undefined +} + +interface __Options_ParentComponent { + abstract set parentSelectedDate(parentSelectedDate: Date | undefined) + abstract get parentSelectedDate(): Date | undefined + abstract set __backing_parentSelectedDate(__backing_parentSelectedDate: StateDecoratedVariable | undefined) + abstract get __backing_parentSelectedDate(): StateDecoratedVariable | undefined +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + ParentComponent._instantiateImpl(undefined, (() => { + return new ParentComponent(); + }), undefined, undefined, undefined); + } + public constructor() {} +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test @Link decorated variables passing', + [parsedTransform, uiNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 02ef7fcc2..4b587b3fa 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -254,7 +254,11 @@ export class factory { arkts.isIdentifier(prop.value.property) ) { const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; - if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { + if ( + structVariableMetadata && + structVariableMetadata.properties.length && + structVariableMetadata.properties.includes(DecoratorNames.LINK) + ) { properties[index] = arkts.Property.updateProperty( prop, arkts.factory.createIdentifier(backingField(prop.key.name)), -- Gitee From 12c957412faaacac2db54fb7d99c4f077aa51cea Mon Sep 17 00:00:00 2001 From: zenghang Date: Fri, 25 Apr 2025 16:28:12 +0800 Subject: [PATCH 068/123] fix bug for oh_modules Issue: IC3ZEW Signed-off-by: zenghang Change-Id: I0af780413e368c67182af88805af6f74395d600c --- compiler/main.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/main.js b/compiler/main.js index a8d7bc0a2..95d20e602 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -160,7 +160,7 @@ function loadEntryObj(projectConfig) { setStageTestRunnerFile(projectConfig); loadNavigationConfig(aceBuildJson); } - if (projectConfig.mixCompile) { + if (projectConfig.mixCompile && projectConfig.isRemoteModule) { return; } if (staticPreviewPage) { @@ -1172,6 +1172,7 @@ function initMixCompileHar(projectConfig) { projectConfig.mixCompile = process.env.mixCompile === 'true'; if (projectConfig.isRemoteModule && projectConfig.mixCompile) { projectConfig.compileHar = true; + process.env.compileMode = 'moduleJson'; getPackageJsonEntryPath(); } } -- Gitee From c4fb816b4b1115f66cbfcbbc2288be87dfd4f837 Mon Sep 17 00:00:00 2001 From: Torok Gergo Date: Fri, 25 Apr 2025 11:08:48 +0200 Subject: [PATCH 069/123] Implementing nonnullish type param node Reason: Nonnullish type parameter node is not implemented yet Description: Adding new type node: NonNullishTypeNode Implementing Parser and Checker for nonnullish type node Adding compiler test Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC13K6 Signed-off-by: Torok Gergo --- koala-wrapper/src/Es2pandaEnums.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/koala-wrapper/src/Es2pandaEnums.ts b/koala-wrapper/src/Es2pandaEnums.ts index 630e1bebd..bf2ce0783 100644 --- a/koala-wrapper/src/Es2pandaEnums.ts +++ b/koala-wrapper/src/Es2pandaEnums.ts @@ -78,6 +78,7 @@ export enum Es2pandaAstNodeType { AST_NODE_TYPE_SCRIPT_FUNCTION, AST_NODE_TYPE_SEQUENCE_EXPRESSION, AST_NODE_TYPE_STRING_LITERAL, + AST_NODE_TYPE_ETS_NON_NULLISH_TYPE, AST_NODE_TYPE_ETS_NULL_TYPE, AST_NODE_TYPE_ETS_UNDEFINED_TYPE, AST_NODE_TYPE_ETS_NEVER_TYPE, -- Gitee From 9eb4125f62d24473c51a1bdfc411e3226d04c104 Mon Sep 17 00:00:00 2001 From: wangcaoyu Date: Sun, 27 Apr 2025 10:54:52 +0800 Subject: [PATCH 070/123] remove common_api Signed-off-by: wangcaoyu --- BUILD.gn | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 4accb34f4..cebb39291 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -331,8 +331,7 @@ ohos_copy("ohos_declaration_ets_ark") { outputs = [ target_out_dir + "/../api" ] } -ohos_copy("ets_loader_ark_hap") { - sources = common_api_src +group("ets_loader_ark_hap") { deps = [ ":ets_loader_ark", ":ets_loader_ark_codegen", @@ -343,8 +342,6 @@ ohos_copy("ets_loader_ark_hap") { ":ets_loader_ark_server", ":ohos_declaration_ets_ark", ] - outputs = [ target_out_dir + "/../../developtools/api/{{source_file_part}}" ] - module_install_name = "" } typescript_dir = get_label_info("//third_party/typescript:build_typescript", -- Gitee From 001cd45fa0e71da681d72b29dee00eb0f12ea116 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Thu, 24 Apr 2025 09:42:08 +0800 Subject: [PATCH 071/123] add ETSNewClassInstanceExpression in visitor Signed-off-by: y00896775 Change-Id: I813b846dd03b2495b67b8420697f221adda20ff5 --- koala-wrapper/src/arkts-api/visitor.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index aa097976e..27fb2b733 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -41,6 +41,7 @@ import { ObjectExpression, isProperty, Expression, + isETSNewClassInstanceExpression, } from '../generated'; import { isEtsScript, @@ -185,7 +186,14 @@ function visitOuterExpression(node: AstNode, visitor: Visitor): AstNode { nodeVisitor(node.right as Expression, visitor) ); } - // TODO + if (isETSNewClassInstanceExpression(node)) { + updated = true; + return factory.updateETSNewClassInstanceExpression( + node, + node.getTypeRef, + nodesVisitor(node.getArguments, visitor) + ); + } return node; } -- Gitee From c72fff7538825d88f12580645586e918b860057d Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Sun, 27 Apr 2025 14:46:11 +0800 Subject: [PATCH 072/123] fix observed transform Signed-off-by: fengyuxin Change-Id: I9b02da31e18162566a81abfde6e2c8ec47ff43db --- .../property-translators/observedTrack.ts | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts index ea2d2d67b..62bcad2d6 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -184,17 +184,19 @@ export class ObservedTrackTranslator { propertyIsClassField(newName: string): arkts.ClassProperty { return arkts.factory.createClassProperty( arkts.factory.createIdentifier(newName), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('BackingValue'), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - [arkts.factory.createETSNewClassInstanceExpression(this.property.typeAnnotation, [])] - ), + this.property.value + ? arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('BackingValue'), + arkts.factory.createTSTypeParameterInstantiation( + this.property.typeAnnotation ? [this.property.typeAnnotation] : [] + ) + ) + ), + [this.property.value] + ) + : undefined, arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier('BackingValue'), -- Gitee From 5923984637f888e039c42d3e7bf1921083812718 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Fri, 25 Apr 2025 09:39:50 +0800 Subject: [PATCH 073/123] add test cases Signed-off-by: y00896775 Change-Id: Icadf91ad14974a7a43473f54153924f0ca295329 --- .../decorators/builder/global-builder.ets | 41 +++ .../mock/decorators/builder/local-builder.ets | 36 ++ .../mock/decorators/prop/prop-basic-type.ets | 29 ++ .../decorators/prop/prop-complex-type.ets | 49 +++ .../mock/decorators/prop/state-to-prop.ets | 54 +++ .../provide-annotation-usage.ets | 32 ++ .../provide-basic-type.ets | 29 ++ .../provide-complex-type.ets | 49 +++ .../decorators/resource/resource-in-build.ets | 42 +++ .../resource/resource-in-property.ets | 31 ++ .../decorators/state/state-basic-type.ets | 29 ++ .../decorators/state/state-complex-type.ets | 49 +++ .../mock/decorators/state/state-to-state.ets | 42 +++ .../decorators/builder/global-builder.test.ts | 97 +++++ .../decorators/builder/local-builder.test.ts | 92 +++++ .../decorators/prop/prop-basic-type.test.ts | 161 +++++++++ .../decorators/prop/prop-complex-type.test.ts | 337 ++++++++++++++++++ .../decorators/prop/state-to-prop.test.ts | 169 +++++++++ .../provide-annotation-usage.test.ts | 179 ++++++++++ .../provide-basic-type.test.ts | 140 ++++++++ .../provide-complex-type.test.ts | 288 +++++++++++++++ .../resource/resource-in-build.test.ts | 133 +++++++ .../resource/resource-in-property.test.ts | 108 ++++++ .../decorators/state/state-basic-type.test.ts | 140 ++++++++ .../state/state-complex-type.test.ts | 288 +++++++++++++++ .../decorators/state/state-to-state.test.ts | 132 +++++++ .../ui-plugins/component-transformer.ts | 3 + .../ui-plugins/property-translators/utils.ts | 10 +- arkui-plugins/ui-plugins/ui-factory.ts | 44 ++- arkui-plugins/ui-plugins/utils.ts | 11 + .../src/arkts-api/factory/nodeFactory.ts | 8 +- .../node-utilities/AnnotationUsage.ts | 10 + 32 files changed, 2855 insertions(+), 7 deletions(-) create mode 100644 arkui-plugins/test/demo/mock/decorators/builder/global-builder.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/builder/local-builder.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/prop/prop-basic-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/prop/prop-complex-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/prop/state-to-prop.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-annotation-usage.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-basic-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-complex-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/resource/resource-in-property.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/state/state-basic-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/state/state-complex-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/state/state-to-state.ets create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts diff --git a/arkui-plugins/test/demo/mock/decorators/builder/global-builder.ets b/arkui-plugins/test/demo/mock/decorators/builder/global-builder.ets new file mode 100644 index 000000000..bba1e6ee0 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/builder/global-builder.ets @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Row, Builder, Text } from "@ohos.arkui.component" + +@Builder +function showTextBuilder() { + Text('Hello World') +} + +class Tmp { + paramA1: string = ''; +} + +@Builder function overBuilder(params: Tmp) { + Row() { + Text('UseStateVarByReference: ' + params.paramA1) + } +} + +@Component +struct BuilderDemo { + build() { + Row() { + showTextBuilder() + overBuilder({ paramA1: 'Hello' }) + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/builder/local-builder.ets b/arkui-plugins/test/demo/mock/decorators/builder/local-builder.ets new file mode 100644 index 000000000..01da4671a --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/builder/local-builder.ets @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Column, Builder, Text } from "@ohos.arkui.component" + +@Component +struct BuilderDemo { + @Builder + showTextBuilder() { + Text('Hello World') + .fontSize(30) + } + @Builder + showTextValueBuilder(param: string) { + Text(param) + .fontSize(30) + } + build() { + Column() { + this.showTextBuilder() + this.showTextValueBuilder('Hello @Builder') + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/prop/prop-basic-type.ets b/arkui-plugins/test/demo/mock/decorators/prop/prop-basic-type.ets new file mode 100644 index 000000000..bcfff2d58 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/prop/prop-basic-type.ets @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { Prop } from "@ohos.arkui.stateManagement" + +@Component +struct PropParent { + @Prop propVar1: string = 'propVar1'; + @Prop propVar2: number = 50; + @Prop propVar3: boolean = true; + @Prop propVar4: undefined = undefined; + @Prop propVar5: null = null; + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/prop/prop-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/prop/prop-complex-type.ets new file mode 100644 index 000000000..a2fbdc9d2 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/prop/prop-complex-type.ets @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { Prop } from "@ohos.arkui.stateManagement" + +class Per { + num: number; + constructor(num: number) { + this.num = num; + } +} + +enum PropType { + TYPE1 = 0, + TYPE2 = 1, + TYPE3 = 3 +} + +@Component +struct Parent { + @Prop propVar1: Per = new Per(6); + @Prop propVar2: Array = new Array(3,6,8); + @Prop propVar3: PropType = PropType.TYPE3; + @Prop propVar4: Set = new Set(new Array('aa', 'bb')); + @Prop propVar5: boolean[] = [true, false]; + @Prop propVar6: Array = new Array(new Per(7), new Per(11)); + @Prop propVar7: Per[] = [new Per(7), new Per(11)]; + @Prop propVar8: (sr: string)=>void = (sr: string)=>{}; + @Prop propVar9: Date = new Date('2025-4-23'); + @Prop propVar10: Map = new Map([[0, new Per(7)], [1, new Per(10)]]); + @Prop propVar11: string | number = 0.0; + @Prop propVar12: Set | Per = new Per(6); + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/prop/state-to-prop.ets b/arkui-plugins/test/demo/mock/decorators/prop/state-to-prop.ets new file mode 100644 index 000000000..38af709df --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/prop/state-to-prop.ets @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Text, Button, Column, ClickEvent } from "@ohos.arkui.component" +import { Prop, State } from "@ohos.arkui.stateManagement" + +@Component +struct CountDownComponent { + @Prop count: number = 0; + costOfOneAttempt: number = 1; + + build() { + Column() { + if (this.count > 0) { + Text('You have'+ this.count + 'Nuggets left') + } else { + Text('Game over!') + } + Button('Try again').onClick((e: ClickEvent) => { + this.count -= this.costOfOneAttempt; + }) + } + } +} + +@Component +struct ParentComponent { + @State countDownStartValue: number = 10; + + build() { + Column() { + Text('Grant' + this.countDownStartValue + 'nuggets to play.') + Button('+1 - Nuggets in New Game').onClick((e: ClickEvent) => { + this.countDownStartValue += 1; + }) + Button('-1 - Nuggets in New Game').onClick((e: ClickEvent) => { + this.countDownStartValue -= 1; + }) + CountDownComponent({ count: this.countDownStartValue, costOfOneAttempt: 2 }) + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-annotation-usage.ets b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-annotation-usage.ets new file mode 100644 index 000000000..74afaf8f9 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-annotation-usage.ets @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { Provide } from "@ohos.arkui.stateManagement" + +@Component +struct Ancestors { + @Provide count: string | undefined = 'Child0'; + @Provide({ alias: 'prov1' }) count1: string | undefined = 'Child1'; + @Provide({ alias: 'prov2', allowOverride: false }) count2: string | undefined = 'Child2'; + @Provide({ alias: 'prov3', allowOverride: true }) count3: string | undefined = 'Child3'; + @Provide({ allowOverride: false }) count4: string | undefined = 'Child4'; + @Provide({ allowOverride: true }) count5: string | undefined = 'Child5'; + @Provide({ alias: "", allowOverride: true }) count6: string | undefined = 'Child6'; + @Provide({ alias: "" }) count7: string | undefined = 'Child7'; + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-basic-type.ets b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-basic-type.ets new file mode 100644 index 000000000..06c9ddea3 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-basic-type.ets @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { Provide } from "@ohos.arkui.stateManagement" + +@Component +struct PropParent { + @Provide provideVar1: string = 'propVar1'; + @Provide provideVar2: number = 50; + @Provide provideVar3: boolean = true; + @Provide provideVar4: undefined = undefined; + @Provide provideVar5: null = null; + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-complex-type.ets new file mode 100644 index 000000000..6395a981b --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-complex-type.ets @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { Provide } from "@ohos.arkui.stateManagement" + +class Per { + num: number; + constructor(num: number) { + this.num = num; + } +} + +enum PropType { + TYPE1 = 0, + TYPE2 = 1, + TYPE3 = 3 +} + +@Component +struct Parent { + @Provide provideVar1: Per = new Per(6); + @Provide provideVar2: Array = new Array(3,6,8); + @Provide provideVar3: PropType = PropType.TYPE3; + @Provide provideVar4: Set = new Set(new Array('aa', 'bb')); + @Provide provideVar5: boolean[] = [true, false]; + @Provide provideVar6: Array = new Array(new Per(7), new Per(11)); + @Provide provideVar7: Per[] = [new Per(7), new Per(11)]; + @Provide provideVar8: (sr: string)=>void = (sr: string)=>{}; + @Provide provideVar9: Date = new Date('2025-4-23'); + @Provide provideVar10: Map = new Map([[0, new Per(7)], [1, new Per(10)]]); + @Provide provideVar11: string | number = 0.0; + @Provide provideVar12: Set | Per = new Per(6); + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets b/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets new file mode 100644 index 000000000..f778c7f4e --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, $r, $rawfile, Column, Text, Image, TextInput, Select, SelectOption, Margin } from "@ohos.arkui.component" + +@Component +struct ResourceComponent { + str1: string = 'app.media.ri' + str2: string = 'app.photo2.png' + build() { + Column() { + Text($r('app.string.app_name')) + Image($rawfile('app.photo.png')) + TextInput({ text: $r('app.string.input_content') }) + Text($r(this.str1)) + Text($r(this.str2)) + Select(new Array( + { value: 'aaa', icon: $r("app.media.selection") }, + { value: 'bbb', icon: $r("app.media.selection") }, + { value: 'ccc', icon: $r("app.media.selection") }, + { value: 'ddd', icon: $r("app.media.selection") } + )) + Image($r('app.media.app_icon')) + .margin({ + top: $r('app.float.elements_margin_horizontal_m'), + bottom: $r('app.float.elements_margin_horizontal_l') + } as Margin) + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/resource/resource-in-property.ets b/arkui-plugins/test/demo/mock/decorators/resource/resource-in-property.ets new file mode 100644 index 000000000..591311c7d --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/resource/resource-in-property.ets @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, $r, $rawfile, Column, Text, Image, Resource } from "@ohos.arkui.component" + +let i: Resource = $r('app.string.app_name'); + +@Component +struct ResourceComponent { + private str: Resource = $r('app.string.app_name'); + private icon: Resource = $rawfile('app.photo.png'); + build() { + Column() { + Text(this.str) + Text(i) + Image(this.icon) + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/state/state-basic-type.ets b/arkui-plugins/test/demo/mock/decorators/state/state-basic-type.ets new file mode 100644 index 000000000..b7e039a77 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/state/state-basic-type.ets @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { State} from "@ohos.arkui.stateManagement" + +@Component +struct Parent { + @State stateVar1: string = 'stateVar1'; + @State stateVar2: number = 50; + @State stateVar3: boolean = true; + @State stateVar4: undefined = undefined; + @State stateVar5: null = null; + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/state/state-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/state/state-complex-type.ets new file mode 100644 index 000000000..5ffe6f50a --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/state/state-complex-type.ets @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component } from "@ohos.arkui.component" +import { State} from "@ohos.arkui.stateManagement" + +class Per { + num: number; + constructor(num: number) { + this.num = num; + } +} + +enum StateType { + TYPE1 = 0, + TYPE2 = 1, + TYPE3 = 3 +} + +@Component +struct Parent { + @State stateVar1: Per = new Per(6); + @State stateVar2: Array = new Array(3,6,8); + @State stateVar3: StateType = StateType.TYPE3; + @State stateVar4: Set = new Set(new Array('aa', 'bb')); + @State stateVar5: boolean[] = [true, false]; + @State stateVar6: Array = new Array(new Per(7), new Per(11)); + @State stateVar7: Per[] = [new Per(7), new Per(11)]; + @State stateVar8: (sr: string)=>void = (sr: string)=>{}; + @State stateVar9: Date = new Date('2025-4-23'); + @State stateVar10: Map = new Map([[0, new Per(7)], [1, new Per(10)]]); + @State stateVar11: string | number = 0.0; + @State stateVar12: Set | Per = new Per(6); + + build() { + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/state/state-to-state.ets b/arkui-plugins/test/demo/mock/decorators/state/state-to-state.ets new file mode 100644 index 000000000..8beb2e452 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/state/state-to-state.ets @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Column, Text } from "@ohos.arkui.component" +import { State } from "@ohos.arkui.stateManagement" + +class Per { + str: string; + constructor(str: string) { + this.str = str; + } +} + +@Component +struct Parent { + @State parentVar1: Per = new Per('hello'); + build() { + Column() { + Child({ childVar1: this.parentVar1 }) + } + } +} + +@Component +struct Child { + @State childVar1: Per = new Per('ccc'); + build() { + Text(this.childVar1.str) + } +} \ No newline at end of file diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts new file mode 100644 index 000000000..09ffcfbaa --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const FUNCTION_DIR_PATH: string = 'decorators/builder'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'global-builder.ets'), +]; + +const pluginTester = new PluginTester('test global builder', buildConfig); + +const parsedTransform: Plugins = { + name: 'global-builder', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UIRowAttribute as UIRowAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, Row as Row, Builder as Builder, Text as Text } from "@ohos.arkui.component"; + +function main() {} + +@memo() function showTextBuilder() { + Text(undefined, "Hello World", undefined, undefined); +} + +@memo() function overBuilder(params: Tmp) { + Row(undefined, undefined, (() => { + Text(undefined, (("UseStateVarByReference: ") + (params.paramA1)), undefined, undefined); + })); +} + +class Tmp { + public paramA1: string = ""; + public constructor() {} +} + +@Component({freezeWhenInactive:false}) final class BuilderDemo extends CustomComponent { + public __initializeStruct(initializers: __Options_BuilderDemo | undefined, @memo() content: (()=> void) | undefined): void {} + public __updateStruct(initializers: __Options_BuilderDemo | undefined): void {} + @memo() public _build(@memo() style: ((instance: BuilderDemo)=> BuilderDemo) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_BuilderDemo | undefined): void { + Row(undefined, undefined, @memo() (() => { + showTextBuilder(); + overBuilder({ + paramA1: "Hello", + }); + })); + } + public constructor() {} +} + +interface __Options_BuilderDemo { + +} +`; + +function testCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'global builder', + [parsedTransform, uiNoRecheck], + { + 'checked:ui-no-recheck': [testCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts new file mode 100644 index 000000000..084238f23 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const FUNCTION_DIR_PATH: string = 'decorators/builder'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'local-builder.ets'), +]; + +const pluginTester = new PluginTester('test local builder', buildConfig); + +const parsedTransform: Plugins = { + name: 'local-builder', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, Column as Column, Builder as Builder, Text as Text } from "@ohos.arkui.component"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class BuilderDemo extends CustomComponent { + public __initializeStruct(initializers: __Options_BuilderDemo | undefined, @memo() content: (()=> void) | undefined): void {} + public __updateStruct(initializers: __Options_BuilderDemo | undefined): void {} + @memo() public showTextBuilder() { + Text(@memo() ((instance: UITextAttribute): void => { + instance.fontSize(30); + return; + }), "Hello World", undefined, undefined); + } + @memo() public showTextValueBuilder(param: string) { + Text(@memo() ((instance: UITextAttribute): void => { + instance.fontSize(30); + return; + }), param, undefined, undefined); + } + @memo() public _build(@memo() style: ((instance: BuilderDemo)=> BuilderDemo) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_BuilderDemo | undefined): void { + Column(undefined, undefined, @memo() (() => { + (this).showTextBuilder(); + (this).showTextValueBuilder("Hello @Builder"); + })); + } + public constructor() {} +} + +interface __Options_BuilderDemo { + +} +`; + +function testCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'local builder', + [parsedTransform, uiNoRecheck], + { + 'checked:ui-no-recheck': [testCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts new file mode 100644 index 000000000..b25b5c22d --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/prop'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'prop-basic-type.ets'), +]; + +const pluginTester = new PluginTester('test basic type @Prop decorated variables transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'prop-basic-type', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { Prop as Prop } from "@ohos.arkui.stateManagement"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class PropParent extends CustomComponent { + public __initializeStruct(initializers: __Options_PropParent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_propVar1 = new PropDecoratedVariable("propVar1", ((({let gensym___95172135 = initializers; + (((gensym___95172135) == (null)) ? undefined : gensym___95172135.propVar1)})) ?? ("propVar1"))); + (this).__backing_propVar2 = new PropDecoratedVariable("propVar2", ((({let gensym___222490386 = initializers; + (((gensym___222490386) == (null)) ? undefined : gensym___222490386.propVar2)})) ?? (50))); + (this).__backing_propVar3 = new PropDecoratedVariable("propVar3", ((({let gensym___201781257 = initializers; + (((gensym___201781257) == (null)) ? undefined : gensym___201781257.propVar3)})) ?? (true))); + (this).__backing_propVar4 = new PropDecoratedVariable("propVar4", ((({let gensym___22028950 = initializers; + (((gensym___22028950) == (null)) ? undefined : gensym___22028950.propVar4)})) ?? (undefined))); + (this).__backing_propVar5 = new PropDecoratedVariable("propVar5", ((({let gensym___54872258 = initializers; + (((gensym___54872258) == (null)) ? undefined : gensym___54872258.propVar5)})) ?? (null))); + } + public __updateStruct(initializers: __Options_PropParent | undefined): void { + if (((({let gensym___67969738 = initializers; + (((gensym___67969738) == (null)) ? undefined : gensym___67969738.propVar1)})) !== (undefined))) { + (this).__backing_propVar1!.update((initializers!.propVar1 as string)); + } + if (((({let gensym___52350476 = initializers; + (((gensym___52350476) == (null)) ? undefined : gensym___52350476.propVar2)})) !== (undefined))) { + (this).__backing_propVar2!.update((initializers!.propVar2 as number)); + } + if (((({let gensym___103864283 = initializers; + (((gensym___103864283) == (null)) ? undefined : gensym___103864283.propVar3)})) !== (undefined))) { + (this).__backing_propVar3!.update((initializers!.propVar3 as boolean)); + } + if (((({let gensym___175155715 = initializers; + (((gensym___175155715) == (null)) ? undefined : gensym___175155715.propVar4)})) !== (undefined))) { + (this).__backing_propVar4!.update((initializers!.propVar4 as undefined)); + } + if (((({let gensym___134530703 = initializers; + (((gensym___134530703) == (null)) ? undefined : gensym___134530703.propVar5)})) !== (undefined))) { + (this).__backing_propVar5!.update((initializers!.propVar5 as null)); + } + } + private __backing_propVar1?: PropDecoratedVariable; + public get propVar1(): string { + return (this).__backing_propVar1!.get(); + } + public set propVar1(value: string) { + (this).__backing_propVar1!.set(value); + } + private __backing_propVar2?: PropDecoratedVariable; + public get propVar2(): number { + return (this).__backing_propVar2!.get(); + } + public set propVar2(value: number) { + (this).__backing_propVar2!.set(value); + } + private __backing_propVar3?: PropDecoratedVariable; + public get propVar3(): boolean { + return (this).__backing_propVar3!.get(); + } + public set propVar3(value: boolean) { + (this).__backing_propVar3!.set(value); + } + private __backing_propVar4?: PropDecoratedVariable; + public get propVar4(): undefined { + return (this).__backing_propVar4!.get(); + } + public set propVar4(value: undefined) { + (this).__backing_propVar4!.set(value); + } + private __backing_propVar5?: PropDecoratedVariable; + public get propVar5(): null { + return (this).__backing_propVar5!.get(); + } + public set propVar5(value: null) { + (this).__backing_propVar5!.set(value); + } + @memo() public _build(@memo() style: ((instance: PropParent)=> PropParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_PropParent | undefined): void {} + public constructor() {} +} + +interface __Options_PropParent { + set propVar1(propVar1: string | undefined) + get propVar1(): string | undefined + set __backing_propVar1(__backing_propVar1: PropDecoratedVariable | undefined) + get __backing_propVar1(): PropDecoratedVariable | undefined + set propVar2(propVar2: number | undefined) + get propVar2(): number | undefined + set __backing_propVar2(__backing_propVar2: PropDecoratedVariable | undefined) + get __backing_propVar2(): PropDecoratedVariable | undefined + set propVar3(propVar3: boolean | undefined) + get propVar3(): boolean | undefined + set __backing_propVar3(__backing_propVar3: PropDecoratedVariable | undefined) + get __backing_propVar3(): PropDecoratedVariable | undefined + set propVar4(propVar4: undefined | undefined) + get propVar4(): undefined | undefined + set __backing_propVar4(__backing_propVar4: PropDecoratedVariable | undefined) + get __backing_propVar4(): PropDecoratedVariable | undefined + set propVar5(propVar5: null | undefined) + get propVar5(): null | undefined + set __backing_propVar5(__backing_propVar5: PropDecoratedVariable | undefined) + get __backing_propVar5(): PropDecoratedVariable | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test basic type @Prop decorated variables transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts new file mode 100644 index 000000000..312db0a77 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/prop'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'prop-complex-type.ets'), +]; + +const pluginTester = new PluginTester('test complex type @Prop decorated variables transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'prop-complex-type', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { Prop as Prop } from "@ohos.arkui.stateManagement"; + +function main() {} + +class Per { + public num: number; + public constructor(num: number) { + (this).num = num; + } +} + +final class PropType extends BaseEnum { + private readonly #ordinal: int; + private static () {} + public constructor(ordinal: int, value: int) { + super(value); + (this).#ordinal = ordinal; + } + public static readonly TYPE1: PropType = new PropType(0, 0); + public static readonly TYPE2: PropType = new PropType(1, 1); + public static readonly TYPE3: PropType = new PropType(2, 3); + private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; + private static readonly #ValuesArray: int[] = [0, 1, 3]; + private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; + private static readonly #ItemsArray: PropType[] = [PropType.TYPE1, PropType.TYPE2, PropType.TYPE3]; + public getName(): String { + return PropType.#NamesArray[(this).#ordinal]; + } + public static getValueOf(name: String): PropType { + for (let i = 0;((i) < (PropType.#NamesArray.length));(++i)) { + if (((name) == (PropType.#NamesArray[i]))) { + return PropType.#ItemsArray[i]; + } + } + throw new Error((("No enum constant PropType.") + (name))); + } + public static fromValue(value: int): PropType { + for (let i = 0;((i) < (PropType.#ValuesArray.length));(++i)) { + if (((value) == (PropType.#ValuesArray[i]))) { + return PropType.#ItemsArray[i]; + } + } + throw new Error((("No enum PropType with value ") + (value))); + } + public valueOf(): int { + return PropType.#ValuesArray[(this).#ordinal]; + } + public toString(): String { + return PropType.#StringValuesArray[(this).#ordinal]; + } + public static values(): PropType[] { + return PropType.#ItemsArray; + } + public getOrdinal(): int { + return (this).#ordinal; + } + public static $_get(e: PropType): String { + return e.getName(); + } +} + +@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { + public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_propVar1 = new PropDecoratedVariable("propVar1", ((({let gensym___95172135 = initializers; + (((gensym___95172135) == (null)) ? undefined : gensym___95172135.propVar1)})) ?? (new Per(6)))); + (this).__backing_propVar2 = new PropDecoratedVariable>("propVar2", ((({let gensym___222490386 = initializers; + (((gensym___222490386) == (null)) ? undefined : gensym___222490386.propVar2)})) ?? (new Array(3, 6, 8)))); + (this).__backing_propVar3 = new PropDecoratedVariable("propVar3", ((({let gensym___201781257 = initializers; + (((gensym___201781257) == (null)) ? undefined : gensym___201781257.propVar3)})) ?? (PropType.TYPE3))); + (this).__backing_propVar4 = new PropDecoratedVariable>("propVar4", ((({let gensym___22028950 = initializers; + (((gensym___22028950) == (null)) ? undefined : gensym___22028950.propVar4)})) ?? (new Set(new Array("aa", "bb"))))); + (this).__backing_propVar5 = new PropDecoratedVariable>("propVar5", ((({let gensym___54872258 = initializers; + (((gensym___54872258) == (null)) ? undefined : gensym___54872258.propVar5)})) ?? ([true, false]))); + (this).__backing_propVar6 = new PropDecoratedVariable>("propVar6", ((({let gensym___128760941 = initializers; + (((gensym___128760941) == (null)) ? undefined : gensym___128760941.propVar6)})) ?? (new Array(new Per(7), new Per(11))))); + (this).__backing_propVar7 = new PropDecoratedVariable>("propVar7", ((({let gensym___30534085 = initializers; + (((gensym___30534085) == (null)) ? undefined : gensym___30534085.propVar7)})) ?? ([new Per(7), new Per(11)]))); + (this).__backing_propVar8 = new PropDecoratedVariable<((sr: string)=> void)>("propVar8", ((({let gensym___12471776 = initializers; + (((gensym___12471776) == (null)) ? undefined : gensym___12471776.propVar8)})) ?? (((sr: string) => {})))); + (this).__backing_propVar9 = new PropDecoratedVariable("propVar9", ((({let gensym___123472108 = initializers; + (((gensym___123472108) == (null)) ? undefined : gensym___123472108.propVar9)})) ?? (new Date("2025-4-23")))); + (this).__backing_propVar10 = new PropDecoratedVariable>("propVar10", ((({let gensym___147847012 = initializers; + (((gensym___147847012) == (null)) ? undefined : gensym___147847012.propVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]])))); + (this).__backing_propVar11 = new PropDecoratedVariable("propVar11", ((({let gensym___117026760 = initializers; + (((gensym___117026760) == (null)) ? undefined : gensym___117026760.propVar11)})) ?? (0.0))); + (this).__backing_propVar12 = new PropDecoratedVariable | Per>("propVar12", ((({let gensym___220245132 = initializers; + (((gensym___220245132) == (null)) ? undefined : gensym___220245132.propVar12)})) ?? (new Per(6)))); + } + public __updateStruct(initializers: __Options_Parent | undefined): void { + if (((({let gensym___67969738 = initializers; + (((gensym___67969738) == (null)) ? undefined : gensym___67969738.propVar1)})) !== (undefined))) { + (this).__backing_propVar1!.update((initializers!.propVar1 as Per)); + } + if (((({let gensym___52350476 = initializers; + (((gensym___52350476) == (null)) ? undefined : gensym___52350476.propVar2)})) !== (undefined))) { + (this).__backing_propVar2!.update((initializers!.propVar2 as Array)); + } + if (((({let gensym___103864283 = initializers; + (((gensym___103864283) == (null)) ? undefined : gensym___103864283.propVar3)})) !== (undefined))) { + (this).__backing_propVar3!.update((initializers!.propVar3 as PropType)); + } + if (((({let gensym___175155715 = initializers; + (((gensym___175155715) == (null)) ? undefined : gensym___175155715.propVar4)})) !== (undefined))) { + (this).__backing_propVar4!.update((initializers!.propVar4 as Set)); + } + if (((({let gensym___134530703 = initializers; + (((gensym___134530703) == (null)) ? undefined : gensym___134530703.propVar5)})) !== (undefined))) { + (this).__backing_propVar5!.update((initializers!.propVar5 as Array)); + } + if (((({let gensym___211600890 = initializers; + (((gensym___211600890) == (null)) ? undefined : gensym___211600890.propVar6)})) !== (undefined))) { + (this).__backing_propVar6!.update((initializers!.propVar6 as Array)); + } + if (((({let gensym___124229427 = initializers; + (((gensym___124229427) == (null)) ? undefined : gensym___124229427.propVar7)})) !== (undefined))) { + (this).__backing_propVar7!.update((initializers!.propVar7 as Array)); + } + if (((({let gensym___248056380 = initializers; + (((gensym___248056380) == (null)) ? undefined : gensym___248056380.propVar8)})) !== (undefined))) { + (this).__backing_propVar8!.update((initializers!.propVar8 as ((sr: string)=> void))); + } + if (((({let gensym___55399278 = initializers; + (((gensym___55399278) == (null)) ? undefined : gensym___55399278.propVar9)})) !== (undefined))) { + (this).__backing_propVar9!.update((initializers!.propVar9 as Date)); + } + if (((({let gensym___125042885 = initializers; + (((gensym___125042885) == (null)) ? undefined : gensym___125042885.propVar10)})) !== (undefined))) { + (this).__backing_propVar10!.update((initializers!.propVar10 as Map)); + } + if (((({let gensym___2015283 = initializers; + (((gensym___2015283) == (null)) ? undefined : gensym___2015283.propVar11)})) !== (undefined))) { + (this).__backing_propVar11!.update((initializers!.propVar11 as string | number)); + } + if (((({let gensym___39009414 = initializers; + (((gensym___39009414) == (null)) ? undefined : gensym___39009414.propVar12)})) !== (undefined))) { + (this).__backing_propVar12!.update((initializers!.propVar12 as Set | Per)); + } + } + private __backing_propVar1?: PropDecoratedVariable; + public get propVar1(): Per { + return (this).__backing_propVar1!.get(); + } + public set propVar1(value: Per) { + (this).__backing_propVar1!.set(value); + } + private __backing_propVar2?: PropDecoratedVariable>; + public get propVar2(): Array { + return (this).__backing_propVar2!.get(); + } + public set propVar2(value: Array) { + (this).__backing_propVar2!.set(value); + } + private __backing_propVar3?: PropDecoratedVariable; + public get propVar3(): PropType { + return (this).__backing_propVar3!.get(); + } + public set propVar3(value: PropType) { + (this).__backing_propVar3!.set(value); + } + private __backing_propVar4?: PropDecoratedVariable>; + public get propVar4(): Set { + return (this).__backing_propVar4!.get(); + } + public set propVar4(value: Set) { + (this).__backing_propVar4!.set(value); + } + private __backing_propVar5?: PropDecoratedVariable>; + public get propVar5(): Array { + return (this).__backing_propVar5!.get(); + } + public set propVar5(value: Array) { + (this).__backing_propVar5!.set(value); + } + private __backing_propVar6?: PropDecoratedVariable>; + public get propVar6(): Array { + return (this).__backing_propVar6!.get(); + } + public set propVar6(value: Array) { + (this).__backing_propVar6!.set(value); + } + private __backing_propVar7?: PropDecoratedVariable>; + public get propVar7(): Array { + return (this).__backing_propVar7!.get(); + } + public set propVar7(value: Array) { + (this).__backing_propVar7!.set(value); + } + private __backing_propVar8?: PropDecoratedVariable<((sr: string)=> void)>; + public get propVar8(): ((sr: string)=> void) { + return (this).__backing_propVar8!.get(); + } + public set propVar8(value: ((sr: string)=> void)) { + (this).__backing_propVar8!.set(value); + } + private __backing_propVar9?: PropDecoratedVariable; + public get propVar9(): Date { + return (this).__backing_propVar9!.get(); + } + public set propVar9(value: Date) { + (this).__backing_propVar9!.set(value); + } + private __backing_propVar10?: PropDecoratedVariable>; + public get propVar10(): Map { + return (this).__backing_propVar10!.get(); + } + public set propVar10(value: Map) { + (this).__backing_propVar10!.set(value); + } + private __backing_propVar11?: PropDecoratedVariable; + public get propVar11(): string | number { + return (this).__backing_propVar11!.get(); + } + public set propVar11(value: string | number) { + (this).__backing_propVar11!.set(value); + } + private __backing_propVar12?: PropDecoratedVariable | Per>; + public get propVar12(): Set | Per { + return (this).__backing_propVar12!.get(); + } + public set propVar12(value: Set | Per) { + (this).__backing_propVar12!.set(value); + } + @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} + public constructor() {} +} + +interface __Options_Parent { + set propVar1(propVar1: Per | undefined) + get propVar1(): Per | undefined + set __backing_propVar1(__backing_propVar1: PropDecoratedVariable | undefined) + get __backing_propVar1(): PropDecoratedVariable | undefined + set propVar2(propVar2: Array | undefined) + get propVar2(): Array | undefined + set __backing_propVar2(__backing_propVar2: PropDecoratedVariable> | undefined) + get __backing_propVar2(): PropDecoratedVariable> | undefined + set propVar3(propVar3: PropType | undefined) + get propVar3(): PropType | undefined + set __backing_propVar3(__backing_propVar3: PropDecoratedVariable | undefined) + get __backing_propVar3(): PropDecoratedVariable | undefined + set propVar4(propVar4: Set | undefined) + get propVar4(): Set | undefined + set __backing_propVar4(__backing_propVar4: PropDecoratedVariable> | undefined) + get __backing_propVar4(): PropDecoratedVariable> | undefined + set propVar5(propVar5: Array | undefined) + get propVar5(): Array | undefined + set __backing_propVar5(__backing_propVar5: PropDecoratedVariable> | undefined) + get __backing_propVar5(): PropDecoratedVariable> | undefined + set propVar6(propVar6: Array | undefined) + get propVar6(): Array | undefined + set __backing_propVar6(__backing_propVar6: PropDecoratedVariable> | undefined) + get __backing_propVar6(): PropDecoratedVariable> | undefined + set propVar7(propVar7: Array | undefined) + get propVar7(): Array | undefined + set __backing_propVar7(__backing_propVar7: PropDecoratedVariable> | undefined) + get __backing_propVar7(): PropDecoratedVariable> | undefined + set propVar8(propVar8: ((sr: string)=> void) | undefined) + get propVar8(): ((sr: string)=> void) | undefined + set __backing_propVar8(__backing_propVar8: PropDecoratedVariable<((sr: string)=> void)> | undefined) + get __backing_propVar8(): PropDecoratedVariable<((sr: string)=> void)> | undefined + set propVar9(propVar9: Date | undefined) + get propVar9(): Date | undefined + set __backing_propVar9(__backing_propVar9: PropDecoratedVariable | undefined) + get __backing_propVar9(): PropDecoratedVariable | undefined + set propVar10(propVar10: Map | undefined) + get propVar10(): Map | undefined + set __backing_propVar10(__backing_propVar10: PropDecoratedVariable> | undefined) + get __backing_propVar10(): PropDecoratedVariable> | undefined + set propVar11(propVar11: string | number | undefined) + get propVar11(): string | number | undefined + set __backing_propVar11(__backing_propVar11: PropDecoratedVariable | undefined) + get __backing_propVar11(): PropDecoratedVariable | undefined + set propVar12(propVar12: Set | Per | undefined) + get propVar12(): Set | Per | undefined + set __backing_propVar12(__backing_propVar12: PropDecoratedVariable | Per> | undefined) + get __backing_propVar12(): PropDecoratedVariable | Per> | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test complex type @Prop decorated variables transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts new file mode 100644 index 000000000..787797bc6 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/prop'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-to-prop.ets'), +]; + +const pluginTester = new PluginTester('test @Prop decorated variables passing', buildConfig); + +const parsedTransform: Plugins = { + name: 'state-to-prop', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, Text as Text, Button as Button, Column as Column, ClickEvent as ClickEvent } from "@ohos.arkui.component"; +import { Prop as Prop, State as State } from "@ohos.arkui.stateManagement"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class CountDownComponent extends CustomComponent { + public __initializeStruct(initializers: __Options_CountDownComponent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_count = new PropDecoratedVariable("count", ((({let gensym___58710805 = initializers; + (((gensym___58710805) == (null)) ? undefined : gensym___58710805.count)})) ?? (0))); + (this).__backing_costOfOneAttempt = ((({let gensym___88948111 = initializers; + (((gensym___88948111) == (null)) ? undefined : gensym___88948111.costOfOneAttempt)})) ?? (1)); + } + public __updateStruct(initializers: __Options_CountDownComponent | undefined): void { + if (((({let gensym___188547633 = initializers; + (((gensym___188547633) == (null)) ? undefined : gensym___188547633.count)})) !== (undefined))) { + (this).__backing_count!.update((initializers!.count as number)); + } + } + private __backing_count?: PropDecoratedVariable; + public get count(): number { + return (this).__backing_count!.get(); + } + public set count(value: number) { + (this).__backing_count!.set(value); + } + private __backing_costOfOneAttempt?: number; + public get costOfOneAttempt(): number { + return ((this).__backing_costOfOneAttempt as number); + } + public set costOfOneAttempt(value: number) { + (this).__backing_costOfOneAttempt = value; + } + + @memo() public _build(@memo() style: ((instance: CountDownComponent)=> CountDownComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CountDownComponent | undefined): void { + Column(undefined, undefined, (() => { + if ((((this).count) > (0))) { + Text(undefined, (((("You have") + ((this).count))) + ("Nuggets left")), undefined, undefined); + } else { + Text(undefined, "Game over!", undefined, undefined); + } + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.onClick(((e: ClickEvent) => { + (this).count -= (this).costOfOneAttempt; + })); + return; + }), "Try again", undefined, undefined); + })); + } + public constructor() {} +} + +@Component({freezeWhenInactive:false}) final class ParentComponent extends CustomComponent { + public __initializeStruct(initializers: __Options_ParentComponent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_countDownStartValue = new StateDecoratedVariable("countDownStartValue", ((({let gensym___249912438 = initializers; + (((gensym___249912438) == (null)) ? undefined : gensym___249912438.countDownStartValue)})) ?? (10))); + } + public __updateStruct(initializers: __Options_ParentComponent | undefined): void {} + private __backing_countDownStartValue?: StateDecoratedVariable; + public get countDownStartValue(): number { + return (this).__backing_countDownStartValue!.get(); + } + public set countDownStartValue(value: number) { + (this).__backing_countDownStartValue!.set(value); + } + @memo() public _build(@memo() style: ((instance: ParentComponent)=> ParentComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ParentComponent | undefined): void { + Column(undefined, undefined, (() => { + Text(undefined, (((("Grant") + ((this).countDownStartValue))) + ("nuggets to play.")), undefined, undefined); + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.onClick(((e: ClickEvent) => { + (this).countDownStartValue += 1; + })); + return; + }), "+1 - Nuggets in New Game", undefined, undefined); + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.onClick(((e: ClickEvent) => { + (this).countDownStartValue -= 1; + })); + return; + }), "-1 - Nuggets in New Game", undefined, undefined); + CountDownComponent._instantiateImpl(undefined, (() => { + return new CountDownComponent(); + }), ({ + count: (this).countDownStartValue, + costOfOneAttempt: 2, + } as __Options_CountDownComponent), undefined, undefined); + })); + } + public constructor() {} +} + +interface __Options_CountDownComponent { + set count(count: number | undefined) + get count(): number | undefined + set __backing_count(__backing_count: PropDecoratedVariable | undefined) + get __backing_count(): PropDecoratedVariable | undefined + set costOfOneAttempt(costOfOneAttempt: number | undefined) + get costOfOneAttempt(): number | undefined +} + +interface __Options_ParentComponent { + set countDownStartValue(countDownStartValue: number | undefined) + get countDownStartValue(): number | undefined + set __backing_countDownStartValue(__backing_countDownStartValue: StateDecoratedVariable | undefined) + get __backing_countDownStartValue(): StateDecoratedVariable | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test @Prop decorated variables passing', + [parsedTransform, uiNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts new file mode 100644 index 000000000..5239317ac --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/provide-and-consume'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'provide-annotation-usage.ets'), +]; + +const pluginTester = new PluginTester('test different @Provide annotation usage transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'provide-annotation-usage', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { Provide as Provide } from "@ohos.arkui.stateManagement"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class Ancestors extends CustomComponent { + public __initializeStruct(initializers: __Options_Ancestors | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_count = (this).addProvidedVar("count", "count", ((({let gensym___58710805 = initializers; + (((gensym___58710805) == (null)) ? undefined : gensym___58710805.count)})) ?? ("Child0")), false); + (this).__backing_count1 = (this).addProvidedVar("count1", "prov1", ((({let gensym___84874570 = initializers; + (((gensym___84874570) == (null)) ? undefined : gensym___84874570.count1)})) ?? ("Child1")), false); + (this).__backing_count2 = (this).addProvidedVar("count2", "prov2", ((({let gensym___124037738 = initializers; + (((gensym___124037738) == (null)) ? undefined : gensym___124037738.count2)})) ?? ("Child2")), false); + (this).__backing_count3 = (this).addProvidedVar("count3", "prov3", ((({let gensym___199202238 = initializers; + (((gensym___199202238) == (null)) ? undefined : gensym___199202238.count3)})) ?? ("Child3")), true); + (this).__backing_count4 = (this).addProvidedVar("count4", "count4", ((({let gensym___4359740 = initializers; + (((gensym___4359740) == (null)) ? undefined : gensym___4359740.count4)})) ?? ("Child4")), false); + (this).__backing_count5 = (this).addProvidedVar("count5", "count5", ((({let gensym___208755050 = initializers; + (((gensym___208755050) == (null)) ? undefined : gensym___208755050.count5)})) ?? ("Child5")), true); + (this).__backing_count6 = (this).addProvidedVar("count6", "", ((({let gensym___37571585 = initializers; + (((gensym___37571585) == (null)) ? undefined : gensym___37571585.count6)})) ?? ("Child6")), true); + (this).__backing_count7 = (this).addProvidedVar("count7", "", ((({let gensym___2162781 = initializers; + (((gensym___2162781) == (null)) ? undefined : gensym___2162781.count7)})) ?? ("Child7")), false); + } + public __updateStruct(initializers: __Options_Ancestors | undefined): void {} + private __backing_count?: ProvideDecoratedVariable; + public get count(): string | undefined { + return (this).__backing_count!.get(); + } + public set count(value: string | undefined) { + (this).__backing_count!.set(value); + } + private __backing_count1?: ProvideDecoratedVariable; + public get count1(): string | undefined { + return (this).__backing_count1!.get(); + } + public set count1(value: string | undefined) { + (this).__backing_count1!.set(value); + } + private __backing_count2?: ProvideDecoratedVariable; + public get count2(): string | undefined { + return (this).__backing_count2!.get(); + } + public set count2(value: string | undefined) { + (this).__backing_count2!.set(value); + } + private __backing_count3?: ProvideDecoratedVariable; + public get count3(): string | undefined { + return (this).__backing_count3!.get(); + } + public set count3(value: string | undefined) { + (this).__backing_count3!.set(value); + } + private __backing_count4?: ProvideDecoratedVariable; + public get count4(): string | undefined { + return (this).__backing_count4!.get(); + } + public set count4(value: string | undefined) { + (this).__backing_count4!.set(value); + } + private __backing_count5?: ProvideDecoratedVariable; + public get count5(): string | undefined { + return (this).__backing_count5!.get(); + } + public set count5(value: string | undefined) { + (this).__backing_count5!.set(value); + } + private __backing_count6?: ProvideDecoratedVariable; + public get count6(): string | undefined { + return (this).__backing_count6!.get(); + } + public set count6(value: string | undefined) { + (this).__backing_count6!.set(value); + } + private __backing_count7?: ProvideDecoratedVariable; + public get count7(): string | undefined { + return (this).__backing_count7!.get(); + } + public set count7(value: string | undefined) { + (this).__backing_count7!.set(value); + } + @memo() public _build(@memo() style: ((instance: Ancestors)=> Ancestors) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Ancestors | undefined): void {} + public constructor() {} +} + +interface __Options_Ancestors { + set count(count: string | undefined | undefined) + get count(): string | undefined | undefined + set __backing_count(__backing_count: ProvideDecoratedVariable | undefined) + get __backing_count(): ProvideDecoratedVariable | undefined + set count1(count1: string | undefined | undefined) + get count1(): string | undefined | undefined + set __backing_count1(__backing_count1: ProvideDecoratedVariable | undefined) + get __backing_count1(): ProvideDecoratedVariable | undefined + set count2(count2: string | undefined | undefined) + get count2(): string | undefined | undefined + set __backing_count2(__backing_count2: ProvideDecoratedVariable | undefined) + get __backing_count2(): ProvideDecoratedVariable | undefined + set count3(count3: string | undefined | undefined) + get count3(): string | undefined | undefined + set __backing_count3(__backing_count3: ProvideDecoratedVariable | undefined) + get __backing_count3(): ProvideDecoratedVariable | undefined + set count4(count4: string | undefined | undefined) + get count4(): string | undefined | undefined + set __backing_count4(__backing_count4: ProvideDecoratedVariable | undefined) + get __backing_count4(): ProvideDecoratedVariable | undefined + set count5(count5: string | undefined | undefined) + get count5(): string | undefined | undefined + set __backing_count5(__backing_count5: ProvideDecoratedVariable | undefined) + get __backing_count5(): ProvideDecoratedVariable | undefined + set count6(count6: string | undefined | undefined) + get count6(): string | undefined | undefined + set __backing_count6(__backing_count6: ProvideDecoratedVariable | undefined) + get __backing_count6(): ProvideDecoratedVariable | undefined + set count7(count7: string | undefined | undefined) + get count7(): string | undefined | undefined + set __backing_count7(__backing_count7: ProvideDecoratedVariable | undefined) + get __backing_count7(): ProvideDecoratedVariable | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test different @Provide annotation usage transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts new file mode 100644 index 000000000..8ce1a14e5 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/provide-and-consume'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'provide-basic-type.ets'), +]; + +const pluginTester = new PluginTester('test basic type @Provide decorated variables transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'provide-basic-type', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { Provide as Provide } from "@ohos.arkui.stateManagement"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class PropParent extends CustomComponent { + public __initializeStruct(initializers: __Options_PropParent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_provideVar1 = (this).addProvidedVar("provideVar1", "provideVar1", ((({let gensym___181030638 = initializers; + (((gensym___181030638) == (null)) ? undefined : gensym___181030638.provideVar1)})) ?? ("propVar1")), false); + (this).__backing_provideVar2 = (this).addProvidedVar("provideVar2", "provideVar2", ((({let gensym___143944235 = initializers; + (((gensym___143944235) == (null)) ? undefined : gensym___143944235.provideVar2)})) ?? (50)), false); + (this).__backing_provideVar3 = (this).addProvidedVar("provideVar3", "provideVar3", ((({let gensym___262195977 = initializers; + (((gensym___262195977) == (null)) ? undefined : gensym___262195977.provideVar3)})) ?? (true)), false); + (this).__backing_provideVar4 = (this).addProvidedVar("provideVar4", "provideVar4", ((({let gensym___85711435 = initializers; + (((gensym___85711435) == (null)) ? undefined : gensym___85711435.provideVar4)})) ?? (undefined)), false); + (this).__backing_provideVar5 = (this).addProvidedVar("provideVar5", "provideVar5", ((({let gensym___139253630 = initializers; + (((gensym___139253630) == (null)) ? undefined : gensym___139253630.provideVar5)})) ?? (null)), false); + } + public __updateStruct(initializers: __Options_PropParent | undefined): void {} + private __backing_provideVar1?: ProvideDecoratedVariable; + public get provideVar1(): string { + return (this).__backing_provideVar1!.get(); + } + public set provideVar1(value: string) { + (this).__backing_provideVar1!.set(value); + } + private __backing_provideVar2?: ProvideDecoratedVariable; + public get provideVar2(): number { + return (this).__backing_provideVar2!.get(); + } + public set provideVar2(value: number) { + (this).__backing_provideVar2!.set(value); + } + private __backing_provideVar3?: ProvideDecoratedVariable; + public get provideVar3(): boolean { + return (this).__backing_provideVar3!.get(); + } + public set provideVar3(value: boolean) { + (this).__backing_provideVar3!.set(value); + } + private __backing_provideVar4?: ProvideDecoratedVariable; + public get provideVar4(): undefined { + return (this).__backing_provideVar4!.get(); + } + public set provideVar4(value: undefined) { + (this).__backing_provideVar4!.set(value); + } + private __backing_provideVar5?: ProvideDecoratedVariable; + public get provideVar5(): null { + return (this).__backing_provideVar5!.get(); + } + public set provideVar5(value: null) { + (this).__backing_provideVar5!.set(value); + } + @memo() public _build(@memo() style: ((instance: PropParent)=> PropParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_PropParent | undefined): void {} + public constructor() {} +} + +interface __Options_PropParent { + set provideVar1(provideVar1: string | undefined) + get provideVar1(): string | undefined + set __backing_provideVar1(__backing_provideVar1: ProvideDecoratedVariable | undefined) + get __backing_provideVar1(): ProvideDecoratedVariable | undefined + set provideVar2(provideVar2: number | undefined) + get provideVar2(): number | undefined + set __backing_provideVar2(__backing_provideVar2: ProvideDecoratedVariable | undefined) + get __backing_provideVar2(): ProvideDecoratedVariable | undefined + set provideVar3(provideVar3: boolean | undefined) + get provideVar3(): boolean | undefined + set __backing_provideVar3(__backing_provideVar3: ProvideDecoratedVariable | undefined) + get __backing_provideVar3(): ProvideDecoratedVariable | undefined + set provideVar4(provideVar4: undefined | undefined) + get provideVar4(): undefined | undefined + set __backing_provideVar4(__backing_provideVar4: ProvideDecoratedVariable | undefined) + get __backing_provideVar4(): ProvideDecoratedVariable | undefined + set provideVar5(provideVar5: null | undefined) + get provideVar5(): null | undefined + set __backing_provideVar5(__backing_provideVar5: ProvideDecoratedVariable | undefined) + get __backing_provideVar5(): ProvideDecoratedVariable | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test basic type @Provide decorated variables transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts new file mode 100644 index 000000000..0a2eb5ae7 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/provide-and-consume'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'provide-complex-type.ets'), +]; + +const pluginTester = new PluginTester('test complex type @Provide decorated variables transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'provide-complex-type', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { Provide as Provide } from "@ohos.arkui.stateManagement"; + +function main() {} + +class Per { + public num: number; + public constructor(num: number) { + (this).num = num; + } +} + +final class PropType extends BaseEnum { + private readonly #ordinal: int; + private static () {} + public constructor(ordinal: int, value: int) { + super(value); + (this).#ordinal = ordinal; + } + public static readonly TYPE1: PropType = new PropType(0, 0); + public static readonly TYPE2: PropType = new PropType(1, 1); + public static readonly TYPE3: PropType = new PropType(2, 3); + private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; + private static readonly #ValuesArray: int[] = [0, 1, 3]; + private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; + private static readonly #ItemsArray: PropType[] = [PropType.TYPE1, PropType.TYPE2, PropType.TYPE3]; + public getName(): String { + return PropType.#NamesArray[(this).#ordinal]; + } + public static getValueOf(name: String): PropType { + for (let i = 0;((i) < (PropType.#NamesArray.length));(++i)) { + if (((name) == (PropType.#NamesArray[i]))) { + return PropType.#ItemsArray[i]; + } + } + throw new Error((("No enum constant PropType.") + (name))); + } + public static fromValue(value: int): PropType { + for (let i = 0;((i) < (PropType.#ValuesArray.length));(++i)) { + if (((value) == (PropType.#ValuesArray[i]))) { + return PropType.#ItemsArray[i]; + } + } + throw new Error((("No enum PropType with value ") + (value))); + } + public valueOf(): int { + return PropType.#ValuesArray[(this).#ordinal]; + } + public toString(): String { + return PropType.#StringValuesArray[(this).#ordinal]; + } + public static values(): PropType[] { + return PropType.#ItemsArray; + } + public getOrdinal(): int { + return (this).#ordinal; + } + public static $_get(e: PropType): String { + return e.getName(); + } +} + +@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { + public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_provideVar1 = (this).addProvidedVar("provideVar1", "provideVar1", ((({let gensym___181030638 = initializers; + (((gensym___181030638) == (null)) ? undefined : gensym___181030638.provideVar1)})) ?? (new Per(6))), false); + (this).__backing_provideVar2 = (this).addProvidedVar>("provideVar2", "provideVar2", ((({let gensym___143944235 = initializers; + (((gensym___143944235) == (null)) ? undefined : gensym___143944235.provideVar2)})) ?? (new Array(3, 6, 8))), false); + (this).__backing_provideVar3 = (this).addProvidedVar("provideVar3", "provideVar3", ((({let gensym___262195977 = initializers; + (((gensym___262195977) == (null)) ? undefined : gensym___262195977.provideVar3)})) ?? (PropType.TYPE3)), false); + (this).__backing_provideVar4 = (this).addProvidedVar>("provideVar4", "provideVar4", ((({let gensym___85711435 = initializers; + (((gensym___85711435) == (null)) ? undefined : gensym___85711435.provideVar4)})) ?? (new Set(new Array("aa", "bb")))), false); + (this).__backing_provideVar5 = (this).addProvidedVar>("provideVar5", "provideVar5", ((({let gensym___139253630 = initializers; + (((gensym___139253630) == (null)) ? undefined : gensym___139253630.provideVar5)})) ?? ([true, false])), false); + (this).__backing_provideVar6 = (this).addProvidedVar>("provideVar6", "provideVar6", ((({let gensym___146872112 = initializers; + (((gensym___146872112) == (null)) ? undefined : gensym___146872112.provideVar6)})) ?? (new Array(new Per(7), new Per(11)))), false); + (this).__backing_provideVar7 = (this).addProvidedVar>("provideVar7", "provideVar7", ((({let gensym___174412117 = initializers; + (((gensym___174412117) == (null)) ? undefined : gensym___174412117.provideVar7)})) ?? ([new Per(7), new Per(11)])), false); + (this).__backing_provideVar8 = (this).addProvidedVar<((sr: string)=> void)>("provideVar8", "provideVar8", ((({let gensym___253467853 = initializers; + (((gensym___253467853) == (null)) ? undefined : gensym___253467853.provideVar8)})) ?? (((sr: string) => {}))), false); + (this).__backing_provideVar9 = (this).addProvidedVar("provideVar9", "provideVar9", ((({let gensym___179115605 = initializers; + (((gensym___179115605) == (null)) ? undefined : gensym___179115605.provideVar9)})) ?? (new Date("2025-4-23"))), false); + (this).__backing_provideVar10 = (this).addProvidedVar>("provideVar10", "provideVar10", ((({let gensym___209671248 = initializers; + (((gensym___209671248) == (null)) ? undefined : gensym___209671248.provideVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]]))), false); + (this).__backing_provideVar11 = (this).addProvidedVar("provideVar11", "provideVar11", ((({let gensym___150211849 = initializers; + (((gensym___150211849) == (null)) ? undefined : gensym___150211849.provideVar11)})) ?? (0.0)), false); + (this).__backing_provideVar12 = (this).addProvidedVar | Per>("provideVar12", "provideVar12", ((({let gensym___256025818 = initializers; + (((gensym___256025818) == (null)) ? undefined : gensym___256025818.provideVar12)})) ?? (new Per(6))), false); + } + public __updateStruct(initializers: __Options_Parent | undefined): void {} + private __backing_provideVar1?: ProvideDecoratedVariable; + public get provideVar1(): Per { + return (this).__backing_provideVar1!.get(); + } + public set provideVar1(value: Per) { + (this).__backing_provideVar1!.set(value); + } + private __backing_provideVar2?: ProvideDecoratedVariable>; + public get provideVar2(): Array { + return (this).__backing_provideVar2!.get(); + } + public set provideVar2(value: Array) { + (this).__backing_provideVar2!.set(value); + } + private __backing_provideVar3?: ProvideDecoratedVariable; + public get provideVar3(): PropType { + return (this).__backing_provideVar3!.get(); + } + public set provideVar3(value: PropType) { + (this).__backing_provideVar3!.set(value); + } + private __backing_provideVar4?: ProvideDecoratedVariable>; + public get provideVar4(): Set { + return (this).__backing_provideVar4!.get(); + } + public set provideVar4(value: Set) { + (this).__backing_provideVar4!.set(value); + } + private __backing_provideVar5?: ProvideDecoratedVariable>; + public get provideVar5(): Array { + return (this).__backing_provideVar5!.get(); + } + public set provideVar5(value: Array) { + (this).__backing_provideVar5!.set(value); + } + private __backing_provideVar6?: ProvideDecoratedVariable>; + public get provideVar6(): Array { + return (this).__backing_provideVar6!.get(); + } + public set provideVar6(value: Array) { + (this).__backing_provideVar6!.set(value); + } + private __backing_provideVar7?: ProvideDecoratedVariable>; + public get provideVar7(): Array { + return (this).__backing_provideVar7!.get(); + } + public set provideVar7(value: Array) { + (this).__backing_provideVar7!.set(value); + } + private __backing_provideVar8?: ProvideDecoratedVariable<((sr: string)=> void)>; + public get provideVar8(): ((sr: string)=> void) { + return (this).__backing_provideVar8!.get(); + } + public set provideVar8(value: ((sr: string)=> void)) { + (this).__backing_provideVar8!.set(value); + } + private __backing_provideVar9?: ProvideDecoratedVariable; + public get provideVar9(): Date { + return (this).__backing_provideVar9!.get(); + } + public set provideVar9(value: Date) { + (this).__backing_provideVar9!.set(value); + } + private __backing_provideVar10?: ProvideDecoratedVariable>; + public get provideVar10(): Map { + return (this).__backing_provideVar10!.get(); + } + public set provideVar10(value: Map) { + (this).__backing_provideVar10!.set(value); + } + private __backing_provideVar11?: ProvideDecoratedVariable; + public get provideVar11(): string | number { + return (this).__backing_provideVar11!.get(); + } + public set provideVar11(value: string | number) { + (this).__backing_provideVar11!.set(value); + } + private __backing_provideVar12?: ProvideDecoratedVariable | Per>; + public get provideVar12(): Set | Per { + return (this).__backing_provideVar12!.get(); + } + public set provideVar12(value: Set | Per) { + (this).__backing_provideVar12!.set(value); + } + @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} + public constructor() {} +} + +interface __Options_Parent { + set provideVar1(provideVar1: Per | undefined) + get provideVar1(): Per | undefined + set __backing_provideVar1(__backing_provideVar1: ProvideDecoratedVariable | undefined) + get __backing_provideVar1(): ProvideDecoratedVariable | undefined + set provideVar2(provideVar2: Array | undefined) + get provideVar2(): Array | undefined + set __backing_provideVar2(__backing_provideVar2: ProvideDecoratedVariable> | undefined) + get __backing_provideVar2(): ProvideDecoratedVariable> | undefined + set provideVar3(provideVar3: PropType | undefined) + get provideVar3(): PropType | undefined + set __backing_provideVar3(__backing_provideVar3: ProvideDecoratedVariable | undefined) + get __backing_provideVar3(): ProvideDecoratedVariable | undefined + set provideVar4(provideVar4: Set | undefined) + get provideVar4(): Set | undefined + set __backing_provideVar4(__backing_provideVar4: ProvideDecoratedVariable> | undefined) + get __backing_provideVar4(): ProvideDecoratedVariable> | undefined + set provideVar5(provideVar5: Array | undefined) + get provideVar5(): Array | undefined + set __backing_provideVar5(__backing_provideVar5: ProvideDecoratedVariable> | undefined) + get __backing_provideVar5(): ProvideDecoratedVariable> | undefined + set provideVar6(provideVar6: Array | undefined) + get provideVar6(): Array | undefined + set __backing_provideVar6(__backing_provideVar6: ProvideDecoratedVariable> | undefined) + get __backing_provideVar6(): ProvideDecoratedVariable> | undefined + set provideVar7(provideVar7: Array | undefined) + get provideVar7(): Array | undefined + set __backing_provideVar7(__backing_provideVar7: ProvideDecoratedVariable> | undefined) + get __backing_provideVar7(): ProvideDecoratedVariable> | undefined + set provideVar8(provideVar8: ((sr: string)=> void) | undefined) + get provideVar8(): ((sr: string)=> void) | undefined + set __backing_provideVar8(__backing_provideVar8: ProvideDecoratedVariable<((sr: string)=> void)> | undefined) + get __backing_provideVar8(): ProvideDecoratedVariable<((sr: string)=> void)> | undefined + set provideVar9(provideVar9: Date | undefined) + get provideVar9(): Date | undefined + set __backing_provideVar9(__backing_provideVar9: ProvideDecoratedVariable | undefined) + get __backing_provideVar9(): ProvideDecoratedVariable | undefined + set provideVar10(provideVar10: Map | undefined) + get provideVar10(): Map | undefined + set __backing_provideVar10(__backing_provideVar10: ProvideDecoratedVariable> | undefined) + get __backing_provideVar10(): ProvideDecoratedVariable> | undefined + set provideVar11(provideVar11: string | number | undefined) + get provideVar11(): string | number | undefined + set __backing_provideVar11(__backing_provideVar11: ProvideDecoratedVariable | undefined) + get __backing_provideVar11(): ProvideDecoratedVariable | undefined + set provideVar12(provideVar12: Set | Per | undefined) + get provideVar12(): Set | Per | undefined + set __backing_provideVar12(__backing_provideVar12: ProvideDecoratedVariable | Per> | undefined) + get __backing_provideVar12(): ProvideDecoratedVariable | Per> | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test complex type @Provide decorated variables transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts new file mode 100644 index 000000000..e8aa44ac8 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/resource'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'resource-in-build.ets'), +]; + +const pluginTester = new PluginTester('test resource transform in build method', buildConfig); + +const parsedTransform: Plugins = { + name: 'resource-in-build', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { UISelectAttribute as UISelectAttribute } from "@ohos.arkui.component"; +import { UITextInputAttribute as UITextInputAttribute } from "@ohos.arkui.component"; +import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { _rawfile as _rawfile } from "@ohos.arkui.component"; +import { _r as _r } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, TextInput as TextInput, Select as Select, SelectOption as SelectOption, Margin as Margin } from "@ohos.arkui.component"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class ResourceComponent extends CustomComponent { + public __initializeStruct(initializers: __Options_ResourceComponent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_str1 = ((({let gensym___147578113 = initializers; + (((gensym___147578113) == (null)) ? undefined : gensym___147578113.str1)})) ?? ("app.media.ri")); + (this).__backing_str2 = ((({let gensym___220149772 = initializers; + (((gensym___220149772) == (null)) ? undefined : gensym___220149772.str2)})) ?? ("app.photo2.png")); + } + public __updateStruct(initializers: __Options_ResourceComponent | undefined): void {} + private __backing_str1?: string; + public get str1(): string { + return ((this).__backing_str1 as string); + } + public set str1(value: string) { + (this).__backing_str1 = value; + } + private __backing_str2?: string; + public get str2(): string { + return ((this).__backing_str2 as string); + } + public set str2(value: string) { + (this).__backing_str2 = value; + } + + @memo() public _build(@memo() style: ((instance: ResourceComponent)=> ResourceComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ResourceComponent | undefined): void { + Column(undefined, undefined, (() => { + Text(undefined, _r("", "", "app.string.app_name"), undefined, undefined); + Image(undefined, _rawfile("", "", "app.photo.png"), undefined, undefined); + TextInput(undefined, { + text: _r("", "", "app.string.input_content"), + }, undefined); + Text(undefined, _r("", "", (this).str1), undefined, undefined); + Text(undefined, _r("", "", (this).str2), undefined, undefined); + Select(undefined, new Array({ + value: "aaa", + icon: _r("", "", "app.media.selection"), + }, { + value: "bbb", + icon: _r("", "", "app.media.selection"), + }, { + value: "ccc", + icon: _r("", "", "app.media.selection"), + }, { + value: "ddd", + icon: _r("", "", "app.media.selection"), + }), undefined); + Image(@memo() ((instance: UIImageAttribute): void => { + instance.margin(({ + top: _r("", "", "app.float.elements_margin_horizontal_m"), + bottom: _r("", "", "app.float.elements_margin_horizontal_l"), + } as Margin)); + return; + }), _r("", "", "app.media.app_icon"), undefined, undefined); + })); + } + public constructor() {} +} + +interface __Options_ResourceComponent { + set str1(str1: string | undefined) + get str1(): string | undefined + set str2(str2: string | undefined) + get str2(): string | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test resource transform in build method', + [parsedTransform, uiNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts new file mode 100644 index 000000000..60451251c --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/resource'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'resource-in-property.ets'), +]; + +const pluginTester = new PluginTester('test resource transform in property', buildConfig); + +const parsedTransform: Plugins = { + name: 'resource-in-property', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { _rawfile as _rawfile } from "@ohos.arkui.component"; +import { _r as _r } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, Resource as Resource } from "@ohos.arkui.component"; + +let i: Resource; +function main() {} +i = _r("", "", "app.string.app_name"); + +@Component({freezeWhenInactive:false}) final class ResourceComponent extends CustomComponent { + public __initializeStruct(initializers: __Options_ResourceComponent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_str = ((({let gensym___42103502 = initializers; + (((gensym___42103502) == (null)) ? undefined : gensym___42103502.str)})) ?? (_r("", "", "app.string.app_name"))); + (this).__backing_icon = ((({let gensym___38135554 = initializers; + (((gensym___38135554) == (null)) ? undefined : gensym___38135554.icon)})) ?? (_rawfile("", "", "app.photo.png"))); + } + public __updateStruct(initializers: __Options_ResourceComponent | undefined): void {} + private __backing_str?: Resource; + public get str(): Resource { + return ((this).__backing_str as Resource); + } + public set str(value: Resource) { + (this).__backing_str = value; + } + private __backing_icon?: Resource; + public get icon(): Resource { + return ((this).__backing_icon as Resource); + } + public set icon(value: Resource) { + (this).__backing_icon = value; + } + @memo() public _build(@memo() style: ((instance: ResourceComponent)=> ResourceComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ResourceComponent | undefined): void { + Column(undefined, undefined, (() => { + Text(undefined, (this).str, undefined, undefined); + Text(undefined, i, undefined, undefined); + Image(undefined, (this).icon, undefined, undefined); + })); + } + public constructor() {} +} + +interface __Options_ResourceComponent { + set str(str: Resource | undefined) + get str(): Resource | undefined + set icon(icon: Resource | undefined) + get icon(): Resource | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test resource transform in property', + [parsedTransform, uiNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts new file mode 100644 index 000000000..a3258fa0b --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/state'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-basic-type.ets'), +]; + +const pluginTester = new PluginTester('test basic type @State decorated variables transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'state-basic-type', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { State as State } from "@ohos.arkui.stateManagement"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { + public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_stateVar1 = new StateDecoratedVariable("stateVar1", ((({let gensym___213853607 = initializers; + (((gensym___213853607) == (null)) ? undefined : gensym___213853607.stateVar1)})) ?? ("stateVar1"))); + (this).__backing_stateVar2 = new StateDecoratedVariable("stateVar2", ((({let gensym___113574154 = initializers; + (((gensym___113574154) == (null)) ? undefined : gensym___113574154.stateVar2)})) ?? (50))); + (this).__backing_stateVar3 = new StateDecoratedVariable("stateVar3", ((({let gensym___166994972 = initializers; + (((gensym___166994972) == (null)) ? undefined : gensym___166994972.stateVar3)})) ?? (true))); + (this).__backing_stateVar4 = new StateDecoratedVariable("stateVar4", ((({let gensym___148024261 = initializers; + (((gensym___148024261) == (null)) ? undefined : gensym___148024261.stateVar4)})) ?? (undefined))); + (this).__backing_stateVar5 = new StateDecoratedVariable("stateVar5", ((({let gensym___99384342 = initializers; + (((gensym___99384342) == (null)) ? undefined : gensym___99384342.stateVar5)})) ?? (null))); + } + public __updateStruct(initializers: __Options_Parent | undefined): void {} + private __backing_stateVar1?: StateDecoratedVariable; + public get stateVar1(): string { + return (this).__backing_stateVar1!.get(); + } + public set stateVar1(value: string) { + (this).__backing_stateVar1!.set(value); + } + private __backing_stateVar2?: StateDecoratedVariable; + public get stateVar2(): number { + return (this).__backing_stateVar2!.get(); + } + public set stateVar2(value: number) { + (this).__backing_stateVar2!.set(value); + } + private __backing_stateVar3?: StateDecoratedVariable; + public get stateVar3(): boolean { + return (this).__backing_stateVar3!.get(); + } + public set stateVar3(value: boolean) { + (this).__backing_stateVar3!.set(value); + } + private __backing_stateVar4?: StateDecoratedVariable; + public get stateVar4(): undefined { + return (this).__backing_stateVar4!.get(); + } + public set stateVar4(value: undefined) { + (this).__backing_stateVar4!.set(value); + } + private __backing_stateVar5?: StateDecoratedVariable; + public get stateVar5(): null { + return (this).__backing_stateVar5!.get(); + } + public set stateVar5(value: null) { + (this).__backing_stateVar5!.set(value); + } + @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} + public constructor() {} +} + +interface __Options_Parent { + set stateVar1(stateVar1: string | undefined) + get stateVar1(): string | undefined + set __backing_stateVar1(__backing_stateVar1: StateDecoratedVariable | undefined) + get __backing_stateVar1(): StateDecoratedVariable | undefined + set stateVar2(stateVar2: number | undefined) + get stateVar2(): number | undefined + set __backing_stateVar2(__backing_stateVar2: StateDecoratedVariable | undefined) + get __backing_stateVar2(): StateDecoratedVariable | undefined + set stateVar3(stateVar3: boolean | undefined) + get stateVar3(): boolean | undefined + set __backing_stateVar3(__backing_stateVar3: StateDecoratedVariable | undefined) + get __backing_stateVar3(): StateDecoratedVariable | undefined + set stateVar4(stateVar4: undefined | undefined) + get stateVar4(): undefined | undefined + set __backing_stateVar4(__backing_stateVar4: StateDecoratedVariable | undefined) + get __backing_stateVar4(): StateDecoratedVariable | undefined + set stateVar5(stateVar5: null | undefined) + get stateVar5(): null | undefined + set __backing_stateVar5(__backing_stateVar5: StateDecoratedVariable | undefined) + get __backing_stateVar5(): StateDecoratedVariable | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test basic type @State decorated variables transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts new file mode 100644 index 000000000..eeec6cdc4 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { structNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/state'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-complex-type.ets'), +]; + +const pluginTester = new PluginTester('test complex type @State decorated variables transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'state-complex-type', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component } from "@ohos.arkui.component"; +import { State as State } from "@ohos.arkui.stateManagement"; + +function main() {} + +class Per { + public num: number; + public constructor(num: number) { + (this).num = num; + } +} + +final class StateType extends BaseEnum { + private readonly #ordinal: int; + private static () {} + public constructor(ordinal: int, value: int) { + super(value); + (this).#ordinal = ordinal; + } + public static readonly TYPE1: StateType = new StateType(0, 0); + public static readonly TYPE2: StateType = new StateType(1, 1); + public static readonly TYPE3: StateType = new StateType(2, 3); + private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; + private static readonly #ValuesArray: int[] = [0, 1, 3]; + private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; + private static readonly #ItemsArray: StateType[] = [StateType.TYPE1, StateType.TYPE2, StateType.TYPE3]; + public getName(): String { + return StateType.#NamesArray[(this).#ordinal]; + } + public static getValueOf(name: String): StateType { + for (let i = 0;((i) < (StateType.#NamesArray.length));(++i)) { + if (((name) == (StateType.#NamesArray[i]))) { + return StateType.#ItemsArray[i]; + } + } + throw new Error((("No enum constant StateType.") + (name))); + } + public static fromValue(value: int): StateType { + for (let i = 0;((i) < (StateType.#ValuesArray.length));(++i)) { + if (((value) == (StateType.#ValuesArray[i]))) { + return StateType.#ItemsArray[i]; + } + } + throw new Error((("No enum StateType with value ") + (value))); + } + public valueOf(): int { + return StateType.#ValuesArray[(this).#ordinal]; + } + public toString(): String { + return StateType.#StringValuesArray[(this).#ordinal]; + } + public static values(): StateType[] { + return StateType.#ItemsArray; + } + public getOrdinal(): int { + return (this).#ordinal; + } + public static $_get(e: StateType): String { + return e.getName(); + } +} + +@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { + public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_stateVar1 = new StateDecoratedVariable("stateVar1", ((({let gensym___213853607 = initializers; + (((gensym___213853607) == (null)) ? undefined : gensym___213853607.stateVar1)})) ?? (new Per(6)))); + (this).__backing_stateVar2 = new StateDecoratedVariable>("stateVar2", ((({let gensym___113574154 = initializers; + (((gensym___113574154) == (null)) ? undefined : gensym___113574154.stateVar2)})) ?? (new Array(3, 6, 8)))); + (this).__backing_stateVar3 = new StateDecoratedVariable("stateVar3", ((({let gensym___166994972 = initializers; + (((gensym___166994972) == (null)) ? undefined : gensym___166994972.stateVar3)})) ?? (StateType.TYPE3))); + (this).__backing_stateVar4 = new StateDecoratedVariable>("stateVar4", ((({let gensym___148024261 = initializers; + (((gensym___148024261) == (null)) ? undefined : gensym___148024261.stateVar4)})) ?? (new Set(new Array("aa", "bb"))))); + (this).__backing_stateVar5 = new StateDecoratedVariable>("stateVar5", ((({let gensym___99384342 = initializers; + (((gensym___99384342) == (null)) ? undefined : gensym___99384342.stateVar5)})) ?? ([true, false]))); + (this).__backing_stateVar6 = new StateDecoratedVariable>("stateVar6", ((({let gensym___133364871 = initializers; + (((gensym___133364871) == (null)) ? undefined : gensym___133364871.stateVar6)})) ?? (new Array(new Per(7), new Per(11))))); + (this).__backing_stateVar7 = new StateDecoratedVariable>("stateVar7", ((({let gensym___69403028 = initializers; + (((gensym___69403028) == (null)) ? undefined : gensym___69403028.stateVar7)})) ?? ([new Per(7), new Per(11)]))); + (this).__backing_stateVar8 = new StateDecoratedVariable<((sr: string)=> void)>("stateVar8", ((({let gensym___219403122 = initializers; + (((gensym___219403122) == (null)) ? undefined : gensym___219403122.stateVar8)})) ?? (((sr: string) => {})))); + (this).__backing_stateVar9 = new StateDecoratedVariable("stateVar9", ((({let gensym___171171899 = initializers; + (((gensym___171171899) == (null)) ? undefined : gensym___171171899.stateVar9)})) ?? (new Date("2025-4-23")))); + (this).__backing_stateVar10 = new StateDecoratedVariable>("stateVar10", ((({let gensym___91651348 = initializers; + (((gensym___91651348) == (null)) ? undefined : gensym___91651348.stateVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]])))); + (this).__backing_stateVar11 = new StateDecoratedVariable("stateVar11", ((({let gensym___56045278 = initializers; + (((gensym___56045278) == (null)) ? undefined : gensym___56045278.stateVar11)})) ?? (0.0))); + (this).__backing_stateVar12 = new StateDecoratedVariable | Per>("stateVar12", ((({let gensym___164759887 = initializers; + (((gensym___164759887) == (null)) ? undefined : gensym___164759887.stateVar12)})) ?? (new Per(6)))); + } + public __updateStruct(initializers: __Options_Parent | undefined): void {} + private __backing_stateVar1?: StateDecoratedVariable; + public get stateVar1(): Per { + return (this).__backing_stateVar1!.get(); + } + public set stateVar1(value: Per) { + (this).__backing_stateVar1!.set(value); + } + private __backing_stateVar2?: StateDecoratedVariable>; + public get stateVar2(): Array { + return (this).__backing_stateVar2!.get(); + } + public set stateVar2(value: Array) { + (this).__backing_stateVar2!.set(value); + } + private __backing_stateVar3?: StateDecoratedVariable; + public get stateVar3(): StateType { + return (this).__backing_stateVar3!.get(); + } + public set stateVar3(value: StateType) { + (this).__backing_stateVar3!.set(value); + } + private __backing_stateVar4?: StateDecoratedVariable>; + public get stateVar4(): Set { + return (this).__backing_stateVar4!.get(); + } + public set stateVar4(value: Set) { + (this).__backing_stateVar4!.set(value); + } + private __backing_stateVar5?: StateDecoratedVariable>; + public get stateVar5(): Array { + return (this).__backing_stateVar5!.get(); + } + public set stateVar5(value: Array) { + (this).__backing_stateVar5!.set(value); + } + private __backing_stateVar6?: StateDecoratedVariable>; + public get stateVar6(): Array { + return (this).__backing_stateVar6!.get(); + } + public set stateVar6(value: Array) { + (this).__backing_stateVar6!.set(value); + } + private __backing_stateVar7?: StateDecoratedVariable>; + public get stateVar7(): Array { + return (this).__backing_stateVar7!.get(); + } + public set stateVar7(value: Array) { + (this).__backing_stateVar7!.set(value); + } + private __backing_stateVar8?: StateDecoratedVariable<((sr: string)=> void)>; + public get stateVar8(): ((sr: string)=> void) { + return (this).__backing_stateVar8!.get(); + } + public set stateVar8(value: ((sr: string)=> void)) { + (this).__backing_stateVar8!.set(value); + } + private __backing_stateVar9?: StateDecoratedVariable; + public get stateVar9(): Date { + return (this).__backing_stateVar9!.get(); + } + public set stateVar9(value: Date) { + (this).__backing_stateVar9!.set(value); + } + private __backing_stateVar10?: StateDecoratedVariable>; + public get stateVar10(): Map { + return (this).__backing_stateVar10!.get(); + } + public set stateVar10(value: Map) { + (this).__backing_stateVar10!.set(value); + } + private __backing_stateVar11?: StateDecoratedVariable; + public get stateVar11(): string | number { + return (this).__backing_stateVar11!.get(); + } + public set stateVar11(value: string | number) { + (this).__backing_stateVar11!.set(value); + } + private __backing_stateVar12?: StateDecoratedVariable | Per>; + public get stateVar12(): Set | Per { + return (this).__backing_stateVar12!.get(); + } + public set stateVar12(value: Set | Per) { + (this).__backing_stateVar12!.set(value); + } + @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} + public constructor() {} +} + +interface __Options_Parent { + set stateVar1(stateVar1: Per | undefined) + get stateVar1(): Per | undefined + set __backing_stateVar1(__backing_stateVar1: StateDecoratedVariable | undefined) + get __backing_stateVar1(): StateDecoratedVariable | undefined + set stateVar2(stateVar2: Array | undefined) + get stateVar2(): Array | undefined + set __backing_stateVar2(__backing_stateVar2: StateDecoratedVariable> | undefined) + get __backing_stateVar2(): StateDecoratedVariable> | undefined + set stateVar3(stateVar3: StateType | undefined) + get stateVar3(): StateType | undefined + set __backing_stateVar3(__backing_stateVar3: StateDecoratedVariable | undefined) + get __backing_stateVar3(): StateDecoratedVariable | undefined + set stateVar4(stateVar4: Set | undefined) + get stateVar4(): Set | undefined + set __backing_stateVar4(__backing_stateVar4: StateDecoratedVariable> | undefined) + get __backing_stateVar4(): StateDecoratedVariable> | undefined + set stateVar5(stateVar5: Array | undefined) + get stateVar5(): Array | undefined + set __backing_stateVar5(__backing_stateVar5: StateDecoratedVariable> | undefined) + get __backing_stateVar5(): StateDecoratedVariable> | undefined + set stateVar6(stateVar6: Array | undefined) + get stateVar6(): Array | undefined + set __backing_stateVar6(__backing_stateVar6: StateDecoratedVariable> | undefined) + get __backing_stateVar6(): StateDecoratedVariable> | undefined + set stateVar7(stateVar7: Array | undefined) + get stateVar7(): Array | undefined + set __backing_stateVar7(__backing_stateVar7: StateDecoratedVariable> | undefined) + get __backing_stateVar7(): StateDecoratedVariable> | undefined + set stateVar8(stateVar8: ((sr: string)=> void) | undefined) + get stateVar8(): ((sr: string)=> void) | undefined + set __backing_stateVar8(__backing_stateVar8: StateDecoratedVariable<((sr: string)=> void)> | undefined) + get __backing_stateVar8(): StateDecoratedVariable<((sr: string)=> void)> | undefined + set stateVar9(stateVar9: Date | undefined) + get stateVar9(): Date | undefined + set __backing_stateVar9(__backing_stateVar9: StateDecoratedVariable | undefined) + get __backing_stateVar9(): StateDecoratedVariable | undefined + set stateVar10(stateVar10: Map | undefined) + get stateVar10(): Map | undefined + set __backing_stateVar10(__backing_stateVar10: StateDecoratedVariable> | undefined) + get __backing_stateVar10(): StateDecoratedVariable> | undefined + set stateVar11(stateVar11: string | number | undefined) + get stateVar11(): string | number | undefined + set __backing_stateVar11(__backing_stateVar11: StateDecoratedVariable | undefined) + get __backing_stateVar11(): StateDecoratedVariable | undefined + set stateVar12(stateVar12: Set | Per | undefined) + get stateVar12(): Set | Per | undefined + set __backing_stateVar12(__backing_stateVar12: StateDecoratedVariable | Per> | undefined) + get __backing_stateVar12(): StateDecoratedVariable | Per> | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test complex type @State decorated variables transformation', + [parsedTransform, structNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts new file mode 100644 index 000000000..eb7d0a500 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/state'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-to-state.ets'), +]; + +const pluginTester = new PluginTester('test @State decorated variables passing', buildConfig); + +const parsedTransform: Plugins = { + name: 'state-to-state', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, Column as Column, Text as Text } from "@ohos.arkui.component"; +import { State as State } from "@ohos.arkui.stateManagement"; + +function main() {} + +class Per { + public str: string; + public constructor(str: string) { + (this).str = str; + } +} + +@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { + public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_parentVar1 = new StateDecoratedVariable("parentVar1", ((({let gensym___247315634 = initializers; + (((gensym___247315634) == (null)) ? undefined : gensym___247315634.parentVar1)})) ?? (new Per("hello")))); + } + public __updateStruct(initializers: __Options_Parent | undefined): void {} + private __backing_parentVar1?: StateDecoratedVariable; + public get parentVar1(): Per { + return (this).__backing_parentVar1!.get(); + } + public set parentVar1(value: Per) { + (this).__backing_parentVar1!.set(value); + } + @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void { + Column(undefined, undefined, (() => { + Child._instantiateImpl(undefined, (() => { + return new Child(); + }), ({ + childVar1: (this).parentVar1, + } as __Options_Child), undefined, undefined); + })); + } + public constructor() {} +} + +@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { + public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_childVar1 = new StateDecoratedVariable("childVar1", ((({let gensym___218939886 = initializers; + (((gensym___218939886) == (null)) ? undefined : gensym___218939886.childVar1)})) ?? (new Per("ccc")))); + } + public __updateStruct(initializers: __Options_Child | undefined): void {} + private __backing_childVar1?: StateDecoratedVariable; + public get childVar1(): Per { + return (this).__backing_childVar1!.get(); + } + public set childVar1(value: Per) { + (this).__backing_childVar1!.set(value); + } + @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { + Text(undefined, (this).childVar1.str, undefined, undefined); + } + public constructor() {} + +} + +interface __Options_Parent { + set parentVar1(parentVar1: Per | undefined) + get parentVar1(): Per | undefined + set __backing_parentVar1(__backing_parentVar1: StateDecoratedVariable | undefined) + get __backing_parentVar1(): StateDecoratedVariable | undefined +} + +interface __Options_Child { + set childVar1(childVar1: Per | undefined) + get childVar1(): Per | undefined + set __backing_childVar1(__backing_childVar1: StateDecoratedVariable | undefined) + get __backing_childVar1(): StateDecoratedVariable | undefined +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test @State decorated variables passing', + [parsedTransform, uiNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 8f25d7715..75429bc42 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -317,6 +317,9 @@ export class ComponentTransformer extends AbstractVisitor { } node.definition.body.map((it) => { if (arkts.isClassProperty(it)) { + if (hasDecorator(it, DecoratorNames.PROVIDE)) { + factory.processNoAliasProvideVariable(it); + } this.context.structMembers.get(className)!.push(...this.createInterfaceInnerMember(it, structInfo)); } }); diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index daa3f4aa5..9005d8d88 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -240,11 +240,11 @@ export function getValueInProvideAnnotation(node: arkts.ClassProperty): ProvideO const annotations: readonly arkts.AnnotationUsage[] = node.annotations; for (let i = 0; i < annotations.length; i++) { const anno: arkts.AnnotationUsage = annotations[i]; - const alias: string | undefined = getValueInObjectAnnotation(anno, DecoratorNames.PROVIDE, 'alias'); - const allowOverride: boolean = getValueInObjectAnnotation(anno, DecoratorNames.PROVIDE, 'allowOverride') - ? true - : false; - if (!!alias) { + if (anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.PROVIDE) { + const alias: string = getValueInObjectAnnotation(anno, DecoratorNames.PROVIDE, 'alias'); + const allowOverride: boolean = getValueInObjectAnnotation(anno, DecoratorNames.PROVIDE, 'allowOverride') + ? true + : false; return { alias, allowOverride }; } } diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index bc2ede8ea..90fefdee5 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -14,8 +14,9 @@ */ import * as arkts from '@koalaui/libarkts'; -import { BuilderLambdaNames, CustomComponentNames } from './utils'; +import { BuilderLambdaNames, CustomComponentNames, hasPropertyInAnnotation } from './utils'; import { annotation } from '../common/arkts-utils'; +import { DecoratorNames } from './property-translators/utils'; export class factory { /** @@ -228,4 +229,45 @@ export class factory { false ); } + + /* + * add alias: to @Provide annotation when no alias in @Provide({...}). + */ + static processNoAliasProvideVariable(property: arkts.ClassProperty): void { + let annotations: readonly arkts.AnnotationUsage[] = property.annotations; + if (annotations.length === 0) { + return; + } + const newAnnos: arkts.AnnotationUsage[] = annotations.map((anno: arkts.AnnotationUsage) => { + if ( + !!anno.expr && + arkts.isIdentifier(anno.expr) && + anno.expr.name === DecoratorNames.PROVIDE && + !hasPropertyInAnnotation(anno, 'alias') && + property.key && + arkts.isIdentifier(property.key) + ) { + return arkts.factory.update1AnnotationUsage(anno, anno.expr, [ + ...anno.properties, + factory.createAliasClassProperty(property.key), + ]); + } else { + return anno; + } + }); + property.setAnnotations(newAnnos); + } + + /* + * create class property : `alias: `. + */ + static createAliasClassProperty(value: arkts.Identifier): arkts.ClassProperty { + return arkts.factory.createClassProperty( + arkts.factory.createIdentifier('alias'), + arkts.factory.create1StringLiteral(value.name), + undefined, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + false + ); + } } diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index 98a79be41..c8a56dd06 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -15,6 +15,7 @@ import * as arkts from '@koalaui/libarkts'; import { annotation } from '../common/arkts-utils'; +import { DecoratorNames } from './property-translators/utils'; export enum CustomComponentNames { ENTRY_ANNOTATION_NAME = 'Entry', @@ -165,3 +166,13 @@ export function addMemoAnnotation(node: T, memoName: stri } return node.setAnnotations(newAnnotations) as T; } + +export function hasPropertyInAnnotation(annotation: arkts.AnnotationUsage, propertyName: string): boolean { + return !!annotation.properties.find( + (annoProp: arkts.AstNode) => + arkts.isClassProperty(annoProp) && + annoProp.key && + arkts.isIdentifier(annoProp.key) && + annoProp.key.name === propertyName + ); +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index c3e6cd06c..d46a22e90 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -117,7 +117,7 @@ import { updateTSTypeParameterInstantiation } from "../node-utilities/TSTypePara import { updateTSInterfaceDeclaration } from "../node-utilities/TSInterfaceDeclaration" import { updateTSInterfaceBody } from "../node-utilities/TSInterfaceBody" import { updateUndefinedLiteral } from "../node-utilities/UndefinedLiteral" -import { updateAnnotationUsage } from "../node-utilities/AnnotationUsage" +import { updateAnnotationUsage, update1AnnotationUsage } from "../node-utilities/AnnotationUsage" import { updateAssignmentExpression } from "../node-utilities/AssignmentExpression" import { updateETSUndefinedType } from "../node-utilities/ETSUndefinedType" import { updateConditionalExpression } from "../node-utilities/ConditionalExpression" @@ -367,6 +367,12 @@ export const factory = { get updateAnnotationUsage() { return updateAnnotationUsage }, + get create1AnnotationUsage(): (...args: Parameters) => AnnotationUsage { + return AnnotationUsage.create1AnnotationUsage; + }, + get update1AnnotationUsage(): (...args: Parameters) => AnnotationUsage { + return update1AnnotationUsage; + }, get createAssignmentExpression() { return AssignmentExpression.create }, diff --git a/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts b/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts index e79cc04c3..82b28fec3 100644 --- a/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts +++ b/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts @@ -16,6 +16,7 @@ import { AnnotationUsage, Expression } from '../../generated'; import { isSameNativeObject } from '../peers/ArktsObject'; import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { AstNode } from '../peers/AstNode'; export function updateAnnotationUsage(original: AnnotationUsage, expr?: Expression): AnnotationUsage { if (isSameNativeObject(expr, original.expr)) { @@ -25,3 +26,12 @@ export function updateAnnotationUsage(original: AnnotationUsage, expr?: Expressi const update = updateThenAttach(AnnotationUsage.updateAnnotationUsage, attachModifiers); return update(original, expr); } + +export function update1AnnotationUsage(original: AnnotationUsage, expr: Expression | undefined, properties: readonly AstNode[]): AnnotationUsage { + if (isSameNativeObject(expr, original.expr) && isSameNativeObject(properties, original.properties)) { + return original; + } + + const update = updateThenAttach(AnnotationUsage.update1AnnotationUsage, attachModifiers); + return update(original, expr, properties); +} -- Gitee From 8eadfad30861c8ce20b024b0c5cd2dde43d3d34f Mon Sep 17 00:00:00 2001 From: y00896775 Date: Wed, 23 Apr 2025 16:31:03 +0800 Subject: [PATCH 074/123] supplement builderparam transformation for trailing lambda Signed-off-by: y00896775 Change-Id: Ia6b32119313a623bd57f858d842761436a87c498 --- .../property-translators/builderParam.ts | 10 ++++-- .../src/arkts-api/factory/nodeFactory.ts | 10 +++++- .../node-utilities/TemplateLiteral.ts | 35 +++++++++++++++++++ koala-wrapper/src/arkts-api/visitor.ts | 18 ++++++++++ .../src/generated/peers/TemplateLiteral.ts | 3 ++ 5 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TemplateLiteral.ts diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts index 5ae6fdf26..fbf600f06 100644 --- a/arkui-plugins/ui-plugins/property-translators/builderParam.ts +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -86,9 +86,13 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia mutableThis, arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName + arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName + ), + arkts.factory.createIdentifier('content'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ), this.property.value ?? arkts.factory.createUndefinedLiteral(), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index d46a22e90..a9bd53d70 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -72,7 +72,8 @@ import { ETSNewClassInstanceExpression, BooleanLiteral, ObjectExpression, - Property + Property, + TemplateLiteral } from "../../generated" import { Es2pandaModifierFlags @@ -131,6 +132,7 @@ import { updateNullLiteral } from "../node-utilities/NullLiteral" import { updateETSNewClassInstanceExpression } from "../node-utilities/ETSNewClassInstanceExpression" import { updateObjectExpression } from "../node-utilities/ObjectExpression" import { updateProperty } from "../node-utilities/Property" +import { updateTemplateLiteral } from "../node-utilities/TemplateLiteral" export const factory = { get createIdentifier() { @@ -460,6 +462,12 @@ export const factory = { get updateProperty(): (...args: Parameters) => Property { return updateProperty; }, + get createTemplateLiteral(): (...args: Parameters) => TemplateLiteral { + return TemplateLiteral.createTemplateLiteral; + }, + get updateTemplateLiteral(): (...args: Parameters) => TemplateLiteral { + return updateTemplateLiteral; + }, /** @deprecated */ createTypeParameter1_(name: Identifier, constraint?: TypeNode, defaultType?: TypeNode) { return TSTypeParameter.createTSTypeParameter(Identifier.create1Identifier(name.name), constraint, defaultType) diff --git a/koala-wrapper/src/arkts-api/node-utilities/TemplateLiteral.ts b/koala-wrapper/src/arkts-api/node-utilities/TemplateLiteral.ts new file mode 100644 index 000000000..840c0d120 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TemplateLiteral.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TemplateLiteral, TemplateElement, Expression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTemplateLiteral( + original: TemplateLiteral, + quasis: readonly TemplateElement[], + expressions: readonly Expression[], + multilineString: string +): TemplateLiteral { + if ( + isSameNativeObject(quasis, original.quasis) && + isSameNativeObject(expressions, original.expressions) + ) { + return original; + } + + const update = updateThenAttach(TemplateLiteral.updateTemplateLiteral, attachModifiers); + return update(original, quasis, expressions, multilineString); +} diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index 27fb2b733..76d531c12 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -42,6 +42,7 @@ import { isProperty, Expression, isETSNewClassInstanceExpression, + isTemplateLiteral, } from '../generated'; import { isEtsScript, @@ -152,6 +153,7 @@ export function visitEachChild(node: AstNode, visitor: Visitor): AstNode { script = visitStatement(script, visitor); script = visitOuterExpression(script, visitor); script = visitInnerExpression(script, visitor); + script = visitLiteral(script, visitor); // TODO return visitWithoutUpdate(script, visitor); } @@ -410,6 +412,22 @@ function visitDefinitionBody(node: AstNode, visitor: Visitor): AstNode { return node; } +function visitLiteral(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; + } + if (isTemplateLiteral(node)) { + updated = true; + return factory.updateTemplateLiteral( + node, + nodesVisitor(node.quasis, visitor), + nodesVisitor(node.expressions, visitor), + node.multilineString + ); + } + return node; +} + // TODO: apply this to all nodes that does not require updating function visitWithoutUpdate(node: T, visitor: Visitor): T { if (updated) { diff --git a/koala-wrapper/src/generated/peers/TemplateLiteral.ts b/koala-wrapper/src/generated/peers/TemplateLiteral.ts index f67bc25da..b51bb606f 100644 --- a/koala-wrapper/src/generated/peers/TemplateLiteral.ts +++ b/koala-wrapper/src/generated/peers/TemplateLiteral.ts @@ -49,6 +49,9 @@ export class TemplateLiteral extends Expression { get expressions(): readonly Expression[] { return unpackNodeArray(global.generatedEs2panda._TemplateLiteralExpressionsConst(global.context, this.peer)) } + get multilineString(): string { + return unpackString(global.generatedEs2panda._TemplateLiteralGetMultilineStringConst(global.context, this.peer)); + } } export function isTemplateLiteral(node: AstNode): node is TemplateLiteral { return node instanceof TemplateLiteral -- Gitee From 8cd6986ee73a13864b2efcd1be6900fe0b2176f2 Mon Sep 17 00:00:00 2001 From: Maxim Bolshov Date: Mon, 28 Apr 2025 21:20:13 +0300 Subject: [PATCH 075/123] Fix hardcoded enum Signed-off-by: Maxim Bolshov --- koala-wrapper/src/generated/Es2pandaEnums.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/koala-wrapper/src/generated/Es2pandaEnums.ts b/koala-wrapper/src/generated/Es2pandaEnums.ts index bde4ac8d9..1e5ee0d2c 100644 --- a/koala-wrapper/src/generated/Es2pandaEnums.ts +++ b/koala-wrapper/src/generated/Es2pandaEnums.ts @@ -17,13 +17,12 @@ export enum Es2pandaContextState { ES2PANDA_STATE_NEW = 0, ES2PANDA_STATE_PARSED = 1, - ES2PANDA_STATE_SCOPE_INITED = 2, - ES2PANDA_STATE_BOUND = 3, - ES2PANDA_STATE_CHECKED = 4, - ES2PANDA_STATE_LOWERED = 5, - ES2PANDA_STATE_ASM_GENERATED = 6, - ES2PANDA_STATE_BIN_GENERATED = 7, - ES2PANDA_STATE_ERROR = 8 + ES2PANDA_STATE_BOUND = 2, + ES2PANDA_STATE_CHECKED = 3, + ES2PANDA_STATE_LOWERED = 4, + ES2PANDA_STATE_ASM_GENERATED = 5, + ES2PANDA_STATE_BIN_GENERATED = 6, + ES2PANDA_STATE_ERROR = 7 } // export enum Es2pandaAstNodeType { // AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION = 0, -- Gitee From 0c7cbb7951530feb2c9b19a904f351dbbc5400e0 Mon Sep 17 00:00:00 2001 From: wangweiyuan Date: Sat, 19 Apr 2025 21:19:40 +0800 Subject: [PATCH 076/123] add ui-syntax-plugins (15/52) Signed-off-by: wangweiyuan --- arkui-plugins/build_ui_plugins.py | 3 + .../demo/localtest/build_config_template.json | 1 + arkui-plugins/tsconfig.build.json | 1 + arkui-plugins/tsconfig.json | 1 + arkui-plugins/ui-syntax-plugins/index.ts | 44 ++++ .../ui-syntax-plugins/processor/index.ts | 64 ++++++ .../rules/build-root-node.ts | 100 +++++++++ .../check-construct-private-parameter.ts | 90 ++++++++ .../rules/componentV2-mix-check.ts | 57 +++++ .../rules/custom-dialog-missing-controller.ts | 68 ++++++ .../rules/decorators-in-ui-component-only.ts | 102 +++++++++ .../rules/entry-localstorage-check.ts | 61 ++++++ .../rules/entry-struct-no-export.ts | 53 +++++ .../ui-syntax-plugins/rules/index.ts | 46 ++++ .../rules/local-builder-check.ts | 63 ++++++ .../rules/no-duplicate-decorators.ts | 104 +++++++++ .../rules/no-duplicate-state-manager.ts | 74 +++++++ .../rules/no-prop-link-objectlink-in-entry.ts | 75 +++++++ .../rules/no-same-as-built-in-attribute.ts | 47 ++++ .../ui-syntax-plugins/rules/ui-syntax-rule.ts | 43 ++++ .../parsed-ui-syntax-linter-transformer.ts | 25 +++ .../transformers/ui-syntax-linter-visitor.ts | 23 ++ .../ui-syntax-plugins/utils/index.ts | 200 ++++++++++++++++++ koala-wrapper/native/src/bridges.cc | 29 ++- koala-wrapper/src/Es2pandaNativeModule.ts | 24 ++- .../src/arkts-api/utilities/public.ts | 13 ++ 26 files changed, 1403 insertions(+), 8 deletions(-) create mode 100644 arkui-plugins/ui-syntax-plugins/index.ts create mode 100644 arkui-plugins/ui-syntax-plugins/processor/index.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/index.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/local-builder-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-duplicate-decorators.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts create mode 100644 arkui-plugins/ui-syntax-plugins/transformers/parsed-ui-syntax-linter-transformer.ts create mode 100644 arkui-plugins/ui-syntax-plugins/transformers/ui-syntax-linter-visitor.ts create mode 100644 arkui-plugins/ui-syntax-plugins/utils/index.ts diff --git a/arkui-plugins/build_ui_plugins.py b/arkui-plugins/build_ui_plugins.py index 3fe73510c..6ae5d669e 100755 --- a/arkui-plugins/build_ui_plugins.py +++ b/arkui-plugins/build_ui_plugins.py @@ -53,6 +53,9 @@ def copy_output(options): copy_files(os.path.join(options.source_path, 'lib'), os.path.join(options.output_path, 'lib')) + copy_files(os.path.join(options.source_path, '../compiler/components'), + os.path.join(options.output_path, 'lib/components')) + copy_files(os.path.join(options.source_path, 'package.json'), os.path.join(options.output_path, 'package.json'), True) diff --git a/arkui-plugins/test/demo/localtest/build_config_template.json b/arkui-plugins/test/demo/localtest/build_config_template.json index aa3de2c82..3855891d1 100755 --- a/arkui-plugins/test/demo/localtest/build_config_template.json +++ b/arkui-plugins/test/demo/localtest/build_config_template.json @@ -1,5 +1,6 @@ { "plugins": { + "ui-syntax-plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/ui-syntax-plugins/index", "ui_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/ui-plugins/index", "memo_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/memo-plugins/index" }, diff --git a/arkui-plugins/tsconfig.build.json b/arkui-plugins/tsconfig.build.json index 7efa8486d..02074ad93 100644 --- a/arkui-plugins/tsconfig.build.json +++ b/arkui-plugins/tsconfig.build.json @@ -20,6 +20,7 @@ "./common/**/*.ts", "./memo-plugins/**/*.ts", "./ui-plugins/**/*.ts", + "./ui-syntax-plugins/**/*.ts", "./interop-plugins/**/*.ts", ], "exclude": [ diff --git a/arkui-plugins/tsconfig.json b/arkui-plugins/tsconfig.json index eab872848..65bdd0988 100644 --- a/arkui-plugins/tsconfig.json +++ b/arkui-plugins/tsconfig.json @@ -21,6 +21,7 @@ "./common/**/*.ts", "./memo-plugins/**/*.ts", "./ui-plugins/**/*.ts", + "./ui-syntax-plugins/**/*.ts", "./interop-plugins/**/*.ts", "./path.ts", "./test/ut/**/*.ts", diff --git a/arkui-plugins/ui-syntax-plugins/index.ts b/arkui-plugins/ui-syntax-plugins/index.ts new file mode 100644 index 000000000..53232081e --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/index.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PluginContext, Plugins } from '../common/plugin-context'; +import { ParsedUISyntaxLinterTransformer } from './transformers/parsed-ui-syntax-linter-transformer'; +import { createUISyntaxRuleProcessor } from './processor'; +import rules from './rules'; + +export function uiSyntaxLinterTransform(): Plugins { + const processor = createUISyntaxRuleProcessor(rules); + return { + name: 'ui-syntax-plugin', + parsed(this: PluginContext): arkts.EtsScript | undefined { + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!contextPtr) { + return undefined; + } + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + const node = program.astNode; + if (node) { + const script = new ParsedUISyntaxLinterTransformer(processor).visitor( + node, + ) as arkts.EtsScript; + arkts.setAllParents(script); + this.setArkTSAst(script); + return script; + } + return undefined; + } + }; +} diff --git a/arkui-plugins/ui-syntax-plugins/processor/index.ts b/arkui-plugins/ui-syntax-plugins/processor/index.ts new file mode 100644 index 000000000..0a447759e --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/processor/index.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from '../rules/ui-syntax-rule'; +import { getContainerComponents } from '../utils'; + +export type UISyntaxRuleProcessor = { + parsed(node: arkts.AstNode): void; +}; + +export function createUISyntaxRuleProcessor( + rules: UISyntaxRule[], +): UISyntaxRuleProcessor { + const containerComponents = getContainerComponents('../../components/'); + const context: UISyntaxRuleContext = { + report(options) { + const position = arkts.getStartPosition(options.node); + let message: string; + if (!options.data) { + message = options.message; + } else { + message = Object.entries(options.data).reduce( + (message, [placehoderName, placehoderValue]) => { + return message.replace(`{{${placehoderName}}}`, placehoderValue); + }, + options.message, + ); + } + // todo + if (options.fix) { + const suggestion = options.fix(options.node); + console.log(`error: ${message}`); + console.log(`range: (${suggestion.range[0].index()}, ${suggestion.range[0].line()}) - (${suggestion.range[1].index()}, ${suggestion.range[1].line()})`, + `code: ${suggestion.code}`); + } else { + console.log(`syntax-error: ${message} (${position.index()},${position.line()})`); + } + }, + containerComponents: containerComponents, + }; + + const instances = rules.map((rule) => rule.setup(context)); + + return { + parsed(node): void { + for (const instance of instances) { + instance.parsed?.(node); + } + }, + }; +} diff --git a/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts b/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts new file mode 100644 index 000000000..c3678f1fe --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getIdentifierName, getAnnotationUsage, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const BUILD_NAME: string = 'build'; +const BUILD_ROOT_NUM: number = 1; +const STATEMENT_LENGTH: number = 1; + +function isBuildOneRoot(statements: readonly arkts.Statement[], buildNode: arkts.Identifier, + context: UISyntaxRuleContext): void { + if (statements.length > STATEMENT_LENGTH && buildNode) { + context.report({ + node: buildNode, + message: rule.messages.invalidBuildRootCount, + }); + } +} + +function checkBuildRootNode(node: arkts.AstNode, context: UISyntaxRuleContext): void { + const loadedContainerComponents = context.containerComponents; + if (!arkts.isStructDeclaration(node)) { + return; + } + const entryDecoratorUsage = getAnnotationUsage(node, PresetDecorators.ENTRY); + node.definition.body.forEach(member => { + // Determine the number of root node + if (!arkts.isMethodDefinition(member) || getIdentifierName(member.name) !== BUILD_NAME) { + return; + } + const blockStatement = member.scriptFunction.body; + if (!blockStatement || !arkts.isBlockStatement(blockStatement)) { + return; + } + const buildNode = member.scriptFunction.id; + const statements = blockStatement.statements; + // rule1: The 'build' method cannot have more than one root node. + if (buildNode) { + isBuildOneRoot(statements, buildNode, context); + } + if (statements.length !== BUILD_ROOT_NUM) { + return; + } + // Determine whether it is a container component + const expressionStatement = statements[0]; + if (!arkts.isExpressionStatement(expressionStatement)) { + return; + } + const callExpression = expressionStatement.expression; + if (!arkts.isCallExpression(callExpression)) { + return; + } + const componentName = callExpression.expression.dumpSrc(); + let isContainer: boolean = false; + loadedContainerComponents?.forEach(container => { + if (componentName.includes(container)) { + isContainer = true; + } + }); + // rule2: If the component is decorated by '@Entry', + // its 'build' function can have only one root node, which must be a container component. + if (entryDecoratorUsage && !isContainer && buildNode) { + context.report({ + node: buildNode, + message: rule.messages.invalidBuildRoot, + }); + } + }); +} + +const rule: UISyntaxRule = { + name: 'build-root-node', + messages: { + invalidBuildRootCount: `The 'build' method cannot have more than one root node.`, + invalidBuildRoot: `If the component is decorated by '@Entry', its 'build' function can have only one root node, which must be a container component.` + }, + setup(context) { + return { + parsed: (node): void => { + checkBuildRootNode(node, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts b/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts new file mode 100644 index 000000000..21325d687 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getClassPropertyName, isPrivateClassProperty } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +let privateMap: Map = new Map(); + +function addProperty(item: arkts.AstNode, structName: string): void { + if (!arkts.isClassProperty(item) || !isPrivateClassProperty(item)) { + return; + } + // Check if structName already exists in privateMap + if (privateMap.has(structName)) { + // If it exists, retrieve the current string[] and append the new content + privateMap.get(structName)?.push(getClassPropertyName(item)); + } else { + // If it doesn't exist, create a new string[] and add the content + privateMap.set(structName, [getClassPropertyName(item)]); + } +} + +function checkPrivateVariables(node: arkts.AstNode, context: UISyntaxRuleContext): void { + // Check if the current node is the root node + if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + node.getChildren().forEach((member) => { + if (!arkts.isStructDeclaration(member)) { + return; + } + const structName: string = member.definition.ident?.name ?? ''; + member.definition?.body?.forEach((item) => { + addProperty(item, structName); + }); + }); + } + if (!arkts.isCallExpression(node)) { + return; + } + const componentName = node.expression.dumpSrc(); + // If the initialization is for a component with private properties + if (!privateMap.has(componentName)) { + return; + } + node.arguments?.forEach((member) => { + member.getChildren().forEach((property) => { + if (!arkts.isProperty(property)) { + return; + } + const propertyName: string = property.key?.dumpSrc() ?? ''; + if (privateMap.get(componentName)!.includes(propertyName)) { + context.report({ + node: property, + message: rule.messages.cannotInitializePrivateVariables, + data: { + propertyName: propertyName, + }, + }); + } + }); + }); +} + +const rule: UISyntaxRule = { + name: 'check-construct-private-parameter', + messages: { + cannotInitializePrivateVariables: `Property '{{propertyName}}' is private and can not be initialized through the component constructor.`, + }, + setup(context) { + return { + parsed: (node): void => { + checkPrivateVariables(node, context); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts new file mode 100644 index 000000000..082d768d1 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, PresetDecorators } from '../utils'; +import { UISyntaxRule } from './ui-syntax-rule'; + +const rule: UISyntaxRule = { + name: 'componentV2-mix-check', + messages: { + conflictWithComponentV2: `The struct '{{structName}}' can not be decorated with '@ComponentV2' and '@Component', '@Reusable', '@CustomDialog' at the same time.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + const structName = node.definition.ident?.name ?? ''; + const structNameNode = node.definition.ident; + if (!structNameNode) { + return; + } + // Check if the struct has the '@ComponentV2' annotation + const hasComponentV2 = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); + if (!hasComponentV2) { + return; + } + // Check for the presence of conflicting decorators: '@Component', '@Reusable', '@CustomDialog' + const hasComponent = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); + const hasReusable = getAnnotationUsage(node, PresetDecorators.REUSABLE_V1); + const hasCustomDialog = getAnnotationUsage(node, PresetDecorators.CUSTOM_DIALOG); + if (hasComponent || hasReusable || hasCustomDialog) { + context.report({ + node: structNameNode, + message: rule.messages.conflictWithComponentV2, + data: { structName }, + }); + } + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts b/arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts new file mode 100644 index 000000000..f7721812c --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getClassPropertyType, PresetDecorators, getAnnotationUsage } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const CUSTOM_DIALOG_CONTROLLER: string = 'CustomDialogController'; + +function missingController( + node: arkts.StructDeclaration, + context: UISyntaxRuleContext +): void { + // Check for the @CustomDialog decorator + const hasCustomDialogDecorator = getAnnotationUsage(node, PresetDecorators.CUSTOM_DIALOG); + const structName = node.definition.ident; + if (!structName) { + return; + } + // Check if there is an attribute of type CustomDialogController in the class + let hasControllerProperty = false; + node.definition.body.forEach((property) => { + if (arkts.isClassProperty(property)) { + const propertyType = getClassPropertyType(property); + if (propertyType === CUSTOM_DIALOG_CONTROLLER) { + hasControllerProperty = true; + } + } + }); + if (!hasControllerProperty && hasCustomDialogDecorator) { + context.report({ + node: structName, + message: rule.messages.missingController, + }); + } +} + +const rule: UISyntaxRule = { + name: 'custom-dialog-missing-controller', + messages: { + missingController: `The @CustomDialog decorated custom component must contain a property of the CustomDialogController type.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + missingController(node, context); + }, + }; + }, +}; + +export default rule; + diff --git a/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts b/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts new file mode 100644 index 000000000..b01e0d40a --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +import { PresetDecorators } from '../utils/index'; + +// Helper function to find the '@Component' decorator in a ClassDeclaration and report errors. +function findComponentDecorator(context: UISyntaxRuleContext, node: arkts.ClassDeclaration): void { + const componentDecorator = node.definition?.annotations?.find( + (annotation) => + annotation.expr && + arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.COMPONENT_V1 + ); + if (componentDecorator) { + reportDecoratorError(context, componentDecorator, rule.messages.invalidComponentDecorator); + } +} + +// Helper function to find the '@Prop' decorator in a MethodDefinition or ClassProperty. +const findPropDecorator = (node: arkts.MethodDefinition | arkts.ClassProperty): arkts.AnnotationUsage | undefined => { + const annotations = 'scriptFunction' in node ? node.scriptFunction.annotations : node.annotations; + return annotations?.find( + (annotation) => + annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.PROP + ); +}; + +// Rule 2: Check for '@Prop' on MethodDefinition +function checkPropOnMethod(context: UISyntaxRuleContext, node: arkts.MethodDefinition): void { + const propDecorator = findPropDecorator(node); + if (propDecorator) { + reportDecoratorError(context, propDecorator, rule.messages.propOnMethod); + } +}; + +// Rule 3: Check for '@Prop' on ClassProperty within a ClassDeclaration +function checkPropOnClassProperty(context: UISyntaxRuleContext, node: arkts.ClassProperty, currentNode: arkts.AstNode) + : void { + const propDecorator = findPropDecorator(node); + while (arkts.nodeType(currentNode) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + currentNode = currentNode.parent; + if (propDecorator && arkts.isClassDeclaration(currentNode)) { + reportDecoratorError(context, propDecorator, rule.messages.propOnMethod); + } + } +}; + +function reportDecoratorError(context: UISyntaxRuleContext, Decorator: arkts.AnnotationUsage, message: string +): void { + context.report({ + node: Decorator, + message: message, + fix: () => { + const startPosition = arkts.getStartPosition(Decorator); + const endPosition = arkts.getEndPosition(Decorator); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +const rule: UISyntaxRule = { + name: 'no-prop-on-method', + messages: { + invalidComponentDecorator: `'@Component' can decorate only custom components.`, + propOnMethod: `'@Prop' can decorate only member variables of custom components.`, + }, + setup(context) { + return { + parsed: (node: arkts.AstNode): void => { + if (arkts.isClassDeclaration(node)) { + findComponentDecorator(context, node); + } + if (arkts.isMethodDefinition(node)) { + checkPropOnMethod(context, node); + } + let currentNode = node; + if (arkts.isClassProperty(node)) { + checkPropOnClassProperty(context, node, currentNode); + } + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts b/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts new file mode 100644 index 000000000..aa82f3104 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function checkLocalStorageLink(node: arkts.StructDeclaration, context: UISyntaxRuleContext): void { + // Check if @Entry decorator exists with parameter + const entryDecorator = getAnnotationUsage(node, PresetDecorators.ENTRY); + const isStorageUsed = entryDecorator && node.definition?.annotations[0].properties[0]; + // Check if @LocalStorageLink exists + let localStorageLinkUsed = false; + node.definition.body.forEach(body => { + if (!arkts.isClassProperty(body)) { + return; + } + const propertyDecorators = getClassPropertyAnnotationNames(body); + localStorageLinkUsed = propertyDecorators.some( + decorator => decorator === PresetDecorators.LOCAL_STORAGE_LINK); + }); + + // If @LocalStorageLink is used but @Entry(storage) is missing, report error + if (entryDecorator && localStorageLinkUsed && !isStorageUsed) { + context.report({ + node: entryDecorator, + message: rule.messages.invalidUsage + }); + } +} + +const rule: UISyntaxRule = { + name: 'entry-localstorage-check', + messages: { + invalidUsage: `@LocalStorageLink requires @Entry(storage) on the struct.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + checkLocalStorageLink(node, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts b/arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts new file mode 100644 index 000000000..7017ab54f --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, PresetDecorators } from '../utils'; +import { UISyntaxRule } from './ui-syntax-rule'; + +const rule: UISyntaxRule = { + name: 'entry-struct-no-export', + messages: { + noExportWithEntry: `It's not a recommended way to export struct with @Entry decorator, which may cause ACE Engine error in component preview mode.`, + }, + setup(context) { + return { + parsed: (node): void => { + // Check if the current node is a schema declaration + if (!arkts.isStructDeclaration(node)) { + return; + } + // Get the usage of the @Entry decorator + const entryDecoratorUsage = getAnnotationUsage( + node, + PresetDecorators.ENTRY, + ); + + //Determines whether the struct is exported + const isExported = node.dumpSrc().includes('export struct'); + + // If a @Entry decorator is present and the struct is exported + if (entryDecoratorUsage && isExported) { + context.report({ + node: entryDecoratorUsage, + message: this.messages.noExportWithEntry, + }); + } + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/index.ts b/arkui-plugins/ui-syntax-plugins/rules/index.ts new file mode 100644 index 000000000..391d52435 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/index.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import { UISyntaxRule } from './ui-syntax-rule'; +import BuildRootNode from './build-root-node'; +import CheckConstructPrivateParameter from './check-construct-private-parameter'; +import ComponentV2MixCheck from './componentV2-mix-check'; +import CustomDialogMissingController from './custom-dialog-missing-controller'; +import DecoratorsInUIComponentOnly from './decorators-in-ui-component-only'; +import EntryLoacalStorageCheck from './entry-localstorage-check'; +import EntryStructNoExport from './entry-struct-no-export'; +import LocalBuilderCheck from './local-builder-check'; +import NoDuplicateDecorators from './no-duplicate-decorators'; +import NoDuplicateStateManager from './no-duplicate-state-manager'; +import NoPropLinkObjectlinkInEntry from './no-prop-link-objectlink-in-entry'; +import NoSameAsBuiltInAttribute from './no-same-as-built-in-attribute'; + +const rules: UISyntaxRule[] = [ + BuildRootNode, + CheckConstructPrivateParameter, + ComponentV2MixCheck, + CustomDialogMissingController, + DecoratorsInUIComponentOnly, + EntryLoacalStorageCheck, + EntryStructNoExport, + LocalBuilderCheck, + NoDuplicateDecorators, + NoDuplicateStateManager, + NoPropLinkObjectlinkInEntry, + NoSameAsBuiltInAttribute, +]; + +export default rules; diff --git a/arkui-plugins/ui-syntax-plugins/rules/local-builder-check.ts b/arkui-plugins/ui-syntax-plugins/rules/local-builder-check.ts new file mode 100644 index 000000000..cbfeef0c3 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/local-builder-check.ts @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function checkLocalBuilder(node: arkts.ClassDeclaration, context: UISyntaxRuleContext): void { + node.definition?.body.forEach(body => { + if (!arkts.isMethodDefinition(body)) { + return; + } + const localBuilder = body.scriptFunction?.annotations?.find( + annotation => annotation.expr && + annotation.expr.dumpSrc() === PresetDecorators.LOCAL_BUILDER); + if (!localBuilder) { + return; + } + context.report({ + node: localBuilder, + message: rule.messages.invalidUsage, + fix: (localBuilder) => { + const startPosition = arkts.getStartPosition(localBuilder); + const endPosition = arkts.getEndPosition(localBuilder); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); + }); +} + +const rule: UISyntaxRule = { + name: 'local-builder-check', + messages: { + invalidUsage: `The '@LocalBuilder' decorator can only be used in 'struct'.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isClassDeclaration(node)) { + return; + } + checkLocalBuilder(node, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-decorators.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-decorators.ts new file mode 100644 index 000000000..ff42b2180 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-decorators.ts @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationName, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +// Decorators that cannot be repeated +const validDecorators = [ + PresetDecorators.ENTRY, + PresetDecorators.COMPONENT_V1, + PresetDecorators.COMPONENT_V2, + PresetDecorators.REUSABLE_V1, + PresetDecorators.PREVIEW, + PresetDecorators.REUSABLE_V2, + PresetDecorators.CUSTOM_DIALOG, +]; + +function checkForDuplicateDecorators(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { + // Initialize a map to record decorators and their occurrences + const decoratorCounts: Map = new Map(); + if (!node.definition || !node.definition.annotations) { + return; + } + // Record all decorators and their counts + node.definition.annotations.forEach((annotation) => { + const decoratorName = getAnnotationName(annotation); + if (!validDecorators.includes(decoratorName)) { + return; + } + + if (decoratorCounts.has(decoratorName)) { + const decoratorInfo = decoratorCounts.get(decoratorName)!; + decoratorInfo.count += 1; + decoratorInfo.annotations.push(annotation); + } else { + decoratorCounts.set(decoratorName, { count: 1, annotations: [annotation] }); + } + }); + + // Process decorators with more than one occurrence + decoratorCounts.forEach(({ count, annotations }, decoratorName) => { + if (count <= 1) { + return; + } + // Report errors for all occurrences except the last one + for (let i = 0; i < annotations.length - 1; i++) { + const prevAnnotation = annotations[i]; + reportDuplicateDecorator(context, prevAnnotation); + } + // For the last occurrence, report an error but do not provide a fix + const lastAnnotation = annotations[annotations.length - 1]; + context.report({ + node: lastAnnotation, + message: rule.messages.duplicateDecorator, + }); + }); +} + +function reportDuplicateDecorator(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage): void { + context.report({ + node: annotation, + message: rule.messages.duplicateDecorator, + fix: () => { + const startPosition = arkts.getStartPosition(annotation); + const endPosition = arkts.getEndPosition(annotation); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +const rule: UISyntaxRule = { + name: 'no-duplicate-decorators', + messages: { + duplicateDecorator: `Duplicate decorators for struct are not allowed.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + checkForDuplicateDecorators(context, node); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts new file mode 100644 index 000000000..df1468fd5 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getClassPropertyAnnotationNames } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +export const stateManagementDecorator = { + STATE: 'State', + PROP: 'Prop', + LINK: 'Link', + PROVIDE: 'Provide', + CONSUME: 'Consume' +}; + +const CLASS_PROPERTY_ANNOTATION_ONE: number = 1; +function duplicateState( + node: arkts.StructDeclaration, + context: UISyntaxRuleContext +): void { + node.definition.body.forEach(body => { + if (arkts.isClassProperty(body)) { + // Get the list of decorators + const propertyDecorators = getClassPropertyAnnotationNames(body); + // Filter the decorators to get those related to state management + const stateDecorators = propertyDecorators.filter(decorator => + Object.values(stateManagementDecorator).includes(decorator) + ); + const propertyNameNode = body.key; + const attributeName = body.key?.dumpSrc(); + if (!propertyNameNode || !attributeName) { + return; + } + if (stateDecorators.length > CLASS_PROPERTY_ANNOTATION_ONE) { + context.report({ + node: propertyNameNode, + message: rule.messages.duplicateState, + data: { attributeName }, + }); + } + } + }); +} + +const rule: UISyntaxRule = { + name: 'no-duplicate-state-manager', + messages: { + duplicateState: `This attribute '{{attributeName}}' cannot have mutilate state management decorators. `, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + duplicateState(node, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts new file mode 100644 index 000000000..8815feff4 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function checkNoPropLinkOrObjectLinkInEntry(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { + // Check if the struct has the @Entry decorator + const isEntryComponent = !!getAnnotationUsage(node, PresetDecorators.ENTRY); + if (!isEntryComponent) { + return; + } + node.definition.body.forEach(body => { + if (!arkts.isClassProperty(body)) { + return; + } + const invalidDecorators = [PresetDecorators.PROP, PresetDecorators.LINK, PresetDecorators.OBJECT_LINK]; + // Check if any invalid decorators are applied to the class property + body.annotations?.forEach(annotation => { + reportInvalidDecorator(context, annotation, invalidDecorators); + }); + }); +} + +function reportInvalidDecorator(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage, + invalidDecorators: string[],): void { + if (annotation.expr && invalidDecorators.includes(annotation.expr.dumpSrc())) { + const decorator = annotation.expr.dumpSrc(); + context.report({ + node: annotation, + message: rule.messages.invalidUsage, + data: { decorator }, + fix: (annotation) => { + const startPosition = arkts.getStartPosition(annotation); + const endPosition = arkts.getEndPosition(annotation); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); + } +} + +const rule: UISyntaxRule = { + name: 'no-prop-link-objectlink-in-entry', + messages: { + invalidUsage: `@{{decorator}} decorator cannot be used for '@Entry' decorated components.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + checkNoPropLinkOrObjectLinkInEntry(context, node); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts b/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts new file mode 100644 index 000000000..e61af0b56 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule } from './ui-syntax-rule'; + +const rule: UISyntaxRule = { + name: 'no-same-as-built-in-attribute', + messages: { + duplicateName: `The struct name '{{structName}}' should not have the same name as a built-in attribute.`, + }, + setup(context) { + const builtInAttributes = ['fontColor', 'width', 'height', 'size', 'border', 'backgroundColor', 'margin', + 'padding']; + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + const structName = node.definition.ident?.name ?? ' '; + const structIdent = node.definition.ident; + // If the struct name matches any built-in attribute, report an error + if (builtInAttributes.includes(structName) && structIdent) { + context.report({ + node: structIdent, + message: rule.messages.duplicateName, + data: { structName } + }); + } + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts b/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts new file mode 100644 index 000000000..c71a7c298 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +export type FixSuggestion = { + range: [start: arkts.SourcePosition, end: arkts.SourcePosition]; + code: string; +}; + +export type ReportOptions = { + node: arkts.AstNode; + message: string; + data?: Record; + fix?: (node: arkts.AstNode) => FixSuggestion; +}; + +export type UISyntaxRuleContext = { + report(options: ReportOptions): void; + containerComponents?: Set | undefined; +}; + +export type UISyntaxRuleHandler = (node: arkts.AstNode) => void; + +export type UISyntaxRule = { + name: string; + messages: Record; + setup(context: UISyntaxRuleContext): { + parsed?: UISyntaxRuleHandler; + }; +}; diff --git a/arkui-plugins/ui-syntax-plugins/transformers/parsed-ui-syntax-linter-transformer.ts b/arkui-plugins/ui-syntax-plugins/transformers/parsed-ui-syntax-linter-transformer.ts new file mode 100644 index 000000000..d8c642ed2 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/transformers/parsed-ui-syntax-linter-transformer.ts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxLinterVisitor } from './ui-syntax-linter-visitor'; + +export class ParsedUISyntaxLinterTransformer extends UISyntaxLinterVisitor { + visitor(node: arkts.AstNode): arkts.AstNode { + this.processor.parsed(node); + node = this.visitEachChild(node); + return node; + } +} diff --git a/arkui-plugins/ui-syntax-plugins/transformers/ui-syntax-linter-visitor.ts b/arkui-plugins/ui-syntax-plugins/transformers/ui-syntax-linter-visitor.ts new file mode 100644 index 000000000..356304f88 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/transformers/ui-syntax-linter-visitor.ts @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbstractVisitor } from '../../common/abstract-visitor'; +import { UISyntaxRuleProcessor } from '../processor'; + +export abstract class UISyntaxLinterVisitor extends AbstractVisitor { + constructor(protected processor: UISyntaxRuleProcessor) { + super(); + } +} diff --git a/arkui-plugins/ui-syntax-plugins/utils/index.ts b/arkui-plugins/ui-syntax-plugins/utils/index.ts new file mode 100644 index 000000000..87ba336a7 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/utils/index.ts @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import * as fs from 'fs'; +import * as path from 'path'; + +export const PresetDecorators = { + BUILDER_PARAM: 'BuilderParam', + COMPONENT_V1: 'Component', + COMPONENT_V2: 'ComponentV2', + COMPUTED: 'Computed', + CONSUME: 'Consume', + CONSUMER: 'Consumer', + CUSTOM_DIALOG: 'CustomDialog', + ENTRY: 'Entry', + EVENT: 'Event', + PREVIEW: 'Preview', + STATE: 'State', + PARAM: 'Param', + PROP: 'Prop', + PROVIDE: 'Provide', + PROVIDER: 'Provider', + LINK: 'Link', + LOCAL: 'Local', + OBJECT_LINK: 'ObjectLink', + STORAGE_PROP: 'StorageProp', + STORAGE_LINK: 'StorageLink', + LOCAL_STORAGE_PROP: 'LocalStorageProp', + LOCAL_STORAGE_LINK: 'LocalStorageLink', + REQUIRE: 'Require', + REUSABLE_V1: 'Reusable', + REUSABLE_V2: 'ReusableV2', + OBSERVED_V1: 'Observed', + OBSERVED_V2: 'ObservedV2', + TYPE: 'Type', + WATCH: 'Watch', + BUILDER: 'Builder', + TRACK: 'Track', + TRACE: 'Trace', + ONCE: 'Once', + MONITOR: 'Monitor', + LOCAL_BUILDER: 'LocalBuilder', +}; + +const PUBLIC_PROPERTY_MODIFIERS: Number = 4; +const PROTECTED_PROPERTY_MODIFIERS: Number = 8; +const PRIVATE_PROPERTY_MODIFIERS: Number = 16; +export function getIdentifierName(node: arkts.AstNode): string { + if (!arkts.isIdentifier(node)) { + throw new Error(`Except a Identifier type!`); + } + return node.name; +} + +export function getAnnotationName(annotation: arkts.AnnotationUsage): string { + if (!annotation.expr) { + throw new Error(`The expr property does not exist!`); + } + return getIdentifierName(annotation.expr); +} + +export function getAnnotationUsage( + declaration: arkts.StructDeclaration, + annotationName: string, +): arkts.AnnotationUsage | undefined { + return declaration.definition.annotations.find( + (annotation) => + annotation.expr && + arkts.isIdentifier(annotation.expr) && + annotation.expr.name === annotationName, + ); +} + +export function getClassAnnotationUsage( + declaration: arkts.ClassDeclaration, + annotationName: string, +): arkts.AnnotationUsage | undefined { + if (!declaration.definition || !declaration.definition.annotations) { + return undefined; + } + return declaration.definition.annotations.find( + (annotation) => + annotation.expr && + ((arkts.isIdentifier(annotation.expr) && annotation.expr.name === annotationName) || + (arkts.isCallExpression(annotation.expr) && + arkts.isIdentifier(annotation.expr) && + annotation.expr.name === annotationName)) + ); +} + + + +export function getClassPropertyName(property: arkts.ClassProperty): string { + return getIdentifierName(property.key); +} + +export function getClassPropertyType(property: arkts.ClassProperty): string { + return property.typeAnnotation.dumpSrc(); +} + +export function getClassPropertyAnnotationNames( + property: arkts.ClassProperty, +): string[] { + return property.annotations.map((annotation) => + getAnnotationName(annotation), + ); +} + +export function isPublicClassProperty(property: arkts.ClassProperty): boolean { + // todo 使用接口实现 + return property.modifiers === PUBLIC_PROPERTY_MODIFIERS; +} + +export function isPrivateClassProperty(property: arkts.ClassProperty): boolean { + // todo 使用接口实现 + return property.modifiers === PRIVATE_PROPERTY_MODIFIERS; +} + +export function isProtectedlassProperty(property: arkts.ClassProperty): boolean { + // todo 使用接口实现 + return property.modifiers === PROTECTED_PROPERTY_MODIFIERS; +} + +export class MultiMap { + private readonly map: Map; + constructor() { + this.map = new Map(); + } + /** + * Add key-value pairs to MultiMap + * @param key key + * @param value value + */ + add(key: K, value: V): void { + if (!this.map.has(key)) { + this.map.set(key, []); + } + this.map.get(key)!.push(value); + } + + /** + * Gets all the values of the specified key + * @param key key + * @returns An array of values, which returns an empty array if the key does not exist + */ + get(key: K): V[] { + return this.map.get(key) || []; + } + + /** + * Check if the specified key exists in the MultiMap + * @param key key + * @returns Whether it exists + */ + has(key: K): boolean { + return this.map.has(key); + } +} + +interface ComponentJson { + name: string; + atomic?: boolean; + attrs: string[]; +} + +export function getContainerComponents(dirPath: string): Set { + const resultSet = new Set(); + const absolutePath = path.resolve(__dirname, dirPath); + + if (!fs.existsSync(absolutePath)) { + throw new Error(`Directory does not exist: ${absolutePath}`); + } + // Read all files in the directory + const files = fs.readdirSync(absolutePath); + + files.forEach(file => { + if (path.extname(file) === '.json') { + const filePath = path.join(absolutePath, file); + const fileContent = fs.readFileSync(filePath, 'utf-8'); + const componentJson: ComponentJson = JSON.parse(fileContent); + if ((!componentJson.atomic || componentJson.atomic !== true) && (componentJson.name)) { + resultSet.add(componentJson.name); + } + } + }); + return resultSet; +} \ No newline at end of file diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index 5f7b6cbfd..f73b489b0 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -397,7 +397,8 @@ KNativePointer impl_AstNodeRangeConst(KNativePointer context, KNativePointer nod } KOALA_INTEROP_2(AstNodeRangeConst, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_SourceRangeStart(KNativePointer context, KNativePointer range) { +KNativePointer impl_SourceRangeStart(KNativePointer context, KNativePointer range) +{ const auto _context = reinterpret_cast(context); const auto _range = reinterpret_cast(range); auto result = GetImpl()->SourceRangeStart(_context, _range); @@ -405,10 +406,34 @@ KNativePointer impl_SourceRangeStart(KNativePointer context, KNativePointer rang } KOALA_INTEROP_2(SourceRangeStart, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_SourceRangeEnd(KNativePointer context, KNativePointer range) { +KNativePointer impl_SourceRangeEnd(KNativePointer context, KNativePointer range) +{ const auto _context = reinterpret_cast(context); const auto _range = reinterpret_cast(range); auto result = GetImpl()->SourceRangeEnd(_context, _range); return result; } KOALA_INTEROP_2(SourceRangeEnd, KNativePointer, KNativePointer, KNativePointer) +bool impl_ClassPropertyIsDefaultAccessModifierConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + return GetImpl()->ClassPropertyIsDefaultAccessModifierConst(_context, _receiver); +} +KOALA_INTEROP_2(ClassPropertyIsDefaultAccessModifierConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeStartConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + return const_cast(GetImpl()->AstNodeStartConst(_context, _receiver)); +} +KOALA_INTEROP_2(AstNodeStartConst, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_AstNodeEndConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + return const_cast(GetImpl()->AstNodeEndConst(_context, _receiver)); +} +KOALA_INTEROP_2(AstNodeEndConst, KNativePointer, KNativePointer, KNativePointer); diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 3a1805b6a..4ddaaee45 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -795,12 +795,24 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } - _ImportSpecifierIsRemovableConst(context: KNativePointer, instance: KNativePointer): KBoolean { - throw new Error('Not implemented'); - } - - _ImportSpecifierSetRemovable(context: KNativePointer, instance: KNativePointer): void { - throw new Error('Not implemented'); + _ImportSpecifierIsRemovableConst(context: KNativePointer, instance: KNativePointer): KBoolean { + throw new Error('Not implemented'); + } + + _ImportSpecifierSetRemovable(context: KNativePointer, instance: KNativePointer): void { + throw new Error('Not implemented'); + } + + _ClassPropertyIsDefaultAccessModifierConst(context: KNativePointer, receiver: KNativePointer): boolean { + throw new Error('Not implemented'); + } + + _AstNodeStartConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error('Not implemented'); + } + + _AstNodeEndConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error('Not implemented'); } _AstNodeRangeConst(context: KNativePointer, node: KNativePointer): KNativePointer { diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index eac5cfad8..6b1bf7d57 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -23,6 +23,7 @@ import type { AstNode } from "../peers/AstNode" import { ClassDefinition, ClassProperty, ETSImportDeclaration, ImportSpecifier, isClassDefinition, isScriptFunction, type AnnotationUsage } from "../../generated" import { Program } from "../peers/Program" import { clearNodeCache } from "../class-by-peer" +import { SourcePosition } from "../peers/SourcePosition" export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { @@ -168,4 +169,16 @@ export function setAllParents(ast: AstNode) { export function generateTsDeclarationsFromContext(outputDeclEts: string, outputEts: string, exportAll: boolean): KInt { return global.es2panda._GenerateTsDeclarationsFromContext(global.context, passString(outputDeclEts), passString(outputEts), exportAll) +} + +export function isDefaultAccessModifierClassProperty(property: ClassProperty): boolean { + return global.es2panda._ClassPropertyIsDefaultAccessModifierConst(global.context, property.peer); +} + +export function getStartPosition(node: AstNode): SourcePosition { + return new SourcePosition(global.es2panda._AstNodeStartConst(global.context, node.peer)); +} + +export function getEndPosition(node: AstNode): SourcePosition { + return new SourcePosition(global.es2panda._AstNodeEndConst(global.context, node.peer)); } \ No newline at end of file -- Gitee From 02444adb6a3566e7802f8734859aaacaf37b905a Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Sun, 27 Apr 2025 11:17:15 +0800 Subject: [PATCH 077/123] add basic testcases for @Track, @Observed, @StorageLink, @StorageProp, @Watch, @Reusable, @ObjectLink Signed-off-by: fengyuxin Change-Id: I5da53cd8497c767050190dc6fd9fb81714e66685 --- .../objectlink/objectlink-basic.ets | 13 + .../objectlink/objectlink-observed.ets | 54 ++ .../observed-track/observed-only.ets | 13 + .../observed-track-class-property.ets | 19 + .../observed-track-complex-type.ets | 76 ++ .../observed-track/observed-track-extends.ets | 23 + .../observed-track-implements.ets | 20 + .../observed-track/observed-track.ets | 13 + .../decorators/observed-track/track-only.ets | 12 + .../decorators/reusable/reusable-basic.ets | 19 + .../decorators/reusable/reusable-complex.ets | 53 ++ .../storagelink/storagelink-appstorage.ets | 35 + .../storagelink/storagelink-complex-type.ets | 28 + .../storagelink-primitive-type.ets | 12 + .../storageprop/storageprop-appstorage.ets | 34 + .../storageprop/storageprop-complex-type.ets | 28 + .../storageprop-primitive-type.ets | 12 + .../mock/decorators/watch/watch-basic.ets | 41 + .../observed-track/observed-only.test.ts | 157 +++ .../observed-track-class-property.test.ts | 206 ++++ .../observed-track-complex-type.test.ts | 898 ++++++++++++++++++ .../observed-track-extends.test.ts | 204 ++++ .../observed-track-implements.test.ts | 187 ++++ .../observed-track/observed-track.test.ts | 142 +++ .../observed-track/track-only.test.ts | 142 +++ .../reusable/reusable-basic.test.ts | 159 ++++ .../reusable/reusable-complex.test.ts | 209 ++++ .../storagelink-appstorage.test.ts | 164 ++++ .../storagelink-complex-type.test.ts | 313 ++++++ .../storagelink-primitive-type.test.ts | 153 +++ .../storageprop-appstorage.test.ts | 165 ++++ .../storageprop-complex-type.test.ts | 312 ++++++ .../storageprop-primitive-type.test.ts | 152 +++ .../decorators/watch/watch-basic.test.ts | 306 ++++++ 34 files changed, 4374 insertions(+) create mode 100644 arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-basic.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-observed.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-only.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-class-property.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-complex-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-extends.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-implements.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/track-only.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/reusable/reusable-complex.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-appstorage.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-complex-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-primitive-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-appstorage.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-complex-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-primitive-type.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/watch/watch-basic.ets create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts diff --git a/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-basic.ets b/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-basic.ets new file mode 100644 index 000000000..273a00f46 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-basic.ets @@ -0,0 +1,13 @@ +import { Component } from "@ohos.arkui.component" +import { Observed, ObjectLink } from "@ohos.arkui.stateManagement" + +@Observed +class A {} + +@Component +struct MyStateSample { + + @ObjectLink objectlinkvar: A; + + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-observed.ets b/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-observed.ets new file mode 100644 index 000000000..54dc8f89b --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-observed.ets @@ -0,0 +1,54 @@ +import { Component, Entry, Column, Button, ClickEvent } from "@ohos.arkui.component" +import { State, ObjectLink, Observed } from "@ohos.arkui.stateManagement" + +@Observed +class DateClass extends Date { + constructor(args: number | string) { + super(args); + } +} + +@Observed +class NewDate { + public data: DateClass; + + constructor(data: DateClass) { + this.data = data; + } +} + +@Component +struct Child { + label: string = 'date'; + @ObjectLink data: DateClass; + + build() { + Column() { + Button(`child increase the day by 1`) + .onClick((e: ClickEvent) => { + this.data.setDate(this.data.getDate() + 1); + }) + } + } +} + +@Entry +@Component +struct Parent { + @State newData: NewDate = new NewDate(new DateClass('2023-1-1')); + + build() { + Column() { + Child({ label: 'date', data: this.newData.data }) + + Button(`parent update the new date`) + .onClick(() => { + this.newData.data = new DateClass('2023-07-07'); + }) + Button(`ViewB: this.newData = new NewDate(new DateClass('2023-08-20'))`) + .onClick(() => { + this.newData = new NewDate(new DateClass('2023-08-20')); + }) + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-only.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-only.ets new file mode 100644 index 000000000..3890ea9ec --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-only.ets @@ -0,0 +1,13 @@ +import { Component } from "@ohos.arkui.component" +import { Observed } from "@ohos.arkui.stateManagement" + +@Observed +class A { + propA: number = 1 + trackA: number = 2 +} + +@Component +struct MyStateSample { + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-class-property.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-class-property.ets new file mode 100644 index 000000000..48a3cd405 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-class-property.ets @@ -0,0 +1,19 @@ +import { Component } from "@ohos.arkui.component" +import { Observed, Track } from "@ohos.arkui.stateManagement" + +class Info{} +class E { + propE: Info = new Info() + @Track trackE: Info = new Info() +} + +@Observed +class E1 { + propE1: Info = new Info() + trackE1: Info = new Info() +} + +@Component +struct MyStateSample { + build() {} +} diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-complex-type.ets new file mode 100644 index 000000000..bf59d6d51 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-complex-type.ets @@ -0,0 +1,76 @@ +import { Component, Entry } from "@ohos.arkui.component" +import { Observed, Track } from "@ohos.arkui.stateManagement" + +class Person{ +} + +enum Status { + Success = 200, + NotFound = 404, + ServerError = 500 +} + +@Observed +class mixed1 { + @Track numA: number = 33; + @Track stringA: string = 'AA'; + @Track booleanA: boolean = true; + @Track arrayA: number[] = [1,2,3]; + @Track objectA: Object = {}; + @Track dateA: Date = new Date('2021-08-08'); + @Track setA: Set = new Set(); + @Track mapA: Map = new Map(); + @Track unionA: string | undefined = ""; + @Track classA: Person = new Person(); + @Track enumA: Status = Status.NotFound; + + numB: number = 33; + stringB: string = 'AA'; + booleanB: boolean = true; + arrayB: number[] = [1,2,3]; + objectB: Object = {}; + dateB: Date = new Date('2021-08-08'); + setB: Set = new Set(); + mapB: Map = new Map(); + unionB: string | undefined = ""; + classB: Person = new Person(); + enumB: Status = Status.NotFound; +} + +@Observed +class mixed2 { + numA: number = 33; + stringA: string = 'AA'; + booleanA: boolean = true; + arrayA: number[] = [1,2,3]; + objectA: Object = {}; + dateA: Date = new Date('2021-08-08'); + setA: Set = new Set(); + mapA: Map = new Map(); + unionA: string | undefined = ""; + classA: Person = new Person(); + enumA: Status = Status.NotFound; +} + +class mixed3 { + @Track numA: number = 33; + @Track stringA: string = 'AA'; + @Track booleanA: boolean = true; + @Track arrayA: number[] = [1,2,3]; + @Track objectA: Object = {}; + @Track dateA: Date = new Date('2021-08-08'); + @Track setA: Set = new Set(); + @Track mapA: Map = new Map(); + @Track unionA: string | undefined = ""; + @Track classA: Person = new Person(); + @Track enumA: Status = Status.NotFound; +} + + +@Entry +@Component +struct MyStateSample { + build() { + + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-extends.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-extends.ets new file mode 100644 index 000000000..66135926a --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-extends.ets @@ -0,0 +1,23 @@ +import { Component } from "@ohos.arkui.component" +import { Observed, Track } from "@ohos.arkui.stateManagement" + +@Observed +class A { + propA: number = 1 + trackA: number = 2 +} + + +class G extends A { + propG: number = 1; +} + +@Observed +class H extends G { + @Track propG: number = 1; +} + +@Component +struct MyStateSample { + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-implements.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-implements.ets new file mode 100644 index 000000000..5be8bd871 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-implements.ets @@ -0,0 +1,20 @@ +import { Component } from "@ohos.arkui.component" +import { Observed } from "@ohos.arkui.stateManagement" + interface PropInterface { + propF: number +} + +interface trackInterface { + trackF: number +} + +@Observed +class F implements PropInterface, trackInterface { + propF: number = 1 + trackF: number = 2 +} + +@Component +struct MyStateSample { + build() {} +} diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track.ets new file mode 100644 index 000000000..3d15c071a --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track.ets @@ -0,0 +1,13 @@ +import { Component } from "@ohos.arkui.component" +import { Observed, Track } from "@ohos.arkui.stateManagement" + +@Observed +class B { + propB: number = 1 + @Track trackB: number = 2 +} + +@Component +struct MyStateSample { + build() {} +} diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/track-only.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/track-only.ets new file mode 100644 index 000000000..fea1df86e --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/observed-track/track-only.ets @@ -0,0 +1,12 @@ +import { Component } from "@ohos.arkui.component" +import { Track } from "@ohos.arkui.stateManagement" + +class C { + propC: number = 1 + @Track trackC: number = 2 +} + +@Component +struct MyStateSample { + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets b/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets new file mode 100644 index 000000000..755a647b3 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets @@ -0,0 +1,19 @@ +import { Component, Reusable} from "@ohos.arkui.component" +import { State, Link } from "@ohos.arkui.stateManagement" + +@Component +struct MyStateSample { + build() { + Child({ num: 5 } ) + } +} + +@Component +@Reusable +struct Child { + @Link num: number = 1 + @State num1: number = 2 + build() { + + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/reusable/reusable-complex.ets b/arkui-plugins/test/demo/mock/decorators/reusable/reusable-complex.ets new file mode 100644 index 000000000..d66fe5451 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/reusable/reusable-complex.ets @@ -0,0 +1,53 @@ +import { Component, Entry, Reusable, Column, Text, Button, ClickEvent, FontWeight} from "@ohos.arkui.component" +import { State } from "@ohos.arkui.stateManagement" + +class Message { + value: string | undefined; + + constructor(value: string) { + this.value = value; + } +} + +@Entry +@Component +struct Index { + @State display: boolean = true; + + build() { + Column() { + Button('Hello') + .fontSize(30) + .fontWeight(FontWeight.Bold) + .onClick((e: ClickEvent) => { + this.display = !this.display; + }) + if (this.display) { + // 如果只有一个复用的组件,可以不用设置reuseId + Child({ message: new Message('Child') }) + } + } + .height("100%") + .width('100%') + } +} + +@Reusable +@Component +struct Child { + @State message: Message = new Message('AboutToReuse'); + + aboutToReuse(params: Record) { + console.info("Recycle ====Child=="); + //this.message = params.message as Message; + } + + build() { + Column() { + Text(this.message.value) + .fontSize(30) + } + .borderWidth(1) + .height(100) + } +} diff --git a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-appstorage.ets b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-appstorage.ets new file mode 100644 index 000000000..298dc8955 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-appstorage.ets @@ -0,0 +1,35 @@ +import { Component, Entry, Column, Text, ClickEvent } from "@ohos.arkui.component" +import { StorageLink, AppStorage } from "@ohos.arkui.stateManagement" + +class Data { + code: number; + + constructor(code: number) { + this.code = code; + } +} + +AppStorage.setOrCreate('PropA', 47); +AppStorage.setOrCreate('PropB', new Data(50)); + + +@Entry +@Component +struct Index { + @StorageLink('PropA') storageLink: number = 1; + @StorageLink('PropB') storageLinkObject: Data = new Data(1); + + build() { + Column() { + Text(`From AppStorage ${this.storageLink}`) + .onClick((e: ClickEvent) => { + this.storageLink += 1; + }) + + Text(`From AppStorage ${this.storageLinkObject.code}`) + .onClick((e: ClickEvent) => { + this.storageLinkObject.code += 1; + }) + } + } +} diff --git a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-complex-type.ets new file mode 100644 index 000000000..9aed6364d --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-complex-type.ets @@ -0,0 +1,28 @@ +import { Component, Entry } from "@ohos.arkui.component" +import { StorageLink } from "@ohos.arkui.stateManagement" + +class Person{ + name: string = '' + constructor(name: string){} +} + +enum Status { + Success = 200, + NotFound = 404, + ServerError = 500 +} + +@Entry +@Component +struct MyStateSample { + @StorageLink('Prop1') arrayA: number[] = [1,2,3]; + @StorageLink('Prop2') objectA: Object = {}; + @StorageLink('Prop3') dateA: Date = new Date('2021-08-08'); + @StorageLink('Prop4') setA: Set = new Set(); + @StorageLink('Prop5') mapA: Map = new Map(); + @StorageLink('Prop6') unionA: string | undefined = ""; + @StorageLink('Prop7') classA: Person = new Person("John"); + @StorageLink('Prop8') enumA: Status = Status.NotFound; + + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-primitive-type.ets b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-primitive-type.ets new file mode 100644 index 000000000..e5afb4d19 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-primitive-type.ets @@ -0,0 +1,12 @@ +import { Component, Entry } from "@ohos.arkui.component" +import { StorageLink } from "@ohos.arkui.stateManagement" + +@Entry +@Component +struct MyStateSample { + @StorageLink('Prop1') numA: number = 33; + @StorageLink('Prop2') stringA: string = 'AA'; + @StorageLink('Prop3') booleanA: boolean = true; + + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-appstorage.ets b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-appstorage.ets new file mode 100644 index 000000000..bff353a17 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-appstorage.ets @@ -0,0 +1,34 @@ +import { Component, Entry, Column, Text, ClickEvent } from "@ohos.arkui.component" +import { StorageProp, AppStorage } from "@ohos.arkui.stateManagement" + +class Data { + code: number; + + constructor(code: number) { + this.code = code; + } +} + +AppStorage.setOrCreate('PropA', 47); +AppStorage.setOrCreate('PropB', new Data(50)); + +@Entry +@Component +struct Index { + @StorageProp('PropA') storageProp: number = 1; + @StorageProp('PropB') storagePropObject: Data = new Data(1); + + build() { + Column() { + Text(`From AppStorage ${this.storageProp}`) + .onClick((e: ClickEvent) => { + this.storageProp += 1; + }) + + Text(`From AppStorage ${this.storagePropObject.code}`) + .onClick((e: ClickEvent) => { + this.storagePropObject.code += 1; + }) + } + } +} diff --git a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-complex-type.ets new file mode 100644 index 000000000..5a770cf6e --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-complex-type.ets @@ -0,0 +1,28 @@ +import { Component, Entry } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins +import { StorageProp } from "@ohos.arkui.stateManagement" + +class Person{ + name: string = '' + constructor(name: string){} +} + +enum Status { + Success = 200, + NotFound = 404, + ServerError = 500 +} + +@Entry +@Component +struct MyStateSample { + @StorageProp('Prop1') arrayB: number[] = [1,2,3]; + @StorageProp('Prop2') objectB: Object = {}; + @StorageProp('Prop3') dateB: Date = new Date('2021-09-09'); + @StorageProp('Prop4') setB: Set = new Set(); + @StorageProp('Prop5') mapB: Map = new Map(); + @StorageProp('Prop6') unionB: string | undefined = ""; + @StorageProp('Prop7') classB: Person = new Person("Kevin"); + @StorageProp('Prop8') enumB: Status = Status.NotFound; + + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-primitive-type.ets b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-primitive-type.ets new file mode 100644 index 000000000..d82a28552 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-primitive-type.ets @@ -0,0 +1,12 @@ +import { Component, Entry } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins +import { StorageProp } from "@ohos.arkui.stateManagement" + +@Entry +@Component +struct MyStateSample { + @StorageProp('Prop1') numB: number = 43; + @StorageProp('Prop2') stringB: string = 'BB'; + @StorageProp('Prop3') booleanB: boolean = false; + + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/watch/watch-basic.ets b/arkui-plugins/test/demo/mock/decorators/watch/watch-basic.ets new file mode 100644 index 000000000..6a85ab00a --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/watch/watch-basic.ets @@ -0,0 +1,41 @@ +import { Component, Entry } from "@ohos.arkui.component" +import { State, Prop, StorageLink, StorageProp, Link, Watch, ObjectLink, Observed, Track, Provide, Consume } from "@ohos.arkui.stateManagement" + +@Observed +class A { + propA: string = 'hello' + @Track trackA: string = 'world' +} + +@Entry +@Component +struct MyStateSample { + @State @Watch('stateOnChange') statevar: string = 'Hello World'; + @Prop @Watch('propOnChange') propvar: string = 'Hello World'; + // @Link @Watch('linkOnChange') linkvar: string; + @StorageLink('prop1') @Watch('storageLinkOnChange') storagelinkvar: string = 'Hello World'; + @StorageProp('prop2') @Watch('storagePropOnChange') storagepropvar: string = 'Hello World'; + // @ObjectLink @Watch('objectLinkOnChange') objectlinkvar: A; + @Provide @Watch('ProvideOnChange') providevar: string = 'Hello World'; + + stateOnChange(propName: string) {} + propOnChange(propName: string) {} + // linkOnChange(propName: string) {} + storageLinkOnChange(propName: string) {} + storagePropOnChange(propName: string) {} + // objectLinkOnChange(propName: string) {} + ProvideOnChange(propName: string) {} + + build() { + Child() + } +} + +@Component +struct Child { + // @Consume @Watch('ConsumeOnChange') providevar: string; + + // ConsumeOnChange(propName: string) {} + + build() {} +} \ No newline at end of file diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts new file mode 100644 index 000000000..55af0dd86 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-only.ets'), +]; + +const observedTrackTransform: Plugins = { + name: 'observedTrack', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test observed only transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; + +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; + +import { int32 as int32 } from "@koalaui.runtime.common"; + +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; + +import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; + +import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; + +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component } from "@ohos.arkui.component"; + +import { Observed as Observed } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +@Observed() class A implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); + + private __backing_propA: number = 1; + + private __backing_trackA: number = 2; + + public constructor() {} + + public get propA(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_propA!; + } + + public set propA(newValue: number) { + if ((((this).__backing_propA) !== (newValue))) { + (this).__backing_propA = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("propA"); + } + } + + public get trackA(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_trackA!; + } + + public set trackA(newValue: number) { + if ((((this).__backing_trackA) !== (newValue))) { + (this).__backing_trackA = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("trackA"); + } + } + +} + +@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + +function testObservedOnlyTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test observed only transform', + [observedTrackTransform, uiNoRecheck], + { + checked: [testObservedOnlyTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts new file mode 100644 index 000000000..becd4ced5 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track-class-property.ets'), +]; + +const observedTrackTransform: Plugins = { + name: 'observedTrack', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test observed track transform with class property', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; + +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; + +import { int32 as int32 } from "@koalaui.runtime.common"; + +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; + +import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; + +import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; + +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component } from "@ohos.arkui.component"; + +import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +class Info { + public constructor() {} + +} + +class E implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + public propE: Info = new Info(); + + private __backing_trackE: BackingValue = new BackingValue(new Info()); + + private __meta_trackE: MutableStateMeta = new MutableStateMeta("@Track"); + + public constructor() {} + + public get trackE(): Info { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_trackE.addRef(); + } + setObservationDepth((this).__backing_trackE.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_trackE.value!; + } + + public set trackE(newValue: Info) { + if ((((this).__backing_trackE.value) !== (newValue))) { + (this).__backing_trackE.value = newValue; + (this).__meta_trackE.fireChange(); + (this).executeOnSubscribingWatches("trackE"); + } + } + +} + +@Observed() class E1 implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); + + private __backing_propE1: BackingValue = new BackingValue(new Info()); + + private __backing_trackE1: BackingValue = new BackingValue(new Info()); + + public constructor() {} + + public get propE1(): Info { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_propE1.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_propE1.value!; + } + + public set propE1(newValue: Info) { + if ((((this).__backing_propE1.value) !== (newValue))) { + (this).__backing_propE1.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("propE1"); + } + } + + public get trackE1(): Info { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_trackE1.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_trackE1.value!; + } + + public set trackE1(newValue: Info) { + if ((((this).__backing_trackE1.value) !== (newValue))) { + (this).__backing_trackE1.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("trackE1"); + } + } + +} + +@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} +`; + +function testObservedOnlyTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test observed track transform with class property', + [observedTrackTransform, uiNoRecheck], + { + checked: [testObservedOnlyTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts new file mode 100644 index 000000000..b0635b8a9 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts @@ -0,0 +1,898 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track-complex-type.ets'), +]; + +const observedTrackTransform: Plugins = { + name: 'observedTrack', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test observed track transform with complex type', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; + +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; + +import { int32 as int32 } from "@koalaui.runtime.common"; + +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; + +import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; + +import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; + +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; + +import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +class Person { + public constructor() {} + +} + +final class Status extends BaseEnum { + private readonly #ordinal: int; + + private static () {} + + public constructor(ordinal: int, value: int) { + super(value); + (this).#ordinal = ordinal; + } + + public static readonly Success: Status = new Status(0, 200); + + public static readonly NotFound: Status = new Status(1, 404); + + public static readonly ServerError: Status = new Status(2, 500); + + private static readonly #NamesArray: String[] = ["Success", "NotFound", "ServerError"]; + + private static readonly #ValuesArray: int[] = [200, 404, 500]; + + private static readonly #StringValuesArray: String[] = ["200", "404", "500"]; + + private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; + + public getName(): String { + return Status.#NamesArray[(this).#ordinal]; + } + + public static getValueOf(name: String): Status { + for (let i = 0;((i) < (Status.#NamesArray.length));(++i)) { + if (((name) == (Status.#NamesArray[i]))) { + return Status.#ItemsArray[i]; + } + } + throw new Error((("No enum constant Status.") + (name))); + } + + public static fromValue(value: int): Status { + for (let i = 0;((i) < (Status.#ValuesArray.length));(++i)) { + if (((value) == (Status.#ValuesArray[i]))) { + return Status.#ItemsArray[i]; + } + } + throw new Error((("No enum Status with value ") + (value))); + } + + public valueOf(): int { + return Status.#ValuesArray[(this).#ordinal]; + } + + public toString(): String { + return Status.#StringValuesArray[(this).#ordinal]; + } + + public static values(): Status[] { + return Status.#ItemsArray; + } + + public getOrdinal(): int { + return (this).#ordinal; + } + + public static $_get(e: Status): String { + return e.getName(); + } + +} + +@Observed() class mixed1 implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + private __backing_numA: number = 33; + + private __meta_numA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_stringA: string = "AA"; + + private __meta_stringA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_booleanA: boolean = true; + + private __meta_booleanA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_arrayA: BackingValue> = new BackingValue>([1, 2, 3]); + + private __meta_arrayA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_objectA: BackingValue = new BackingValue({}); + + private __meta_objectA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_dateA: BackingValue = new BackingValue(new Date("2021-08-08")); + + private __meta_dateA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_setA: BackingValue> = new BackingValue>(new Set()); + + private __meta_setA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_mapA: BackingValue> = new BackingValue>(new Map()); + + private __meta_mapA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_unionA: string | undefined = ""; + + private __meta_unionA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_classA: BackingValue = new BackingValue(new Person()); + + private __meta_classA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_enumA: BackingValue = new BackingValue(Status.NotFound); + + private __meta_enumA: MutableStateMeta = new MutableStateMeta("@Track"); + + public numB: number = 33; + + public stringB: string = "AA"; + + public booleanB: boolean = true; + + public arrayB: Array = [1, 2, 3]; + + public objectB: Object = {}; + + public dateB: Date = new Date("2021-08-08"); + + public setB: Set = new Set(); + + public mapB: Map = new Map(); + + public unionB: string | undefined = ""; + + public classB: Person = new Person(); + + public enumB: Status = Status.NotFound; + + public constructor() {} + + public get numA(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_numA.addRef(); + } + return (this).__backing_numA!; + } + + public set numA(newValue: number) { + if ((((this).__backing_numA) !== (newValue))) { + (this).__backing_numA = newValue; + (this).__meta_numA.fireChange(); + (this).executeOnSubscribingWatches("numA"); + } + } + + public get stringA(): string { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_stringA.addRef(); + } + return (this).__backing_stringA!; + } + + public set stringA(newValue: string) { + if ((((this).__backing_stringA) !== (newValue))) { + (this).__backing_stringA = newValue; + (this).__meta_stringA.fireChange(); + (this).executeOnSubscribingWatches("stringA"); + } + } + + public get booleanA(): boolean { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_booleanA.addRef(); + } + return (this).__backing_booleanA!; + } + + public set booleanA(newValue: boolean) { + if ((((this).__backing_booleanA) !== (newValue))) { + (this).__backing_booleanA = newValue; + (this).__meta_booleanA.fireChange(); + (this).executeOnSubscribingWatches("booleanA"); + } + } + + public get arrayA(): Array { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_arrayA.addRef(); + } + setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_arrayA.value!; + } + + public set arrayA(newValue: Array) { + if ((((this).__backing_arrayA.value) !== (newValue))) { + (this).__backing_arrayA.value = newValue; + (this).__meta_arrayA.fireChange(); + (this).executeOnSubscribingWatches("arrayA"); + } + } + + public get objectA(): Object { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_objectA.addRef(); + } + setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_objectA.value!; + } + + public set objectA(newValue: Object) { + if ((((this).__backing_objectA.value) !== (newValue))) { + (this).__backing_objectA.value = newValue; + (this).__meta_objectA.fireChange(); + (this).executeOnSubscribingWatches("objectA"); + } + } + + public get dateA(): Date { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_dateA.addRef(); + } + setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_dateA.value!; + } + + public set dateA(newValue: Date) { + if ((((this).__backing_dateA.value) !== (newValue))) { + (this).__backing_dateA.value = newValue; + (this).__meta_dateA.fireChange(); + (this).executeOnSubscribingWatches("dateA"); + } + } + + public get setA(): Set { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_setA.addRef(); + } + setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_setA.value!; + } + + public set setA(newValue: Set) { + if ((((this).__backing_setA.value) !== (newValue))) { + (this).__backing_setA.value = newValue; + (this).__meta_setA.fireChange(); + (this).executeOnSubscribingWatches("setA"); + } + } + + public get mapA(): Map { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_mapA.addRef(); + } + setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_mapA.value!; + } + + public set mapA(newValue: Map) { + if ((((this).__backing_mapA.value) !== (newValue))) { + (this).__backing_mapA.value = newValue; + (this).__meta_mapA.fireChange(); + (this).executeOnSubscribingWatches("mapA"); + } + } + + public get unionA(): string | undefined { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_unionA.addRef(); + } + return (this).__backing_unionA!; + } + + public set unionA(newValue: string | undefined) { + if ((((this).__backing_unionA) !== (newValue))) { + (this).__backing_unionA = newValue; + (this).__meta_unionA.fireChange(); + (this).executeOnSubscribingWatches("unionA"); + } + } + + public get classA(): Person { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_classA.addRef(); + } + setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_classA.value!; + } + + public set classA(newValue: Person) { + if ((((this).__backing_classA.value) !== (newValue))) { + (this).__backing_classA.value = newValue; + (this).__meta_classA.fireChange(); + (this).executeOnSubscribingWatches("classA"); + } + } + + public get enumA(): Status { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_enumA.addRef(); + } + setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_enumA.value!; + } + + public set enumA(newValue: Status) { + if ((((this).__backing_enumA.value) !== (newValue))) { + (this).__backing_enumA.value = newValue; + (this).__meta_enumA.fireChange(); + (this).executeOnSubscribingWatches("enumA"); + } + } + +} + +@Observed() class mixed2 implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); + + private __backing_numA: number = 33; + + private __backing_stringA: string = "AA"; + + private __backing_booleanA: boolean = true; + + private __backing_arrayA: BackingValue> = new BackingValue>([1, 2, 3]); + + private __backing_objectA: BackingValue = new BackingValue({}); + + private __backing_dateA: BackingValue = new BackingValue(new Date("2021-08-08")); + + private __backing_setA: BackingValue> = new BackingValue>(new Set()); + + private __backing_mapA: BackingValue> = new BackingValue>(new Map()); + + private __backing_unionA: string | undefined = ""; + + private __backing_classA: BackingValue = new BackingValue(new Person()); + + private __backing_enumA: BackingValue = new BackingValue(Status.NotFound); + + public constructor() {} + + public get numA(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_numA!; + } + + public set numA(newValue: number) { + if ((((this).__backing_numA) !== (newValue))) { + (this).__backing_numA = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("numA"); + } + } + + public get stringA(): string { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_stringA!; + } + + public set stringA(newValue: string) { + if ((((this).__backing_stringA) !== (newValue))) { + (this).__backing_stringA = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("stringA"); + } + } + + public get booleanA(): boolean { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_booleanA!; + } + + public set booleanA(newValue: boolean) { + if ((((this).__backing_booleanA) !== (newValue))) { + (this).__backing_booleanA = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("booleanA"); + } + } + + public get arrayA(): Array { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_arrayA.value!; + } + + public set arrayA(newValue: Array) { + if ((((this).__backing_arrayA.value) !== (newValue))) { + (this).__backing_arrayA.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("arrayA"); + } + } + + public get objectA(): Object { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_objectA.value!; + } + + public set objectA(newValue: Object) { + if ((((this).__backing_objectA.value) !== (newValue))) { + (this).__backing_objectA.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("objectA"); + } + } + + public get dateA(): Date { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_dateA.value!; + } + + public set dateA(newValue: Date) { + if ((((this).__backing_dateA.value) !== (newValue))) { + (this).__backing_dateA.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("dateA"); + } + } + + public get setA(): Set { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_setA.value!; + } + + public set setA(newValue: Set) { + if ((((this).__backing_setA.value) !== (newValue))) { + (this).__backing_setA.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("setA"); + } + } + + public get mapA(): Map { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_mapA.value!; + } + + public set mapA(newValue: Map) { + if ((((this).__backing_mapA.value) !== (newValue))) { + (this).__backing_mapA.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("mapA"); + } + } + + public get unionA(): string | undefined { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_unionA!; + } + + public set unionA(newValue: string | undefined) { + if ((((this).__backing_unionA) !== (newValue))) { + (this).__backing_unionA = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("unionA"); + } + } + + public get classA(): Person { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_classA.value!; + } + + public set classA(newValue: Person) { + if ((((this).__backing_classA.value) !== (newValue))) { + (this).__backing_classA.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("classA"); + } + } + + public get enumA(): Status { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_enumA.value!; + } + + public set enumA(newValue: Status) { + if ((((this).__backing_enumA.value) !== (newValue))) { + (this).__backing_enumA.value = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("enumA"); + } + } + +} + +class mixed3 implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + private __backing_numA: number = 33; + + private __meta_numA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_stringA: string = "AA"; + + private __meta_stringA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_booleanA: boolean = true; + + private __meta_booleanA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_arrayA: BackingValue> = new BackingValue>([1, 2, 3]); + + private __meta_arrayA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_objectA: BackingValue = new BackingValue({}); + + private __meta_objectA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_dateA: BackingValue = new BackingValue(new Date("2021-08-08")); + + private __meta_dateA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_setA: BackingValue> = new BackingValue>(new Set()); + + private __meta_setA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_mapA: BackingValue> = new BackingValue>(new Map()); + + private __meta_mapA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_unionA: string | undefined = ""; + + private __meta_unionA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_classA: BackingValue = new BackingValue(new Person()); + + private __meta_classA: MutableStateMeta = new MutableStateMeta("@Track"); + + private __backing_enumA: BackingValue = new BackingValue(Status.NotFound); + + private __meta_enumA: MutableStateMeta = new MutableStateMeta("@Track"); + + public constructor() {} + + public get numA(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_numA.addRef(); + } + return (this).__backing_numA!; + } + + public set numA(newValue: number) { + if ((((this).__backing_numA) !== (newValue))) { + (this).__backing_numA = newValue; + (this).__meta_numA.fireChange(); + (this).executeOnSubscribingWatches("numA"); + } + } + + public get stringA(): string { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_stringA.addRef(); + } + return (this).__backing_stringA!; + } + + public set stringA(newValue: string) { + if ((((this).__backing_stringA) !== (newValue))) { + (this).__backing_stringA = newValue; + (this).__meta_stringA.fireChange(); + (this).executeOnSubscribingWatches("stringA"); + } + } + + public get booleanA(): boolean { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_booleanA.addRef(); + } + return (this).__backing_booleanA!; + } + + public set booleanA(newValue: boolean) { + if ((((this).__backing_booleanA) !== (newValue))) { + (this).__backing_booleanA = newValue; + (this).__meta_booleanA.fireChange(); + (this).executeOnSubscribingWatches("booleanA"); + } + } + + public get arrayA(): Array { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_arrayA.addRef(); + } + setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_arrayA.value!; + } + + public set arrayA(newValue: Array) { + if ((((this).__backing_arrayA.value) !== (newValue))) { + (this).__backing_arrayA.value = newValue; + (this).__meta_arrayA.fireChange(); + (this).executeOnSubscribingWatches("arrayA"); + } + } + + public get objectA(): Object { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_objectA.addRef(); + } + setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_objectA.value!; + } + + public set objectA(newValue: Object) { + if ((((this).__backing_objectA.value) !== (newValue))) { + (this).__backing_objectA.value = newValue; + (this).__meta_objectA.fireChange(); + (this).executeOnSubscribingWatches("objectA"); + } + } + + public get dateA(): Date { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_dateA.addRef(); + } + setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_dateA.value!; + } + + public set dateA(newValue: Date) { + if ((((this).__backing_dateA.value) !== (newValue))) { + (this).__backing_dateA.value = newValue; + (this).__meta_dateA.fireChange(); + (this).executeOnSubscribingWatches("dateA"); + } + } + + public get setA(): Set { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_setA.addRef(); + } + setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_setA.value!; + } + + public set setA(newValue: Set) { + if ((((this).__backing_setA.value) !== (newValue))) { + (this).__backing_setA.value = newValue; + (this).__meta_setA.fireChange(); + (this).executeOnSubscribingWatches("setA"); + } + } + + public get mapA(): Map { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_mapA.addRef(); + } + setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_mapA.value!; + } + + public set mapA(newValue: Map) { + if ((((this).__backing_mapA.value) !== (newValue))) { + (this).__backing_mapA.value = newValue; + (this).__meta_mapA.fireChange(); + (this).executeOnSubscribingWatches("mapA"); + } + } + + public get unionA(): string | undefined { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_unionA.addRef(); + } + return (this).__backing_unionA!; + } + + public set unionA(newValue: string | undefined) { + if ((((this).__backing_unionA) !== (newValue))) { + (this).__backing_unionA = newValue; + (this).__meta_unionA.fireChange(); + (this).executeOnSubscribingWatches("unionA"); + } + } + + public get classA(): Person { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_classA.addRef(); + } + setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_classA.value!; + } + + public set classA(newValue: Person) { + if ((((this).__backing_classA.value) !== (newValue))) { + (this).__backing_classA.value = newValue; + (this).__meta_classA.fireChange(); + (this).executeOnSubscribingWatches("classA"); + } + } + + public get enumA(): Status { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_enumA.addRef(); + } + setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); + return (this).__backing_enumA.value!; + } + + public set enumA(newValue: Status) { + if ((((this).__backing_enumA.value) !== (newValue))) { + (this).__backing_enumA.value = newValue; + (this).__meta_enumA.fireChange(); + (this).executeOnSubscribingWatches("enumA"); + } + } + +} + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + MyStateSample._instantiateImpl(undefined, (() => { + return new MyStateSample(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} +`; + +function testObservedOnlyTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test observed track transform with complex type', + [observedTrackTransform, uiNoRecheck], + { + checked: [testObservedOnlyTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts new file mode 100644 index 000000000..47237cf0c --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track-extends.ets'), +]; + +const observedTrackTransform: Plugins = { + name: 'observedTrack', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test observed track transform with extends', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; + +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; + +import { int32 as int32 } from "@koalaui.runtime.common"; + +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; + +import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; + +import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; + +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component } from "@ohos.arkui.component"; + +import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +@Observed() class A implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); + + private __backing_propA: number = 1; + + private __backing_trackA: number = 2; + + public constructor() {} + + public get propA(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_propA!; + } + + public set propA(newValue: number) { + if ((((this).__backing_propA) !== (newValue))) { + (this).__backing_propA = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("propA"); + } + } + + public get trackA(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_trackA!; + } + + public set trackA(newValue: number) { + if ((((this).__backing_trackA) !== (newValue))) { + (this).__backing_trackA = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("trackA"); + } + } + +} + +class G extends A { + public propG: number = 1; + + public constructor() {} + +} + +@Observed() class H extends G implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + private __backing_propG: number = 1; + + private __meta_propG: MutableStateMeta = new MutableStateMeta("@Track"); + + public constructor() {} + + public get propG(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_propG.addRef(); + } + return (this).__backing_propG!; + } + + public set propG(newValue: number) { + if ((((this).__backing_propG) !== (newValue))) { + (this).__backing_propG = newValue; + (this).__meta_propG.fireChange(); + (this).executeOnSubscribingWatches("propG"); + } + } + +} + +@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + +function testObservedOnlyTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test observed track transform with extends', + [observedTrackTransform, uiNoRecheck], + { + checked: [testObservedOnlyTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts new file mode 100644 index 000000000..c4239714b --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track-implements.ets'), +]; + +const observedTrackTransform: Plugins = { + name: 'observedTrack', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test observed track transform with implements', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; + +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; + +import { int32 as int32 } from "@koalaui.runtime.common"; + +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; + +import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; + +import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; + +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component } from "@ohos.arkui.component"; + +import { Observed as Observed } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +interface PropInterface { + set propF(propF: number) + + get propF(): number + +} + +interface trackInterface { + set trackF(trackF: number) + + get trackF(): number + +} + +@Observed() class F implements PropInterface, trackInterface, IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); + + private __backing_propF: number = 1; + + private __backing_trackF: number = 2; + + public constructor() {} + + public set propF(newValue: number) { + if ((((this).__backing_propF) !== (newValue))) { + (this).__backing_propF = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("propF"); + } + } + + public get propF(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_propF!; + } + + public set trackF(newValue: number) { + if ((((this).__backing_trackF) !== (newValue))) { + (this).__backing_trackF = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("trackF"); + } + } + + public get trackF(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta.addRef(); + } + return (this).__backing_trackF!; + } + + public set propF(newValue: number) { + if ((((this).__backing_propF) !== (newValue))) { + (this).__backing_propF = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("propF"); + } + } + + public set trackF(newValue: number) { + if ((((this).__backing_trackF) !== (newValue))) { + (this).__backing_trackF = newValue; + (this).__meta.fireChange(); + (this).executeOnSubscribingWatches("trackF"); + } + } + +} + +@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + +function testObservedOnlyTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test observed track transform with implements', + [observedTrackTransform, uiNoRecheck], + { + checked: [testObservedOnlyTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts new file mode 100644 index 000000000..95a77ed88 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track.ets'), +]; + +const observedTrackTransform: Plugins = { + name: 'observedTrack', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test observed with track transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; + +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; + +import { int32 as int32 } from "@koalaui.runtime.common"; + +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; + +import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; + +import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; + +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component } from "@ohos.arkui.component"; + +import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +@Observed() class B implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + public propB: number = 1; + + private __backing_trackB: number = 2; + + private __meta_trackB: MutableStateMeta = new MutableStateMeta("@Track"); + + public constructor() {} + + public get trackB(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_trackB.addRef(); + } + return (this).__backing_trackB!; + } + + public set trackB(newValue: number) { + if ((((this).__backing_trackB) !== (newValue))) { + (this).__backing_trackB = newValue; + (this).__meta_trackB.fireChange(); + (this).executeOnSubscribingWatches("trackB"); + } + } + +} + +@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + +function testObservedOnlyTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test observed with track transform', + [observedTrackTransform, uiNoRecheck], + { + checked: [testObservedOnlyTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts new file mode 100644 index 000000000..c21fe95f3 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'track-only.ets'), +]; + +const observedTrackTransform: Plugins = { + name: 'observedTrack', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test track only transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; + +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; + +import { int32 as int32 } from "@koalaui.runtime.common"; + +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; + +import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; + +import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; + +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component } from "@ohos.arkui.component"; + +import { Track as Track } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +class C implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + public propC: number = 1; + + private __backing_trackC: number = 2; + + private __meta_trackC: MutableStateMeta = new MutableStateMeta("@Track"); + + public constructor() {} + + public get trackC(): number { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_trackC.addRef(); + } + return (this).__backing_trackC!; + } + + public set trackC(newValue: number) { + if ((((this).__backing_trackC) !== (newValue))) { + (this).__backing_trackC = newValue; + (this).__meta_trackC.fireChange(); + (this).executeOnSubscribingWatches("trackC"); + } + } + +} + +@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +`; + +function testObservedOnlyTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test track only transform', + [observedTrackTransform, uiNoRecheck], + { + checked: [testObservedOnlyTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts new file mode 100644 index 000000000..f4a20b03e --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const REUSABLE_DIR_PATH: string = 'decorators/reusable'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, REUSABLE_DIR_PATH, 'reusable-basic.ets'), +]; + +const reusableTransform: Plugins = { + name: 'reusable', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test basic reusable', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; + +import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Reusable as Reusable } from "@ohos.arkui.component"; + +import { State as State, Link as Link } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void { + Child._instantiateImpl(undefined, (() => { + return new Child(); + }), ({ + num: 5, + } as __Options_Child), undefined, "Child"); + } + + public constructor() {} + +} + +@Component({freezeWhenInactive:false}) @Reusable() final class Child extends CustomComponent { + public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { + if (({let gensym___98468840 = initializers; + (((gensym___98468840) == (null)) ? undefined : gensym___98468840.__backing_num)})) { + (this).__backing_num = new LinkDecoratedVariable("num", initializers!.__backing_num!); + }; + (this).__backing_num1 = new StateDecoratedVariable("num1", ((({let gensym___33833641 = initializers; + (((gensym___33833641) == (null)) ? undefined : gensym___33833641.num1)})) ?? (2))); + } + + public __updateStruct(initializers: __Options_Child | undefined): void {} + + public override __toRecord(params: Object): Record { + const paramsCasted = (params as __Options_Child); + return { + "num": ((paramsCasted.num) ?? (new Object())), + "num1": ((paramsCasted.num1) ?? (new Object())), + }; + } + + private __backing_num?: LinkDecoratedVariable; + + public get num(): number { + return (this).__backing_num!.get(); + } + + public set num(value: number) { + (this).__backing_num!.set(value); + } + + private __backing_num1?: StateDecoratedVariable; + + public get num1(): number { + return (this).__backing_num1!.get(); + } + + public set num1(value: number) { + (this).__backing_num1!.set(value); + } + + @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + +} + +interface __Options_Child { + set num(num: number | undefined) + + get num(): number | undefined + set __backing_num(__backing_num: DecoratedV1VariableBase | undefined) + + get __backing_num(): DecoratedV1VariableBase | undefined + set num1(num1: number | undefined) + + get num1(): number | undefined + set __backing_num1(__backing_num1: StateDecoratedVariable | undefined) + + get __backing_num1(): StateDecoratedVariable | undefined + +} +`; + +function testReusableTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test basic reusable', + [reusableTransform, uiNoRecheck], + { + checked: [testReusableTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts new file mode 100644 index 000000000..dbbd61448 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const REUSABLE_DIR_PATH: string = 'decorators/reusable'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, REUSABLE_DIR_PATH, 'reusable-complex.ets'), +]; + +const reusableTransform: Plugins = { + name: 'reusable', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test complex reusable', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; + +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; + +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry, Reusable as Reusable, Column as Column, Text as Text, Button as Button, ClickEvent as ClickEvent, FontWeight as FontWeight } from "@ohos.arkui.component"; + +import { State as State } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +class Message { + public value: string | undefined; + + public constructor(value: string) { + (this).value = value; + } + +} + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { + public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_display = new StateDecoratedVariable("display", ((({let gensym___83835842 = initializers; + (((gensym___83835842) == (null)) ? undefined : gensym___83835842.display)})) ?? (true))); + } + + public __updateStruct(initializers: __Options_Index | undefined): void {} + + private __backing_display?: StateDecoratedVariable; + + public get display(): boolean { + return (this).__backing_display!.get(); + } + + public set display(value: boolean) { + (this).__backing_display!.set(value); + } + + @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { + Column(@memo() ((instance: UIColumnAttribute): void => { + instance.height("100%").width("100%"); + return; + }), undefined, (() => { + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.fontSize(30).fontWeight(FontWeight.Bold).onClick(((e: ClickEvent) => { + (this).display = !((this).display); + })); + return; + }), "Hello", undefined, undefined); + if ((this).display) { + Child._instantiateImpl(undefined, (() => { + return new Child(); + }), ({ + message: new Message("Child"), + } as __Options_Child), undefined, "Child"); + } + })); + } + + public constructor() {} + +} + +@Reusable() @Component({freezeWhenInactive:false}) final class Child extends CustomComponent { + public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_message = new StateDecoratedVariable("message", ((({let gensym___91869411 = initializers; + (((gensym___91869411) == (null)) ? undefined : gensym___91869411.message)})) ?? (new Message("AboutToReuse")))); + } + + public __updateStruct(initializers: __Options_Child | undefined): void {} + + public override __toRecord(params: Object): Record { + const paramsCasted = (params as __Options_Child); + return { + "message": ((paramsCasted.message) ?? (new Object())), + }; + } + + private __backing_message?: StateDecoratedVariable; + + public get message(): Message { + return (this).__backing_message!.get(); + } + + public set message(value: Message) { + (this).__backing_message!.set(value); + } + + public aboutToReuse(params: Record) { + console.info("Recycle ====Child=="); + } + + @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { + Column(@memo() ((instance: UIColumnAttribute): void => { + instance.borderWidth(1).height(100); + return; + }), undefined, (() => { + Text(@memo() ((instance: UITextAttribute): void => { + instance.fontSize(30); + return; + }), (this).message.value, undefined, undefined); + })); + } + + public constructor() {} + +} + +interface __Options_Index { + set display(display: boolean | undefined) + + get display(): boolean | undefined + set __backing_display(__backing_display: StateDecoratedVariable | undefined) + + get __backing_display(): StateDecoratedVariable | undefined + +} + +interface __Options_Child { + set message(message: Message | undefined) + + get message(): Message | undefined + set __backing_message(__backing_message: StateDecoratedVariable | undefined) + + get __backing_message(): StateDecoratedVariable | undefined + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + Index._instantiateImpl(undefined, (() => { + return new Index(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} + +`; + +function testReusableTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test complex reusable', + [reusableTransform, uiNoRecheck], + { + checked: [testReusableTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts new file mode 100644 index 000000000..8e1832428 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const STORAGELINK_DIR_PATH: string = 'decorators/storagelink'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGELINK_DIR_PATH, 'storagelink-appstorage.ets'), +]; + +const storageLinkTransform: Plugins = { + name: 'storageLink', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test storagelink with appstorage', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; + +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; + +import { StorageLink as StorageLink, AppStorage as AppStorage } from "@ohos.arkui.stateManagement"; + +function main() {} + +AppStorage.setOrCreate("PropA", 47); +AppStorage.setOrCreate("PropB", new Data(50)); + +class Data { + public code: number; + + public constructor(code: number) { + (this).code = code; + } + +} + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { + public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_storageLink = new StorageLinkDecoratedVariable("PropA", "storageLink", 1) + (this).__backing_storageLinkObject = new StorageLinkDecoratedVariable("PropB", "storageLinkObject", new Data(1)) + } + + public __updateStruct(initializers: __Options_Index | undefined): void {} + + private __backing_storageLink?: StorageLinkDecoratedVariable; + + public get storageLink(): number { + return (this).__backing_storageLink!.get(); + } + + public set storageLink(value: number) { + (this).__backing_storageLink!.set(value); + } + + private __backing_storageLinkObject?: StorageLinkDecoratedVariable; + + public get storageLinkObject(): Data { + return (this).__backing_storageLinkObject!.get(); + } + + public set storageLinkObject(value: Data) { + (this).__backing_storageLinkObject!.set(value); + } + + @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { + Column(undefined, undefined, (() => { + Text(@memo() ((instance: UITextAttribute): void => { + instance.onClick(((e: ClickEvent) => { + (this).storageLink += 1; + })); + return; + }), \`From AppStorage \${(this).storageLink}\`, undefined, undefined); + Text(@memo() ((instance: UITextAttribute): void => { + instance.onClick(((e: ClickEvent) => { + (this).storageLinkObject.code += 1; + })); + return; + }), \`From AppStorage \${(this).storageLinkObject.code}\`, undefined, undefined); + })); + } + + public constructor() {} + +} + +interface __Options_Index { + set storageLink(storageLink: number | undefined) + + get storageLink(): number | undefined + set __backing_storageLink(__backing_storageLink: StorageLinkDecoratedVariable | undefined) + + get __backing_storageLink(): StorageLinkDecoratedVariable | undefined + set storageLinkObject(storageLinkObject: Data | undefined) + + get storageLinkObject(): Data | undefined + set __backing_storageLinkObject(__backing_storageLinkObject: StorageLinkDecoratedVariable | undefined) + + get __backing_storageLinkObject(): StorageLinkDecoratedVariable | undefined + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + Index._instantiateImpl(undefined, (() => { + return new Index(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} +`; + +function testStorageLinkTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test storagelink with appstorage', + [storageLinkTransform, uiNoRecheck], + { + checked: [testStorageLinkTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts new file mode 100644 index 000000000..c060b7a83 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const STORAGELINK_DIR_PATH: string = 'decorators/storagelink'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGELINK_DIR_PATH, 'storagelink-complex-type.ets'), +]; + +const storageLinkTransform: Plugins = { + name: 'storageLink', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test storagelink complex type transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; + +import { StorageLink as StorageLink } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +class Person { + public name: string = ""; + + public constructor(name: string) {} + +} + +final class Status extends BaseEnum { + private readonly #ordinal: int; + + private static () {} + + public constructor(ordinal: int, value: int) { + super(value); + (this).#ordinal = ordinal; + } + + public static readonly Success: Status = new Status(0, 200); + + public static readonly NotFound: Status = new Status(1, 404); + + public static readonly ServerError: Status = new Status(2, 500); + + private static readonly #NamesArray: String[] = ["Success", "NotFound", "ServerError"]; + + private static readonly #ValuesArray: int[] = [200, 404, 500]; + + private static readonly #StringValuesArray: String[] = ["200", "404", "500"]; + + private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; + + public getName(): String { + return Status.#NamesArray[(this).#ordinal]; + } + + public static getValueOf(name: String): Status { + for (let i = 0;((i) < (Status.#NamesArray.length));(++i)) { + if (((name) == (Status.#NamesArray[i]))) { + return Status.#ItemsArray[i]; + } + } + throw new Error((("No enum constant Status.") + (name))); + } + + public static fromValue(value: int): Status { + for (let i = 0;((i) < (Status.#ValuesArray.length));(++i)) { + if (((value) == (Status.#ValuesArray[i]))) { + return Status.#ItemsArray[i]; + } + } + throw new Error((("No enum Status with value ") + (value))); + } + + public valueOf(): int { + return Status.#ValuesArray[(this).#ordinal]; + } + + public toString(): String { + return Status.#StringValuesArray[(this).#ordinal]; + } + + public static values(): Status[] { + return Status.#ItemsArray; + } + + public getOrdinal(): int { + return (this).#ordinal; + } + + public static $_get(e: Status): String { + return e.getName(); + } + +} + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_arrayA = new StorageLinkDecoratedVariable>("Prop1", "arrayA", [1, 2, 3]) + (this).__backing_objectA = new StorageLinkDecoratedVariable("Prop2", "objectA", {}) + (this).__backing_dateA = new StorageLinkDecoratedVariable("Prop3", "dateA", new Date("2021-08-08")) + (this).__backing_setA = new StorageLinkDecoratedVariable>("Prop4", "setA", new Set()) + (this).__backing_mapA = new StorageLinkDecoratedVariable>("Prop5", "mapA", new Map()) + (this).__backing_unionA = new StorageLinkDecoratedVariable("Prop6", "unionA", "") + (this).__backing_classA = new StorageLinkDecoratedVariable("Prop7", "classA", new Person("John")) + (this).__backing_enumA = new StorageLinkDecoratedVariable("Prop8", "enumA", Status.NotFound) + } + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + private __backing_arrayA?: StorageLinkDecoratedVariable>; + + public get arrayA(): Array { + return (this).__backing_arrayA!.get(); + } + + public set arrayA(value: Array) { + (this).__backing_arrayA!.set(value); + } + + private __backing_objectA?: StorageLinkDecoratedVariable; + + public get objectA(): Object { + return (this).__backing_objectA!.get(); + } + + public set objectA(value: Object) { + (this).__backing_objectA!.set(value); + } + + private __backing_dateA?: StorageLinkDecoratedVariable; + + public get dateA(): Date { + return (this).__backing_dateA!.get(); + } + + public set dateA(value: Date) { + (this).__backing_dateA!.set(value); + } + + private __backing_setA?: StorageLinkDecoratedVariable>; + + public get setA(): Set { + return (this).__backing_setA!.get(); + } + + public set setA(value: Set) { + (this).__backing_setA!.set(value); + } + + private __backing_mapA?: StorageLinkDecoratedVariable>; + + public get mapA(): Map { + return (this).__backing_mapA!.get(); + } + + public set mapA(value: Map) { + (this).__backing_mapA!.set(value); + } + + private __backing_unionA?: StorageLinkDecoratedVariable; + + public get unionA(): string | undefined { + return (this).__backing_unionA!.get(); + } + + public set unionA(value: string | undefined) { + (this).__backing_unionA!.set(value); + } + + private __backing_classA?: StorageLinkDecoratedVariable; + + public get classA(): Person { + return (this).__backing_classA!.get(); + } + + public set classA(value: Person) { + (this).__backing_classA!.set(value); + } + + private __backing_enumA?: StorageLinkDecoratedVariable; + + public get enumA(): Status { + return (this).__backing_enumA!.get(); + } + + public set enumA(value: Status) { + (this).__backing_enumA!.set(value); + } + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + set arrayA(arrayA: Array | undefined) + + get arrayA(): Array | undefined + set __backing_arrayA(__backing_arrayA: StorageLinkDecoratedVariable> | undefined) + + get __backing_arrayA(): StorageLinkDecoratedVariable> | undefined + set objectA(objectA: Object | undefined) + + get objectA(): Object | undefined + set __backing_objectA(__backing_objectA: StorageLinkDecoratedVariable | undefined) + + get __backing_objectA(): StorageLinkDecoratedVariable | undefined + set dateA(dateA: Date | undefined) + + get dateA(): Date | undefined + set __backing_dateA(__backing_dateA: StorageLinkDecoratedVariable | undefined) + + get __backing_dateA(): StorageLinkDecoratedVariable | undefined + set setA(setA: Set | undefined) + + get setA(): Set | undefined + set __backing_setA(__backing_setA: StorageLinkDecoratedVariable> | undefined) + + get __backing_setA(): StorageLinkDecoratedVariable> | undefined + set mapA(mapA: Map | undefined) + + get mapA(): Map | undefined + set __backing_mapA(__backing_mapA: StorageLinkDecoratedVariable> | undefined) + + get __backing_mapA(): StorageLinkDecoratedVariable> | undefined + set unionA(unionA: string | undefined | undefined) + + get unionA(): string | undefined | undefined + set __backing_unionA(__backing_unionA: StorageLinkDecoratedVariable | undefined) + + get __backing_unionA(): StorageLinkDecoratedVariable | undefined + set classA(classA: Person | undefined) + + get classA(): Person | undefined + set __backing_classA(__backing_classA: StorageLinkDecoratedVariable | undefined) + + get __backing_classA(): StorageLinkDecoratedVariable | undefined + set enumA(enumA: Status | undefined) + + get enumA(): Status | undefined + set __backing_enumA(__backing_enumA: StorageLinkDecoratedVariable | undefined) + + get __backing_enumA(): StorageLinkDecoratedVariable | undefined + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + MyStateSample._instantiateImpl(undefined, (() => { + return new MyStateSample(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} + +`; + +function testStorageLinkTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test storagelink complex type transform', + [storageLinkTransform, uiNoRecheck], + { + checked: [testStorageLinkTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts new file mode 100644 index 000000000..e129e2600 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const STORAGELINK_DIR_PATH: string = 'decorators/storagelink'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGELINK_DIR_PATH, 'storagelink-primitive-type.ets'), +]; + +const storageLinkTransform: Plugins = { + name: 'storageLink', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test storagelink primitive type transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; + +import { StorageLink as StorageLink } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_numA = new StorageLinkDecoratedVariable("Prop1", "numA", 33) + (this).__backing_stringA = new StorageLinkDecoratedVariable("Prop2", "stringA", "AA") + (this).__backing_booleanA = new StorageLinkDecoratedVariable("Prop3", "booleanA", true) + } + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + private __backing_numA?: StorageLinkDecoratedVariable; + + public get numA(): number { + return (this).__backing_numA!.get(); + } + + public set numA(value: number) { + (this).__backing_numA!.set(value); + } + + private __backing_stringA?: StorageLinkDecoratedVariable; + + public get stringA(): string { + return (this).__backing_stringA!.get(); + } + + public set stringA(value: string) { + (this).__backing_stringA!.set(value); + } + + private __backing_booleanA?: StorageLinkDecoratedVariable; + + public get booleanA(): boolean { + return (this).__backing_booleanA!.get(); + } + + public set booleanA(value: boolean) { + (this).__backing_booleanA!.set(value); + } + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + set numA(numA: number | undefined) + + get numA(): number | undefined + set __backing_numA(__backing_numA: StorageLinkDecoratedVariable | undefined) + + get __backing_numA(): StorageLinkDecoratedVariable | undefined + set stringA(stringA: string | undefined) + + get stringA(): string | undefined + set __backing_stringA(__backing_stringA: StorageLinkDecoratedVariable | undefined) + + get __backing_stringA(): StorageLinkDecoratedVariable | undefined + set booleanA(booleanA: boolean | undefined) + + get booleanA(): boolean | undefined + set __backing_booleanA(__backing_booleanA: StorageLinkDecoratedVariable | undefined) + + get __backing_booleanA(): StorageLinkDecoratedVariable | undefined + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + MyStateSample._instantiateImpl(undefined, (() => { + return new MyStateSample(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} + +`; + +function testStorageLinkTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test storagelink primitive type transform', + [storageLinkTransform, uiNoRecheck], + { + checked: [testStorageLinkTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts new file mode 100644 index 000000000..a403e00a9 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const STORAGEPROP_DIR_PATH: string = 'decorators/storageprop'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGEPROP_DIR_PATH, 'storageprop-appstorage.ets'), +]; + +const storagePropTransform: Plugins = { + name: 'storageprop', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test storageprop with appstorage', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; + +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; + +import { StorageProp as StorageProp, AppStorage as AppStorage } from "@ohos.arkui.stateManagement"; + +function main() {} + +AppStorage.setOrCreate("PropA", 47); +AppStorage.setOrCreate("PropB", new Data(50)); + +class Data { + public code: number; + + public constructor(code: number) { + (this).code = code; + } + +} + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { + public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_storageProp = new StoragePropDecoratedVariable("PropA", "storageProp", 1) + (this).__backing_storagePropObject = new StoragePropDecoratedVariable("PropB", "storagePropObject", new Data(1)) + } + + public __updateStruct(initializers: __Options_Index | undefined): void {} + + private __backing_storageProp?: StoragePropDecoratedVariable; + + public get storageProp(): number { + return (this).__backing_storageProp!.get(); + } + + public set storageProp(value: number) { + (this).__backing_storageProp!.set(value); + } + + private __backing_storagePropObject?: StoragePropDecoratedVariable; + + public get storagePropObject(): Data { + return (this).__backing_storagePropObject!.get(); + } + + public set storagePropObject(value: Data) { + (this).__backing_storagePropObject!.set(value); + } + + @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { + Column(undefined, undefined, (() => { + Text(@memo() ((instance: UITextAttribute): void => { + instance.onClick(((e: ClickEvent) => { + (this).storageProp += 1; + })); + return; + }), \`From AppStorage \${(this).storageProp}\`, undefined, undefined); + Text(@memo() ((instance: UITextAttribute): void => { + instance.onClick(((e: ClickEvent) => { + (this).storagePropObject.code += 1; + })); + return; + }), \`From AppStorage \${(this).storagePropObject.code}\`, undefined, undefined); + })); + } + + public constructor() {} + +} + +interface __Options_Index { + set storageProp(storageProp: number | undefined) + + get storageProp(): number | undefined + set __backing_storageProp(__backing_storageProp: StoragePropDecoratedVariable | undefined) + + get __backing_storageProp(): StoragePropDecoratedVariable | undefined + set storagePropObject(storagePropObject: Data | undefined) + + get storagePropObject(): Data | undefined + set __backing_storagePropObject(__backing_storagePropObject: StoragePropDecoratedVariable | undefined) + + get __backing_storagePropObject(): StoragePropDecoratedVariable | undefined + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + Index._instantiateImpl(undefined, (() => { + return new Index(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} + +`; + +function testStoragePropTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test storageprop with appstorage', + [storagePropTransform, uiNoRecheck], + { + checked: [testStoragePropTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts new file mode 100644 index 000000000..aa649440b --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const STORAGEPROP_DIR_PATH: string = 'decorators/storageprop'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGEPROP_DIR_PATH, 'storageprop-complex-type.ets'), +]; + +const storagePropTransform: Plugins = { + name: 'storageprop', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test storageprop complex type transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; + +import { StorageProp as StorageProp } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +class Person { + public name: string = ""; + + public constructor(name: string) {} + +} + +final class Status extends BaseEnum { + private readonly #ordinal: int; + + private static () {} + + public constructor(ordinal: int, value: int) { + super(value); + (this).#ordinal = ordinal; + } + + public static readonly Success: Status = new Status(0, 200); + + public static readonly NotFound: Status = new Status(1, 404); + + public static readonly ServerError: Status = new Status(2, 500); + + private static readonly #NamesArray: String[] = ["Success", "NotFound", "ServerError"]; + + private static readonly #ValuesArray: int[] = [200, 404, 500]; + + private static readonly #StringValuesArray: String[] = ["200", "404", "500"]; + + private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; + + public getName(): String { + return Status.#NamesArray[(this).#ordinal]; + } + + public static getValueOf(name: String): Status { + for (let i = 0;((i) < (Status.#NamesArray.length));(++i)) { + if (((name) == (Status.#NamesArray[i]))) { + return Status.#ItemsArray[i]; + } + } + throw new Error((("No enum constant Status.") + (name))); + } + + public static fromValue(value: int): Status { + for (let i = 0;((i) < (Status.#ValuesArray.length));(++i)) { + if (((value) == (Status.#ValuesArray[i]))) { + return Status.#ItemsArray[i]; + } + } + throw new Error((("No enum Status with value ") + (value))); + } + + public valueOf(): int { + return Status.#ValuesArray[(this).#ordinal]; + } + + public toString(): String { + return Status.#StringValuesArray[(this).#ordinal]; + } + + public static values(): Status[] { + return Status.#ItemsArray; + } + + public getOrdinal(): int { + return (this).#ordinal; + } + + public static $_get(e: Status): String { + return e.getName(); + } + +} + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_arrayB = new StoragePropDecoratedVariable>("Prop1", "arrayB", [1, 2, 3]) + (this).__backing_objectB = new StoragePropDecoratedVariable("Prop2", "objectB", {}) + (this).__backing_dateB = new StoragePropDecoratedVariable("Prop3", "dateB", new Date("2021-09-09")) + (this).__backing_setB = new StoragePropDecoratedVariable>("Prop4", "setB", new Set()) + (this).__backing_mapB = new StoragePropDecoratedVariable>("Prop5", "mapB", new Map()) + (this).__backing_unionB = new StoragePropDecoratedVariable("Prop6", "unionB", "") + (this).__backing_classB = new StoragePropDecoratedVariable("Prop7", "classB", new Person("Kevin")) + (this).__backing_enumB = new StoragePropDecoratedVariable("Prop8", "enumB", Status.NotFound) + } + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + private __backing_arrayB?: StoragePropDecoratedVariable>; + + public get arrayB(): Array { + return (this).__backing_arrayB!.get(); + } + + public set arrayB(value: Array) { + (this).__backing_arrayB!.set(value); + } + + private __backing_objectB?: StoragePropDecoratedVariable; + + public get objectB(): Object { + return (this).__backing_objectB!.get(); + } + + public set objectB(value: Object) { + (this).__backing_objectB!.set(value); + } + + private __backing_dateB?: StoragePropDecoratedVariable; + + public get dateB(): Date { + return (this).__backing_dateB!.get(); + } + + public set dateB(value: Date) { + (this).__backing_dateB!.set(value); + } + + private __backing_setB?: StoragePropDecoratedVariable>; + + public get setB(): Set { + return (this).__backing_setB!.get(); + } + + public set setB(value: Set) { + (this).__backing_setB!.set(value); + } + + private __backing_mapB?: StoragePropDecoratedVariable>; + + public get mapB(): Map { + return (this).__backing_mapB!.get(); + } + + public set mapB(value: Map) { + (this).__backing_mapB!.set(value); + } + + private __backing_unionB?: StoragePropDecoratedVariable; + + public get unionB(): string | undefined { + return (this).__backing_unionB!.get(); + } + + public set unionB(value: string | undefined) { + (this).__backing_unionB!.set(value); + } + + private __backing_classB?: StoragePropDecoratedVariable; + + public get classB(): Person { + return (this).__backing_classB!.get(); + } + + public set classB(value: Person) { + (this).__backing_classB!.set(value); + } + + private __backing_enumB?: StoragePropDecoratedVariable; + + public get enumB(): Status { + return (this).__backing_enumB!.get(); + } + + public set enumB(value: Status) { + (this).__backing_enumB!.set(value); + } + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + set arrayB(arrayB: Array | undefined) + + get arrayB(): Array | undefined + set __backing_arrayB(__backing_arrayB: StoragePropDecoratedVariable> | undefined) + + get __backing_arrayB(): StoragePropDecoratedVariable> | undefined + set objectB(objectB: Object | undefined) + + get objectB(): Object | undefined + set __backing_objectB(__backing_objectB: StoragePropDecoratedVariable | undefined) + + get __backing_objectB(): StoragePropDecoratedVariable | undefined + set dateB(dateB: Date | undefined) + + get dateB(): Date | undefined + set __backing_dateB(__backing_dateB: StoragePropDecoratedVariable | undefined) + + get __backing_dateB(): StoragePropDecoratedVariable | undefined + set setB(setB: Set | undefined) + + get setB(): Set | undefined + set __backing_setB(__backing_setB: StoragePropDecoratedVariable> | undefined) + + get __backing_setB(): StoragePropDecoratedVariable> | undefined + set mapB(mapB: Map | undefined) + + get mapB(): Map | undefined + set __backing_mapB(__backing_mapB: StoragePropDecoratedVariable> | undefined) + + get __backing_mapB(): StoragePropDecoratedVariable> | undefined + set unionB(unionB: string | undefined | undefined) + + get unionB(): string | undefined | undefined + set __backing_unionB(__backing_unionB: StoragePropDecoratedVariable | undefined) + + get __backing_unionB(): StoragePropDecoratedVariable | undefined + set classB(classB: Person | undefined) + + get classB(): Person | undefined + set __backing_classB(__backing_classB: StoragePropDecoratedVariable | undefined) + + get __backing_classB(): StoragePropDecoratedVariable | undefined + set enumB(enumB: Status | undefined) + + get enumB(): Status | undefined + set __backing_enumB(__backing_enumB: StoragePropDecoratedVariable | undefined) + + get __backing_enumB(): StoragePropDecoratedVariable | undefined + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + MyStateSample._instantiateImpl(undefined, (() => { + return new MyStateSample(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} +`; + +function testStoragePropTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test storageprop complex type transform', + [storagePropTransform, uiNoRecheck], + { + checked: [testStoragePropTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts new file mode 100644 index 000000000..c56d42735 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const STORAGEPROP_DIR_PATH: string = 'decorators/storageprop'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGEPROP_DIR_PATH, 'storageprop-primitive-type.ets'), +]; + +const storagePropTransform: Plugins = { + name: 'storageprop', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test storageprop primitive type transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; + +import { StorageProp as StorageProp } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_numB = new StoragePropDecoratedVariable("Prop1", "numB", 43) + (this).__backing_stringB = new StoragePropDecoratedVariable("Prop2", "stringB", "BB") + (this).__backing_booleanB = new StoragePropDecoratedVariable("Prop3", "booleanB", false) + } + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} + + private __backing_numB?: StoragePropDecoratedVariable; + + public get numB(): number { + return (this).__backing_numB!.get(); + } + + public set numB(value: number) { + (this).__backing_numB!.set(value); + } + + private __backing_stringB?: StoragePropDecoratedVariable; + + public get stringB(): string { + return (this).__backing_stringB!.get(); + } + + public set stringB(value: string) { + (this).__backing_stringB!.set(value); + } + + private __backing_booleanB?: StoragePropDecoratedVariable; + + public get booleanB(): boolean { + return (this).__backing_booleanB!.get(); + } + + public set booleanB(value: boolean) { + (this).__backing_booleanB!.set(value); + } + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + set numB(numB: number | undefined) + + get numB(): number | undefined + set __backing_numB(__backing_numB: StoragePropDecoratedVariable | undefined) + + get __backing_numB(): StoragePropDecoratedVariable | undefined + set stringB(stringB: string | undefined) + + get stringB(): string | undefined + set __backing_stringB(__backing_stringB: StoragePropDecoratedVariable | undefined) + + get __backing_stringB(): StoragePropDecoratedVariable | undefined + set booleanB(booleanB: boolean | undefined) + + get booleanB(): boolean | undefined + set __backing_booleanB(__backing_booleanB: StoragePropDecoratedVariable | undefined) + + get __backing_booleanB(): StoragePropDecoratedVariable | undefined + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + MyStateSample._instantiateImpl(undefined, (() => { + return new MyStateSample(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} +`; + +function testStoragePropTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test storageprop primitive type transform', + [storagePropTransform, uiNoRecheck], + { + checked: [testStoragePropTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts new file mode 100644 index 000000000..692bf1f24 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const WATCH_DIR_PATH: string = 'decorators/watch'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, WATCH_DIR_PATH, 'watch-basic.ets'), +]; + +const watchTransform: Plugins = { + name: 'watch', + parsed: uiTransform().parsed, +}; + +const pluginTester = new PluginTester('test basic watch transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { ConsumeDecoratedVariable as ConsumeDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; + +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; + +import { int32 as int32 } from "@koalaui.runtime.common"; + +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; + +import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; + +import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; + +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; + +import { ObjectLinkDecoratedVariable as ObjectLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; + +import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; + +import { State as State, Prop as Prop, StorageLink as StorageLink, StorageProp as StorageProp, Link as Link, Watch as Watch, ObjectLink as ObjectLink, Observed as Observed, Track as Track, Provide as Provide, Consume as Consume } from "@ohos.arkui.stateManagement"; + +function main() {} + + + +@Observed() class A implements IObservedObject { + private subscribedWatches: SubscribedWatches = new SubscribedWatches(); + + public addWatchSubscriber(watchId: WatchIdType): void { + (this).subscribedWatches.addWatchSubscriber(watchId); + } + + public removeWatchSubscriber(watchId: WatchIdType): boolean { + return (this).subscribedWatches.removeWatchSubscriber(watchId); + } + + public executeOnSubscribingWatches(propertyName: string): void { + (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + } + + public _permissibleAddRefDepth: int32 = 0; + + public propA: string = "hello"; + + private __backing_trackA: string = "world"; + + private __meta_trackA: MutableStateMeta = new MutableStateMeta("@Track"); + + public constructor() {} + + public get trackA(): string { + if ((((this)._permissibleAddRefDepth) > (0))) { + (this).__meta_trackA.addRef(); + } + return (this).__backing_trackA!; + } + + public set trackA(newValue: string) { + if ((((this).__backing_trackA) !== (newValue))) { + (this).__backing_trackA = newValue; + (this).__meta_trackA.fireChange(); + (this).executeOnSubscribingWatches("trackA"); + } + } + +} + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { + public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_statevar = new StateDecoratedVariable("statevar", ((({let gensym___76198660 = initializers; + (((gensym___76198660) == (null)) ? undefined : gensym___76198660.statevar)})) ?? ("Hello World")), ((_: string): void => { + (this).stateOnChange(_); + })); + (this).__backing_propvar = new PropDecoratedVariable("propvar", ((({let gensym___241486692 = initializers; + (((gensym___241486692) == (null)) ? undefined : gensym___241486692.propvar)})) ?? ("Hello World")), ((_: string): void => { + (this).propOnChange(_); + })); + (this).__backing_storagelinkvar = new StorageLinkDecoratedVariable("prop1", "storagelinkvar", "Hello World", ((_: string): void => { + (this).storageLinkOnChange(_); + })) + (this).__backing_storagepropvar = new StoragePropDecoratedVariable("prop2", "storagepropvar", "Hello World", ((_: string): void => { + (this).storagePropOnChange(_); + })) + (this).__backing_providevar = (this).addProvidedVar("providevar", "providevar", ((({let gensym___194235814 = initializers; + (((gensym___194235814) == (null)) ? undefined : gensym___194235814.providevar)})) ?? ("Hello World")), false, ((_: string): void => { + (this).ProvideOnChange(_); + })); + } + + public __updateStruct(initializers: __Options_MyStateSample | undefined): void { + if (((({let gensym___220608839 = initializers; + (((gensym___220608839) == (null)) ? undefined : gensym___220608839.propvar)})) !== (undefined))) { + (this).__backing_propvar!.update((initializers!.propvar as string)); + } + } + + private __backing_statevar?: StateDecoratedVariable; + + public get statevar(): string { + return (this).__backing_statevar!.get(); + } + + public set statevar(value: string) { + (this).__backing_statevar!.set(value); + } + + private __backing_propvar?: PropDecoratedVariable; + + public get propvar(): string { + return (this).__backing_propvar!.get(); + } + + public set propvar(value: string) { + (this).__backing_propvar!.set(value); + } + + private __backing_storagelinkvar?: StorageLinkDecoratedVariable; + + public get storagelinkvar(): string { + return (this).__backing_storagelinkvar!.get(); + } + + public set storagelinkvar(value: string) { + (this).__backing_storagelinkvar!.set(value); + } + + private __backing_storagepropvar?: StoragePropDecoratedVariable; + + public get storagepropvar(): string { + return (this).__backing_storagepropvar!.get(); + } + + public set storagepropvar(value: string) { + (this).__backing_storagepropvar!.set(value); + } + + private __backing_providevar?: ProvideDecoratedVariable; + + public get providevar(): string { + return (this).__backing_providevar!.get(); + } + + public set providevar(value: string) { + (this).__backing_providevar!.set(value); + } + + public stateOnChange(propName: string) {} + + public propOnChange(propName: string) {} + + public storageLinkOnChange(propName: string) {} + + public storagePropOnChange(propName: string) {} + + public ProvideOnChange(propName: string) {} + + @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void { + Child._instantiateImpl(undefined, (() => { + return new Child(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} + +@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { + public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_Child | undefined): void {} + + @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void {} + + public constructor() {} + +} + +interface __Options_MyStateSample { + set statevar(statevar: string | undefined) + + get statevar(): string | undefined + set __backing_statevar(__backing_statevar: StateDecoratedVariable | undefined) + + get __backing_statevar(): StateDecoratedVariable | undefined + set propvar(propvar: string | undefined) + + get propvar(): string | undefined + set __backing_propvar(__backing_propvar: PropDecoratedVariable | undefined) + + get __backing_propvar(): PropDecoratedVariable | undefined + set storagelinkvar(storagelinkvar: string | undefined) + + get storagelinkvar(): string | undefined + set __backing_storagelinkvar(__backing_storagelinkvar: StorageLinkDecoratedVariable | undefined) + + get __backing_storagelinkvar(): StorageLinkDecoratedVariable | undefined + set storagepropvar(storagepropvar: string | undefined) + + get storagepropvar(): string | undefined + set __backing_storagepropvar(__backing_storagepropvar: StoragePropDecoratedVariable | undefined) + + get __backing_storagepropvar(): StoragePropDecoratedVariable | undefined + set providevar(providevar: string | undefined) + + get providevar(): string | undefined + set __backing_providevar(__backing_providevar: ProvideDecoratedVariable | undefined) + + get __backing_providevar(): ProvideDecoratedVariable | undefined + +} + +interface __Options_Child { + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + MyStateSample._instantiateImpl(undefined, (() => { + return new MyStateSample(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} + +`; + +function testWatchTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test basic watch transform', + [watchTransform, uiNoRecheck], + { + checked: [testWatchTransformer], + }, + { + stopAfter: 'checked', + } +); -- Gitee From 651b792884e75951aca9e33df9d6b57bf2dcad15 Mon Sep 17 00:00:00 2001 From: y00896775 Date: Tue, 29 Apr 2025 20:20:38 +0800 Subject: [PATCH 078/123] insert undefined in custom component Signed-off-by: y00896775 Change-Id: Iaa3c577ab7031a3b8184bbadde00c9989d6fa12a --- .../custom-component-call.ets | 43 +++++ .../builder-param/builder-param-passing.ets | 41 +++++ .../builder-param/init-with-local-builder.ets | 29 +++ .../custom-component-call.test.ts | 166 ++++++++++++++++++ .../builder-param-passing.test.ts | 133 ++++++++++++++ .../init-with-local-builder.test.ts | 100 +++++++++++ .../ui-plugins/preprocessor-transform.ts | 17 +- 7 files changed, 524 insertions(+), 5 deletions(-) create mode 100644 arkui-plugins/test/demo/mock/builder-lambda/custom-component/custom-component-call.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/builder-param/builder-param-passing.ets create mode 100644 arkui-plugins/test/demo/mock/decorators/builder-param/init-with-local-builder.ets create mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts diff --git a/arkui-plugins/test/demo/mock/builder-lambda/custom-component/custom-component-call.ets b/arkui-plugins/test/demo/mock/builder-lambda/custom-component/custom-component-call.ets new file mode 100644 index 000000000..4da86661b --- /dev/null +++ b/arkui-plugins/test/demo/mock/builder-lambda/custom-component/custom-component-call.ets @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Text, Column, Component, Builder, BuilderParam } from "@ohos.arkui.component" + +@Component +struct CustomContainer { + @Builder closerBuilder(){}; + @BuilderParam closer: () => void = this.closerBuilder; + + build() {} +} + +@Component +struct CustomContainerUser { + + build() { + Column() { + CustomContainer() { + Column() { + Text('hello') + } + } + CustomContainer({}) { + Column() {} + } + CustomContainer(undefined) {} + CustomContainer() + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/builder-param/builder-param-passing.ets b/arkui-plugins/test/demo/mock/decorators/builder-param/builder-param-passing.ets new file mode 100644 index 000000000..c679899b2 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/builder-param/builder-param-passing.ets @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Entry, Builder, BuilderParam, Column, Text } from "@ohos.arkui.component" + +@Component +struct Child { + @Builder customBuilder() {}; + @BuilderParam customBuilderParam: () => void = this.customBuilder; + + build() { + this.customBuilderParam() + } +} + +@Component +struct Parent { + @Builder componentBuilder() { + Text('Parent builder') + } + + build() { + Column() { + Child({ customBuilderParam: this.componentBuilder }) + Child({ customBuilderParam: () => { this.componentBuilder() } }) + Child() { Text('Parent builder') } + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/builder-param/init-with-local-builder.ets b/arkui-plugins/test/demo/mock/decorators/builder-param/init-with-local-builder.ets new file mode 100644 index 000000000..e1e2b46c9 --- /dev/null +++ b/arkui-plugins/test/demo/mock/decorators/builder-param/init-with-local-builder.ets @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, Builder, BuilderParam } from "@ohos.arkui.component" + +@Component +struct Child { + @Builder doNothingBuilder() {}; + @Builder doNothingBuilder2(str: string) {}; + @BuilderParam customBuilderParam: () => void = this.doNothingBuilder; + @BuilderParam customBuilderParam2: (str: string) => void = this.doNothingBuilder2; + + build(){ + this.customBuilderParam() + this.customBuilderParam2('hello') + } +} \ No newline at end of file diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts new file mode 100644 index 000000000..b9a0d5943 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'builder-lambda'; +const CUSTOM_COMPONENT_DIR_PATH: string = 'custom-component'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, CUSTOM_COMPONENT_DIR_PATH, 'custom-component-call.ets'), +]; + +const pluginTester = new PluginTester('test custom component call transformation', buildConfig); + +const parsedTransform: Plugins = { + name: 'custom-component-call', + parsed: uiTransform().parsed +}; + +const expectedParsedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Text as Text, Column as Column, Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; + +@Component() final class CustomContainer extends CustomComponent { + @Builder() public closerBuilder() {} + @BuilderParam() public closer: (()=> void) = (this).closerBuilder; + public build() {} + public constructor() {} +} + +@Component() final class CustomContainerUser extends CustomComponent { + public build() { + Column(undefined){ + CustomContainer(undefined){ + Column(undefined){ + Text("hello", undefined); + }; + }; + CustomContainer(({} as __Options_CustomContainer)){ + Column(undefined){}; + }; + CustomContainer(undefined){}; + CustomContainer(); + }; + } + public constructor() {} +} + +interface __Options_CustomContainer { + closer?: @memo() (()=> void); +} + +interface __Options_CustomContainerUser { +} +`; + +function testParedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedParsedScript)); +} + +const expectedBuilderLambdaScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Text as Text, Column as Column, Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class CustomContainer extends CustomComponent { + public __initializeStruct(initializers: __Options_CustomContainer | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_closer = ((((({let gensym___38813563 = initializers; + (((gensym___38813563) == (null)) ? undefined : gensym___38813563.closer)})) ?? (content))) ?? ((this).closerBuilder)) + } + public __updateStruct(initializers: __Options_CustomContainer | undefined): void {} + private __backing_closer?: @memo() (()=> void); + public get closer(): @memo() (()=> void) { + return (this).__backing_closer!; + } + public set closer(@memo() value: (()=> void)) { + (this).__backing_closer = value; + } + @memo() public closerBuilder() {} + @memo() public _build(@memo() style: ((instance: CustomContainer)=> CustomContainer) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CustomContainer | undefined): void {} + public constructor() {} +} + +@Component({freezeWhenInactive:false}) final class CustomContainerUser extends CustomComponent { + public __initializeStruct(initializers: __Options_CustomContainerUser | undefined, @memo() content: (()=> void) | undefined): void {} + public __updateStruct(initializers: __Options_CustomContainerUser | undefined): void {} + @memo() public _build(@memo() style: ((instance: CustomContainerUser)=> CustomContainerUser) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CustomContainerUser | undefined): void { + Column(undefined, undefined, (() => { + CustomContainer._instantiateImpl(undefined, (() => { + return new CustomContainer(); + }), undefined, (() => { + Column(undefined, undefined, (() => { + Text(undefined, "hello", undefined, undefined); + })); + }), undefined); + CustomContainer._instantiateImpl(undefined, (() => { + return new CustomContainer(); + }), ({} as __Options_CustomContainer), (() => { + Column(undefined, undefined, (() => {})); + }), undefined); + CustomContainer._instantiateImpl(undefined, (() => { + return new CustomContainer(); + }), undefined, (() => {}), undefined); + CustomContainer._instantiateImpl(undefined, (() => { + return new CustomContainer(); + }), undefined, undefined, undefined); + })); + } + public constructor() {} +} + +interface __Options_CustomContainer { + set closer(closer: @memo() (()=> void) | undefined) + get closer(): @memo() (()=> void) | undefined +} + +interface __Options_CustomContainerUser { +} +`; + +function testCustomComponentTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedBuilderLambdaScript)); +} + +pluginTester.run( + 'test custom component call transformation', + [parsedTransform, recheck, uiNoRecheck], + { + parsed: [testParedTransformer], + 'checked:builder-lambda-no-recheck': [testCustomComponentTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts new file mode 100644 index 000000000..ba63b9e2d --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const FUNCTION_DIR_PATH: string = 'decorators/builder-param'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'builder-param-passing.ets'), +]; + +const pluginTester = new PluginTester('test builder param variable passing', buildConfig); + +const parsedTransform: Plugins = { + name: 'builder-param-passing', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, Entry as Entry, Builder as Builder, BuilderParam as BuilderParam, Column as Column, Text as Text } from "@ohos.arkui.component"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { + public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; + (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? ((this).customBuilder)) + } + + public __updateStruct(initializers: __Options_Child | undefined): void {} + + private __backing_customBuilderParam?: @memo() (()=> void); + + public get customBuilderParam(): @memo() (()=> void) { + return (this).__backing_customBuilderParam!; + } + + public set customBuilderParam(@memo() value: (()=> void)) { + (this).__backing_customBuilderParam = value; + } + + @memo() public customBuilder() {} + + @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { + (this).customBuilderParam(); + } + + public constructor() {} + +} + +@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { + public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_Parent | undefined): void {} + + @memo() public componentBuilder() { + Text(undefined, "Parent builder", undefined, undefined); + } + + @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void { + Column(undefined, undefined, (() => { + Child._instantiateImpl(undefined, (() => { + return new Child(); + }), ({ + customBuilderParam: (this).componentBuilder, + } as __Options_Child), undefined, undefined); + Child._instantiateImpl(undefined, (() => { + return new Child(); + }), ({ + customBuilderParam: @memo() (() => { + (this).componentBuilder(); + }), + } as __Options_Child), undefined, undefined); + Child._instantiateImpl(undefined, (() => { + return new Child(); + }), undefined, (() => { + Text(undefined, "Parent builder", undefined, undefined); + }), undefined); + })); + } + public constructor() {} +} + +interface __Options_Child { + set customBuilderParam(customBuilderParam: @memo() (()=> void) | undefined) + get customBuilderParam(): @memo() (()=> void) | undefined +} + +interface __Options_Parent { +} +`; + +function testCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test builder param variable passing', + [parsedTransform, uiNoRecheck], + { + 'checked:ui-no-recheck': [testCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts new file mode 100644 index 000000000..336ee7389 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; +import { parseDumpSrc } from '../../../../utils/parse-string'; +import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiTransform } from '../../../../../ui-plugins'; +import { Plugins } from '../../../../../common/plugin-context'; + +const FUNCTION_DIR_PATH: string = 'decorators/builder-param'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'init-with-local-builder.ets'), +]; + +const pluginTester = new PluginTester('test builder param init with local builder', buildConfig); + +const parsedTransform: Plugins = { + name: 'init-with-local-builder', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { + public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; + (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? ((this).doNothingBuilder)) + (this).__backing_customBuilderParam2 = ((((({let gensym___14041256 = initializers; + (((gensym___14041256) == (null)) ? undefined : gensym___14041256.customBuilderParam2)})) ?? (content))) ?? ((this).doNothingBuilder2)) + } + public __updateStruct(initializers: __Options_Child | undefined): void {} + private __backing_customBuilderParam?: @memo() (()=> void); + public get customBuilderParam(): @memo() (()=> void) { + return (this).__backing_customBuilderParam!; + } + public set customBuilderParam(@memo() value: (()=> void)) { + (this).__backing_customBuilderParam = value; + } + private __backing_customBuilderParam2?: @memo() ((str: string)=> void); + public get customBuilderParam2(): @memo() ((str: string)=> void) { + return (this).__backing_customBuilderParam2!; + } + public set customBuilderParam2(@memo() value: ((str: string)=> void)) { + (this).__backing_customBuilderParam2 = value; + } + @memo() public doNothingBuilder() {} + @memo() public doNothingBuilder2(str: string) {} + @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { + (this).customBuilderParam(); + (this).customBuilderParam2("hello"); + } + public constructor() {} +} + +interface __Options_Child { + set customBuilderParam(customBuilderParam: @memo() (()=> void) | undefined) + get customBuilderParam(): @memo() (()=> void) | undefined + set customBuilderParam2(customBuilderParam2: @memo() ((str: string)=> void) | undefined) + get customBuilderParam2(): @memo() ((str: string)=> void) | undefined +} +`; + +function testCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test builder param init with local builder', + [parsedTransform, uiNoRecheck], + { + 'checked:ui-no-recheck': [testCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 522f1ea10..d6f90b49c 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -66,8 +66,14 @@ export class PreprocessorTransformer extends AbstractVisitor { } transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { - if (arkts.isObjectExpression(node.arguments[0])) { - const componentName: string = `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${node.expression.dumpSrc()}`; + if (node.arguments.length === 0 && node.trailingBlock) { + return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ + arkts.factory.createUndefinedLiteral(), + ]); + } else if (arkts.isObjectExpression(node.arguments[0])) { + const componentName: string = `${ + CustomComponentNames.COMPONENT_INTERFACE_PREFIX + }${node.expression.dumpSrc()}`; const newArg = arkts.factory.createTSAsExpression( node.arguments[0].clone(), arkts.factory.createTypeReference( @@ -75,9 +81,10 @@ export class PreprocessorTransformer extends AbstractVisitor { ), true ); - return arkts.factory - .updateCallExpression(node, node.expression, node.typeArguments, [newArg, ...node.arguments.slice(1)]) - .setTralingBlock(node.trailingBlock); + return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ + newArg, + ...node.arguments.slice(1), + ]); } else { return node; } -- Gitee From 05e1759a02335f44c210db86ec95a57cd0f0facc Mon Sep 17 00:00:00 2001 From: Maxim Bolshov Date: Tue, 29 Apr 2025 13:26:56 +0300 Subject: [PATCH 079/123] Update hardcode that is meant be generated Signed-off-by: Maxim Bolshov --- koala-wrapper/native/src/generated/bridges.cc | 9 --------- koala-wrapper/src/generated/peers/NumberLiteral.ts | 3 --- 2 files changed, 12 deletions(-) diff --git a/koala-wrapper/native/src/generated/bridges.cc b/koala-wrapper/native/src/generated/bridges.cc index edb553d71..e1de4b1a1 100644 --- a/koala-wrapper/native/src/generated/bridges.cc +++ b/koala-wrapper/native/src/generated/bridges.cc @@ -1713,15 +1713,6 @@ void impl_NamedTypeSetTypeParams(KNativePointer context, KNativePointer receiver } KOALA_INTEROP_V3(NamedTypeSetTypeParams, KNativePointer, KNativePointer, KNativePointer); -KNativePointer impl_NumberLiteralStrConst(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - auto result = GetImpl()->NumberLiteralStrConst(_context, _receiver); - return new std::string(result); -} -KOALA_INTEROP_2(NumberLiteralStrConst, KNativePointer, KNativePointer, KNativePointer); - KNativePointer impl_CreateTSFunctionType(KNativePointer context, KNativePointer signature) { const auto _context = reinterpret_cast(context); diff --git a/koala-wrapper/src/generated/peers/NumberLiteral.ts b/koala-wrapper/src/generated/peers/NumberLiteral.ts index 419e7cb74..0930bbc02 100644 --- a/koala-wrapper/src/generated/peers/NumberLiteral.ts +++ b/koala-wrapper/src/generated/peers/NumberLiteral.ts @@ -36,9 +36,6 @@ export class NumberLiteral extends Literal { super(pointer) } - get str(): string { - return unpackString(global.generatedEs2panda._NumberLiteralStrConst(global.context, this.peer)) - } } export function isNumberLiteral(node: AstNode): node is NumberLiteral { return node instanceof NumberLiteral -- Gitee From f21c979cd5e30066e5db2cc70e774dd92726b221 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Mon, 21 Apr 2025 17:42:44 +0800 Subject: [PATCH 080/123] support memo type reference in memo-plugin Signed-off-by: Jiakai Shi Change-Id: I10cc96c0878bde41f9ee2c527d1d723b2f5d747a --- arkui-plugins/.gitignore | 2 + arkui-plugins/jest-test.config.js | 20 +- .../memo-plugins/function-transformer.ts | 521 ++++++++++++------ arkui-plugins/memo-plugins/memo-factory.ts | 154 ++++-- .../memo-plugins/parameter-transformer.ts | 256 +++++++-- .../memo-plugins/return-transformer.ts | 24 +- .../memo-plugins/signature-transformer.ts | 54 +- arkui-plugins/memo-plugins/utils.ts | 295 +++++++++- arkui-plugins/package.json | 3 +- .../mock/builder-lambda/simple-component.ets | 2 +- .../mock/memo/functions/argument-call.ets | 52 ++ .../mock/memo/functions/declare-and-call.ets | 35 ++ .../mock/memo/functions/inner-functions.ets | 37 ++ .../memo/functions/non-void-return-type.ets | 64 +++ .../mock/memo/functions/type-reference.ets | 40 ++ .../mock/memo/functions/void-return-type.ets | 2 +- .../demo/mock/memo/lambdas/argument-call.ets | 40 ++ .../mock/memo/lambdas/trailing-lambdas.ets | 44 ++ .../demo/mock/memo/lambdas/void-lambda.ets | 26 + .../demo/mock/memo/lambdas/with-receiver.ets | 51 ++ .../demo/mock/memo/methods/argument-call.ets | 49 ++ .../test/demo/mock/memo/methods/callable.ets | 47 ++ .../mock/memo/methods/declare-and-call.ets | 41 ++ .../demo/mock/memo/methods/internal-calls.ets | 81 +++ .../mock/memo/methods/non-void-method.ets | 67 +++ .../demo/mock/memo/methods/void-method.ets | 57 ++ .../memo/properties/class-constructor.ets | 39 ++ .../mock/memo/properties/class-properties.ets | 39 ++ .../demo/mock/memo/properties/implements.ets | 24 + .../demo/mock/memo/properties/interfaces.ets | 34 ++ .../argument-call.test.ts | 109 ++++ .../declare-and-call.test.ts | 90 +++ .../inner-functions.test.ts | 112 ++++ .../non-void-return-type.test.ts | 112 ++++ .../type-reference.test.ts | 92 ++++ .../void-return-type.test.ts | 11 +- .../lambda-literals/argument-call.test.ts | 173 ++++++ .../lambda-literals/trailing-lambdas.test.ts | 169 ++++++ .../lambda-literals/void-lambda.test.ts | 73 +++ .../lambda-literals/with-receiver.test.ts | 125 +++++ .../method-declarations/argument-call.test.ts | 145 +++++ .../method-declarations/callable.test.ts | 112 ++++ .../declare-and-call.test.ts | 83 +++ .../internal-calls.test.ts | 186 +++++++ .../non-void-method.test.ts | 119 ++++ .../method-declarations/void-method.test.ts | 151 +++++ .../class-constructor.test.ts | 101 ++++ .../class-properties.test.ts | 106 ++++ .../property-declarations/interfaces.test.ts | 107 ++++ .../builder-lambda/simple-component.test.ts | 22 +- koala-wrapper/native/src/bridges.cc | 26 + koala-wrapper/src/Es2pandaNativeModule.ts | 8 + .../src/arkts-api/factory/nodeTests.ts | 9 +- .../node-utilities/VariableDeclaration.ts | 6 +- koala-wrapper/src/arkts-api/peers/AstNode.ts | 7 +- koala-wrapper/src/arkts-api/types.ts | 16 + .../src/arkts-api/utilities/public.ts | 185 +++++-- koala-wrapper/src/arkts-api/visitor.ts | 10 + 58 files changed, 4319 insertions(+), 346 deletions(-) create mode 100644 arkui-plugins/test/demo/mock/memo/functions/argument-call.ets create mode 100644 arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets create mode 100644 arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets create mode 100644 arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets create mode 100644 arkui-plugins/test/demo/mock/memo/functions/type-reference.ets create mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets create mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets create mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets create mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets create mode 100644 arkui-plugins/test/demo/mock/memo/methods/argument-call.ets create mode 100644 arkui-plugins/test/demo/mock/memo/methods/callable.ets create mode 100644 arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets create mode 100644 arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets create mode 100644 arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets create mode 100644 arkui-plugins/test/demo/mock/memo/methods/void-method.ets create mode 100644 arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets create mode 100644 arkui-plugins/test/demo/mock/memo/properties/class-properties.ets create mode 100644 arkui-plugins/test/demo/mock/memo/properties/implements.ets create mode 100644 arkui-plugins/test/demo/mock/memo/properties/interfaces.ets create mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts create mode 100644 arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts diff --git a/arkui-plugins/.gitignore b/arkui-plugins/.gitignore index 7f8e5351e..98f9b3e90 100644 --- a/arkui-plugins/.gitignore +++ b/arkui-plugins/.gitignore @@ -3,6 +3,7 @@ node_modules/ **/*/dist/ **/*/build/ +dist/ build/ lib/ @@ -13,5 +14,6 @@ package-lock.json coverage/ **/*/generated +**/*/report test/demo/localtest/build_config.json diff --git a/arkui-plugins/jest-test.config.js b/arkui-plugins/jest-test.config.js index 4094af6dd..541b1dc39 100644 --- a/arkui-plugins/jest-test.config.js +++ b/arkui-plugins/jest-test.config.js @@ -28,7 +28,25 @@ module.exports = { testRegex: './test/ut/.+\\.test\\.ts$', moduleFileExtensions: ['ts', 'js', 'json', 'node'], coverageDirectory: './test/report', - collectCoverageFrom: ['common/**', 'memo-plugins/**', 'ui-plugins/**'], + collectCoverageFrom: [ + 'common/**', + 'memo-plugins/**', + 'ui-plugins/**' + ], + coveragePathIgnorePatterns: [ + 'common/debug.ts', + 'common/etsglobal-remover.ts', + 'common/print-visitor.ts', + 'common/plugin-context.ts', + 'memo-plugins/index.ts', + 'memo-plugins/import-transformer.ts', + 'memo-plugins/memo-transformer.ts', + 'ui-plugins/index.ts', + 'ui-plugins/printer-transformer.ts', + 'ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts', + 'ui-plugins/entry-translators/entry-transformer.ts', + 'ui-plugins/struct-translators/struct-transformer.ts' + ], verbose: true, globals: { SDK_PATH: sdkPath, diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 9c4027dd4..fa4a06bc4 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -17,112 +17,46 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { + MemoInfo, PositionalIdTracker, + ReturnTypeInfo, + buildReturnTypeInfo, castArrowFunctionExpression, - castFunctionExpression, + castIdentifier, castOverloadsToMethods, castParameters, findMemoFromTypeAnnotation, + findThisAttribute, + getDeclResolveAlias, hasMemoAnnotation, + hasMemoEntryAnnotation, hasMemoIntrinsicAnnotation, hasMemoStableAnnotation, + isDeclaredMethodWithMemoParams, + isFunctionProperty, isMemoArrowFunction, isMemoClassProperty, + isMemoDeclaredClassProperty, + isMemoDeclaredIdentifier, + isMemoDeclaredMethod, + isMemoETSParameterExpression, isMemoMethodDefinition, + isMemoProperty, isMemoTSTypeAliasDeclaration, + isMemoThisAttribute, + isMemoVariableDeclarator, isStandaloneArrowFunction, - isVoidType, + isThisAttributeAssignment, removeMemoAnnotation, } from './utils'; import { ParameterTransformer } from './parameter-transformer'; import { ReturnTransformer } from './return-transformer'; import { SignatureTransformer } from './signature-transformer'; -function mayAddLastReturn(node: arkts.BlockStatement): boolean { - return ( - node.statements.length > 0 && - !arkts.isReturnStatement(node.statements[node.statements.length - 1]) && - !arkts.isThrowStatement(node.statements[node.statements.length - 1]) - ); +interface ScopeInfo extends MemoInfo { + regardAsSameScope?: boolean; } -function updateFunctionBody( - node: arkts.BlockStatement, - parameters: arkts.ETSParameterExpression[], - returnTypeAnnotation: arkts.TypeNode | undefined, - stableThis: boolean, - hash: arkts.NumberLiteral | arkts.StringLiteral -): [ - arkts.BlockStatement, - arkts.VariableDeclaration | undefined, - arkts.ReturnStatement | arkts.BlockStatement | undefined -] { - let returnTypeAnno = - !returnTypeAnnotation || stableThis - ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) - : returnTypeAnnotation; - const scopeDeclaration = factory.createScopeDeclaration(returnTypeAnno, hash, parameters.length); - const memoParameters = parameters.map((name, id) => { - return factory.createMemoParameterDeclarator(id, name.identifier.name); - }); - const memoParametersDeclaration = memoParameters.length - ? [ - arkts.factory.createVariableDeclaration( - 0, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, - memoParameters - ), - ] - : []; - const syntheticReturnStatement = factory.createSyntheticReturnStatement(stableThis); - const isVoidValue = isVoidType(returnTypeAnno); - const unchangedCheck = factory.createIfStatementWithSyntheticReturnStatement(syntheticReturnStatement, isVoidValue); - if (node) { - return [ - arkts.factory.updateBlock(node, [ - scopeDeclaration, - ...memoParametersDeclaration, - unchangedCheck, - ...node.statements, - ...(mayAddLastReturn(node) ? [arkts.factory.createReturnStatement()] : []), - ]), - memoParametersDeclaration.length ? memoParametersDeclaration[0] : undefined, - syntheticReturnStatement, - ]; - } else { - return [ - node, - memoParametersDeclaration.length ? memoParametersDeclaration[0] : undefined, - syntheticReturnStatement, - ]; - } -} - -function updateMemoTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): arkts.TypeNode | undefined { - if (!typeAnnotation) return undefined; - if (!arkts.isTypeNode(typeAnnotation)) return undefined; - - if (typeAnnotation && arkts.isETSFunctionType(typeAnnotation)) { - return factory.updateFunctionTypeWithMemoParameters(typeAnnotation); - } else if (typeAnnotation && arkts.isETSUnionType(typeAnnotation)) { - return arkts.factory.updateUnionType( - typeAnnotation, - typeAnnotation.types.map((it) => { - if (arkts.isETSFunctionType(it)) { - return factory.updateFunctionTypeWithMemoParameters(it); - } - return it; - }) - ); - } - return typeAnnotation; -} - -type ScopeInfo = { - name?: string; - isMemo: boolean; -}; - export interface FunctionTransformerOptions extends VisitorOptions { positionalIdTracker: PositionalIdTracker; parameterTransformer: ParameterTransformer; @@ -156,26 +90,78 @@ export class FunctionTransformer extends AbstractVisitor { this.signatureTransformer.reset(); } - enter(node: arkts.AstNode) { + private enterMethod(node: arkts.MethodDefinition): void { + const name = node.name.name; + const isMemo = isMemoMethodDefinition(node); + this.scopes.push({ name, isMemo }); + } + + private enterClassPropety(node: arkts.ClassProperty): void { + const name = castIdentifier(node.key).name; + const isMemo = isMemoClassProperty(node); + this.scopes.push({ name, isMemo }); + } + + private enterStandaloneArrowFunction(node: arkts.ArrowFunctionExpression): void { + const name = undefined; + const isMemo = isMemoArrowFunction(node); + this.scopes.push({ name, isMemo }); + } + + private enterTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration): void { + const name = castIdentifier(node.id).name; + const isMemo = isMemoTSTypeAliasDeclaration(node); + this.scopes.push({ name, isMemo }); + } + + private enterVariableDeclarator(node: arkts.VariableDeclarator): void { + const name = node.name.name; + const isMemo = isMemoVariableDeclarator(node); + this.scopes.push({ name, isMemo, regardAsSameScope: !!node.initializer }); + } + + private enterTSAsExpression(node: arkts.TSAsExpression): void { + const isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); + this.scopes.push({ isMemo }); + } + + private enterFunctionProperty(node: arkts.Property): void { + const name = castIdentifier(node.key).name; + const isMemo = isMemoProperty(node, castArrowFunctionExpression(node.value)); + this.scopes.push({ name, isMemo }); + } + + private enterThisAttributeAssignment(node: arkts.AssignmentExpression): void { + const thisAttribute = findThisAttribute(node.left!)!; + const name = thisAttribute.name; + const isMemo = isMemoThisAttribute(thisAttribute, castArrowFunctionExpression(node.right)); + this.scopes.push({ name, isMemo }); + } + + enter(node: arkts.AstNode): this { if (arkts.isMethodDefinition(node)) { - const name = node.name.name; - const isMemo = isMemoMethodDefinition(node); - this.scopes.push({ name, isMemo }); + this.enterMethod(node); } if (arkts.isClassProperty(node) && !!node.key && arkts.isIdentifier(node.key)) { - const name = node.key.name; - const isMemo = isMemoClassProperty(node); - this.scopes.push({ name, isMemo }); + this.enterClassPropety(node); } if (isStandaloneArrowFunction(node)) { - const name = undefined; - const isMemo = isMemoArrowFunction(node); - this.scopes.push({ name, isMemo }); + this.enterStandaloneArrowFunction(node); } if (arkts.isTSTypeAliasDeclaration(node) && !!node.id && !!node.typeAnnotation) { - const name = node.id.name; - const isMemo = isMemoTSTypeAliasDeclaration(node); - this.scopes.push({ name, isMemo }); + this.enterTSTypeAliasDeclaration(node); + } + if (arkts.isVariableDeclarator(node)) { + this.enterVariableDeclarator(node); + } + if (arkts.isTSAsExpression(node) && !!node.expr && arkts.isArrowFunctionExpression(node.expr)) { + this.enterTSAsExpression(node); + } + if (isFunctionProperty(node)) { + this.enterFunctionProperty(node); + } + if (isThisAttributeAssignment(node) && !!node.right && arkts.isArrowFunctionExpression(node.right)) { + this.enterThisAttributeAssignment(node); } if (arkts.isClassDefinition(node)) { if (hasMemoStableAnnotation(node)) { @@ -210,13 +196,10 @@ export class FunctionTransformer extends AbstractVisitor { } checkMemoCallInMethod(decl: arkts.MethodDefinition) { - if (this.scopes[this.scopes.length - 1].isMemo == false) { - if (this.scopes[this.scopes.length - 1].name) { - console.error( - `Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${ - this.scopes[this.scopes.length - 1].name - }` - ); + const scope = this.scopes[this.scopes.length - 1]; + if (scope?.regardAsSameScope === false && scope?.isMemo === false) { + if (scope.name) { + console.error(`Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${scope.name}`); throw 'Invalid @memo usage'; } else { console.error(`Attempt to call @memo-method ${decl.name.name} from anonymous non-@memo-method`); @@ -227,7 +210,8 @@ export class FunctionTransformer extends AbstractVisitor { } checkMemoCallInFunction() { - if (this.scopes[this.scopes.length - 1]?.isMemo == false) { + const scope = this.scopes[this.scopes.length - 1]; + if (scope?.regardAsSameScope === false && scope?.isMemo == false) { console.error(`Attempt to call @memo-function`); throw 'Invalid @memo usage'; } @@ -235,39 +219,39 @@ export class FunctionTransformer extends AbstractVisitor { } updateScriptFunction(scriptFunction: arkts.ScriptFunction, name: string = ''): arkts.ScriptFunction { - const isStableThis = - this.stable > 0 && - scriptFunction.returnTypeAnnotation !== undefined && - arkts.isTSThisType(scriptFunction.returnTypeAnnotation); - const [body, memoParametersDeclaration, syntheticReturnStatement] = updateFunctionBody( - scriptFunction.body as arkts.BlockStatement, - castParameters(scriptFunction.params), - scriptFunction.returnTypeAnnotation, - isStableThis, - this.positionalIdTracker.id(name) + if (!scriptFunction.body || !arkts.isBlockStatement(scriptFunction.body)) { + return scriptFunction; + } + if (hasMemoIntrinsicAnnotation(scriptFunction) || hasMemoEntryAnnotation(scriptFunction)) { + return scriptFunction; + } + const returnType = scriptFunction.returnTypeAnnotation; + const isStableThis = this.stable > 0 && returnType !== undefined && arkts.isTSThisType(returnType); + const returnTypeInfo: ReturnTypeInfo = buildReturnTypeInfo( + returnType, + findMemoFromTypeAnnotation(returnType), + isStableThis ); + const [body, parameterIdentifiers, memoParametersDeclaration, syntheticReturnStatement] = + factory.updateFunctionBody( + scriptFunction.body, + castParameters(scriptFunction.params), + returnTypeInfo, + this.positionalIdTracker.id(name) + ); const afterParameterTransformer = this.parameterTransformer - .withParameters(scriptFunction.params as arkts.ETSParameterExpression[]) + .withParameters(parameterIdentifiers) .skip(memoParametersDeclaration) .visitor(body); const afterReturnTransformer = this.returnTransformer .skip(syntheticReturnStatement) + .registerReturnTypeInfo(returnTypeInfo) .rewriteThis(this.stable > 0) .visitor(afterParameterTransformer); - const updateScriptFunction = arkts.factory.updateScriptFunction( + const updateScriptFunction = factory.updateScriptFunctionWithMemoParameters( scriptFunction, afterReturnTransformer, - arkts.FunctionSignature.createFunctionSignature( - scriptFunction.typeParams, - [ - ...factory.createHiddenParameters(), - ...scriptFunction.params, // we handle function params with signature-transformer - ], - scriptFunction.returnTypeAnnotation, - scriptFunction.hasReceiver - ), - scriptFunction.flags, - scriptFunction.modifiers + returnTypeInfo.node ); return updateScriptFunction; } @@ -276,10 +260,11 @@ export class FunctionTransformer extends AbstractVisitor { let updateMethod: arkts.MethodDefinition; const that = this; const updateOverloads = node.overloads?.map((overload) => that.visitor(overload)) ?? undefined; - if ( - node.scriptFunction.body && - (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) - ) { + const isMemo = + hasMemoAnnotation(node.scriptFunction) || + hasMemoIntrinsicAnnotation(node.scriptFunction) || + hasMemoEntryAnnotation(node.scriptFunction); + if (isMemo && node.scriptFunction.body) { updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, @@ -308,30 +293,56 @@ export class FunctionTransformer extends AbstractVisitor { return updateMethod; } - private updateDeclaredMemoCall(node: arkts.CallExpression, decl: arkts.MethodDefinition): arkts.CallExpression { - this.checkMemoCallInMethod(decl); - const updatedArguments = node.arguments.map((it, index) => { - const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type; - if (type && arkts.isETSFunctionType(type)) { - if ( - !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) && - !hasMemoIntrinsicAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) - ) { - return it; //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) - } - if (arkts.isArrowFunctionExpression(it)) { - this.enterAnonymousScope(it.scriptFunction); - const res = this.updateScriptFunction(it.scriptFunction); - this.exitAnonymousScope(); - return arkts.factory.updateArrowFunction(it, res); - } + private updateDeclaredMethodMemoCall( + node: arkts.CallExpression, + decl: arkts.MethodDefinition, + ignoreSelf: boolean = false + ): arkts.CallExpression { + let updatedArguments: arkts.AstNode[] = node.arguments.map((it, index) => { + const param = decl.scriptFunction.params.at(index); + if (!param || !arkts.isEtsParameterExpression(param)) { + return it; + } + if (isMemoETSParameterExpression(param) && arkts.isArrowFunctionExpression(it)) { + this.enterAnonymousScope(it.scriptFunction); + const res = this.updateScriptFunction(it.scriptFunction); + this.exitAnonymousScope(); + return arkts.factory.updateArrowFunction(it, res); } return it; }); - return arkts.factory.updateCallExpression(node, node.expression, undefined, [ - ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), - ...updatedArguments, - ]); + if (!ignoreSelf) { + this.checkMemoCallInMethod(decl); + updatedArguments = [ + ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), + ...updatedArguments, + ]; + } + return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, updatedArguments); + } + + private updateDeclaredCallWithName(node: arkts.CallExpression, name: string): arkts.CallExpression { + return factory.insertHiddenArgumentsToCall(node, this.positionalIdTracker.id(name)); + } + + private updateAnonymousCallWithMemoParams(node: arkts.CallExpression): arkts.CallExpression { + let newExpression: arkts.AstNode = node.expression; + if (isStandaloneArrowFunction(node.expression)) { + newExpression = arkts.factory.updateArrowFunction( + node.expression, + this.signatureTransformer.visitor(node.expression.scriptFunction) + ); + } + const updatedArguments: arkts.AstNode[] = node.arguments.map((it) => { + if (arkts.isArrowFunctionExpression(it) && isMemoArrowFunction(it)) { + this.enterAnonymousScope(it.scriptFunction); + const res = this.updateScriptFunction(it.scriptFunction); + this.exitAnonymousScope(); + return arkts.factory.updateArrowFunction(it, res); + } + return it; + }); + return arkts.factory.updateCallExpression(node, newExpression, node.typeArguments, updatedArguments); } private updateAnonymousMemoCall( @@ -345,7 +356,7 @@ export class FunctionTransformer extends AbstractVisitor { } this.exitAnonymousScope(); if (!scope.isMemo) { - return node; + return this.updateAnonymousCallWithMemoParams(node); } this.checkMemoCallInFunction(); @@ -353,32 +364,49 @@ export class FunctionTransformer extends AbstractVisitor { const res = this.updateScriptFunction(expression.scriptFunction, expression.scriptFunction.id?.name); this.exitAnonymousScope(); + const newNode = this.updateAnonymousCallWithMemoParams(node); return arkts.factory.updateCallExpression( node, arkts.factory.updateArrowFunction(expression, res), - node.typeArguments, - [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...node.arguments] + newNode.typeArguments, + [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments] ); } + private updateCallExpressionWithNoDecl(node: arkts.CallExpression): arkts.CallExpression { + if (isStandaloneArrowFunction(node.expression)) { + return this.updateAnonymousMemoCall(node, node.expression); + } + return this.updateAnonymousCallWithMemoParams(node); + } + private updateCallExpression(node: arkts.CallExpression): arkts.CallExpression { const expr = node.expression; - const decl = arkts.getDecl(expr); - if (!decl || !arkts.isMethodDefinition(decl)) { - return node; + const decl = getDeclResolveAlias(expr); + if (!decl) { + return this.updateCallExpressionWithNoDecl(node); + } + if (arkts.isMethodDefinition(decl) && isMemoDeclaredMethod(decl)) { + return this.updateDeclaredMethodMemoCall(node, decl); + } + if (arkts.isMethodDefinition(decl) && isDeclaredMethodWithMemoParams(decl)) { + return this.updateDeclaredMethodMemoCall(node, decl, true); + } + if (arkts.isIdentifier(decl) && isMemoDeclaredIdentifier(decl)) { + return this.updateDeclaredCallWithName(node, decl.name); } if ( - (decl.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET && - findMemoFromTypeAnnotation(decl.scriptFunction.returnTypeAnnotation)) || - hasMemoAnnotation(decl.scriptFunction) || - hasMemoIntrinsicAnnotation(decl.scriptFunction) + arkts.isClassProperty(decl) && + isMemoDeclaredClassProperty(decl) && + !!decl.key && + arkts.isIdentifier(decl.key) ) { - return this.updateDeclaredMemoCall(node, decl); + return this.updateDeclaredCallWithName(node, decl.key.name); } - if (isStandaloneArrowFunction(node.expression)) { - return this.updateAnonymousMemoCall(node, node.expression); + if (arkts.isEtsParameterExpression(decl) && isMemoETSParameterExpression(decl)) { + return this.updateDeclaredCallWithName(node, decl.identifier.name); } - return node; + return this.updateCallExpressionWithNoDecl(node); } private updateClassProperty(node: arkts.ClassProperty, key: arkts.Identifier): arkts.ClassProperty { @@ -400,7 +428,7 @@ export class FunctionTransformer extends AbstractVisitor { } let typeAnnotation: arkts.TypeNode | undefined; - if (!!node.typeAnnotation && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { + if (!!node.typeAnnotation && !(typeAnnotation = factory.updateMemoTypeAnnotation(node.typeAnnotation))) { console.error(`ETSFunctionType or ETSUnionType expected for @memo-property ${key.name}`); throw 'Invalid @memo usage'; } @@ -423,11 +451,19 @@ export class FunctionTransformer extends AbstractVisitor { } this.exitAnonymousScope(); if (!scope.isMemo) { + if (!!node.typeAnnotation) { + return arkts.factory.updateTSTypeAliasDeclaration( + node, + node.id, + node.typeParams, + this.signatureTransformer.visitor(node.typeAnnotation) + ); + } return node; } let typeAnnotation: arkts.TypeNode | undefined; - if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { + if (!(typeAnnotation = factory.updateMemoTypeAnnotation(node.typeAnnotation))) { console.error(`ETSFunctionType or ETSUnionType expected for @memo-type ${node.id!.name}`); throw 'Invalid @memo usage'; } @@ -443,14 +479,142 @@ export class FunctionTransformer extends AbstractVisitor { } this.exitAnonymousScope(); if (!scope.isMemo) { - return node; + return arkts.factory.updateArrowFunction(node, this.signatureTransformer.visitor(node.scriptFunction)); } this.enterAnonymousScope(node.scriptFunction); const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); this.exitAnonymousScope(); - return arkts.factory.updateArrowFunction(node, res); + return arkts.factory.updateArrowFunction(node, this.signatureTransformer.visitor(res)); + } + + private updateVariableDeclarator(node: arkts.VariableDeclarator): arkts.VariableDeclarator { + const scope = this.scopes[this.scopes.length - 1]; + const isValidScope = !!scope && scope.name === node.name.name; + if (!isValidScope) { + return node; + } + this.exitAnonymousScope(); + if (!scope.isMemo) { + if (!!node.initializer && arkts.isArrowFunctionExpression(node.initializer)) { + return arkts.factory.updateVariableDeclarator( + node, + node.flag, + node.name, + arkts.factory.updateArrowFunction( + node.initializer, + this.signatureTransformer.visitor(node.initializer.scriptFunction) + ) + ); + } + return node; + } + + let typeAnnotation: arkts.TypeNode | undefined; + if ( + !!node.name.typeAnnotation && + !(typeAnnotation = factory.updateMemoTypeAnnotation(node.name.typeAnnotation)) + ) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-variable-type ${node.name.name}`); + throw 'Invalid @memo usage'; + } + + let initializer: arkts.AstNode | undefined = node.initializer; + if (!!initializer && arkts.isArrowFunctionExpression(initializer)) { + this.enterAnonymousScope(initializer.scriptFunction); + const res = this.updateScriptFunction(initializer.scriptFunction, initializer.scriptFunction.id?.name); + this.exitAnonymousScope(); + initializer = arkts.factory.updateArrowFunction(initializer, res); + } + + return arkts.factory.updateVariableDeclarator( + node, + node.flag, + arkts.factory.updateIdentifier(node.name, node.name.name, typeAnnotation), + initializer + ); + } + + private updateTSAsExpression( + node: arkts.TSAsExpression, + expr: arkts.ArrowFunctionExpression + ): arkts.TSAsExpression { + const scope = this.scopes[this.scopes.length - 1]; + const isValidScope = !!scope; + if (!isValidScope) { + return node; + } + this.exitAnonymousScope(); + if (!scope.isMemo) { + return node; + } + + this.enterAnonymousScope(expr.scriptFunction); + const res = this.updateScriptFunction(expr.scriptFunction, expr.scriptFunction.id?.name); + this.exitAnonymousScope(); + + let typeAnnotation: arkts.TypeNode | undefined; + if (!(typeAnnotation = factory.updateMemoTypeAnnotation(node.typeAnnotation))) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-as-type`); + throw 'Invalid @memo usage'; + } + + return arkts.factory.updateTSAsExpression( + node, + arkts.factory.updateArrowFunction(expr, res), + typeAnnotation, + node.isConst + ); + } + + private updateProperty( + node: arkts.Property, + key: arkts.Identifier, + value: arkts.ArrowFunctionExpression + ): arkts.Property { + const scope = this.scopes[this.scopes.length - 1]; + const isValidScope = !!scope && scope.name === key.name; + if (!isValidScope) { + return node; + } + this.exitAnonymousScope(); + if (!scope.isMemo) { + return node; + } + + this.enterAnonymousScope(value.scriptFunction); + const res = this.updateScriptFunction(value.scriptFunction, value.scriptFunction.id?.name); + this.exitAnonymousScope(); + + return arkts.factory.updateProperty(node, key, arkts.factory.updateArrowFunction(value, res)); + } + + private updateThisAttributeAssignment( + node: arkts.AssignmentExpression, + thisAttribute: arkts.Identifier, + right: arkts.ArrowFunctionExpression + ): arkts.AssignmentExpression { + const scope = this.scopes[this.scopes.length - 1]; + const isValidScope = !!scope && scope.name === thisAttribute.name; + if (!isValidScope) { + return node; + } + this.exitAnonymousScope(); + if (!scope.isMemo) { + return node; + } + + this.enterAnonymousScope(right.scriptFunction); + const res = this.updateScriptFunction(right.scriptFunction, right.scriptFunction.id?.name); + this.exitAnonymousScope(); + + return arkts.factory.updateAssignmentExpression( + node, + node.left!, + node.operatorType, + arkts.factory.updateArrowFunction(right, res) + ); } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { @@ -472,6 +636,19 @@ export class FunctionTransformer extends AbstractVisitor { if (isStandaloneArrowFunction(node)) { return this.updateStandaloneArrowFunction(node); } + if (arkts.isVariableDeclarator(node)) { + return this.updateVariableDeclarator(node); + } + if (arkts.isTSAsExpression(node) && node.expr && arkts.isArrowFunctionExpression(node.expr)) { + return this.updateTSAsExpression(node, node.expr); + } + if (isFunctionProperty(node)) { + return this.updateProperty(node, castIdentifier(node.key), castArrowFunctionExpression(node.value)); + } + if (isThisAttributeAssignment(node) && !!node.right && arkts.isArrowFunctionExpression(node.right)) { + const thisAttribute = findThisAttribute(node.left!)!; + return this.updateThisAttributeAssignment(node, thisAttribute, node.right); + } return node; } } diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index 35a1e92d4..c1288e7eb 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -14,7 +14,15 @@ */ import * as arkts from '@koalaui/libarkts'; -import { RuntimeNames } from './utils'; +import { + fixGensymParams, + buildeParamInfos, + isUnmemoizedInFunction, + mayAddLastReturn, + ParamInfo, + ReturnTypeInfo, + RuntimeNames, +} from './utils'; export class factory { // Importing @@ -33,9 +41,6 @@ export class factory { // TODO: Currently, import declaration can only be inserted at after-parsed stage. static createContextTypesImportDeclaration(program?: arkts.Program): void { const source: arkts.StringLiteral = arkts.factory.createStringLiteral(RuntimeNames.CONTEXT_TYPE_DEFAULT_IMPORT); - // const resolvedSource: arkts.StringLiteral = arkts.factory.create1StringLiteral( - // arkts.ImportPathManager.create().resolvePath('', source.str) - // ); const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, [factory.createContextTypeImportSpecifier(), factory.createIdTypeImportSpecifier()], @@ -77,18 +82,43 @@ export class factory { static createHiddenParameters(): arkts.ETSParameterExpression[] { return [factory.createContextParameter(), factory.createIdParameter()]; } + static createHiddenParameterIfNotAdded(params?: readonly arkts.Expression[]): readonly arkts.Expression[] { + const _params = params ?? []; + if (isUnmemoizedInFunction(_params)) { + return _params; + } + return [...factory.createHiddenParameters(), ..._params]; + } static updateFunctionTypeWithMemoParameters(type: arkts.ETSFunctionType): arkts.ETSFunctionType { return arkts.factory.updateFunctionType( type, arkts.factory.createFunctionSignature( undefined, - [...factory.createHiddenParameters(), ...type.params], + factory.createHiddenParameterIfNotAdded(type.params), type.returnType, false ), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ); } + static updateScriptFunctionWithMemoParameters( + func: arkts.ScriptFunction, + newBody?: arkts.AstNode | undefined, + returnType?: arkts.TypeNode | undefined + ): arkts.ScriptFunction { + return arkts.factory.updateScriptFunction( + func, + newBody ?? func.body, + arkts.factory.createFunctionSignature( + func.typeParams, + factory.createHiddenParameterIfNotAdded(func.params), + returnType ?? func.returnTypeAnnotation, + func.hasReceiver + ), + func.flags, + func.modifiers + ); + } // Arguments static createContextArgument(): arkts.AstNode { @@ -126,6 +156,15 @@ export class factory { ) ); } + static createMemoParameterDeclaration(parameters: string[]): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, + parameters.map((name, id) => { + return factory.createMemoParameterDeclarator(id, name); + }) + ); + } static createMemoParameterAccess(name: string): arkts.MemberExpression { return arkts.factory.createMemberExpression( factory.createMemoParameterIdentifier(name), @@ -135,40 +174,7 @@ export class factory { false ); } - static createMemoParameterAccessMemoWithScope( - name: string, - hash: arkts.NumberLiteral | arkts.StringLiteral, - passArgs?: arkts.AstNode[] - ): arkts.CallExpression { - const updatedArgs = passArgs ? passArgs : []; - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - factory.createMemoParameterIdentifier(name), - arkts.factory.createIdentifier(RuntimeNames.VALUE), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_GETTER, - false, - false - ), - undefined, - [...factory.createHiddenArguments(hash), ...updatedArgs] - ); - } - static createMemoParameterAccessMemoWithoutScope( - name: string, - hash: arkts.NumberLiteral | arkts.StringLiteral, - passArgs?: arkts.AstNode[] - ): arkts.CallExpression { - const updatedArgs = passArgs ? passArgs : []; - return arkts.factory.createCallExpression(arkts.factory.createIdentifier(name), undefined, [ - ...factory.createHiddenArguments(hash), - ...updatedArgs, - ]); - } - static createMemoParameterAccessCall( - name: string, - hash: arkts.NumberLiteral | arkts.StringLiteral, - passArgs?: arkts.AstNode[] - ): arkts.CallExpression { + static createMemoParameterAccessCall(name: string, passArgs?: arkts.AstNode[]): arkts.CallExpression { const updatedArgs = passArgs ? passArgs : []; return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -305,4 +311,74 @@ export class factory { [factory.createIdArgument(hash), factory.createLambdaWrapper(node)] ); } + + static updateFunctionBody( + node: arkts.BlockStatement, + parameters: arkts.ETSParameterExpression[], + returnTypeInfo: ReturnTypeInfo, + hash: arkts.NumberLiteral | arkts.StringLiteral + ): [ + arkts.BlockStatement, + ParamInfo[], + arkts.VariableDeclaration | undefined, + arkts.ReturnStatement | arkts.BlockStatement | undefined + ] { + const paramInfos = buildeParamInfos(parameters); + const gensymParamsCount = fixGensymParams(paramInfos, node); + const parameterNames = paramInfos.map((it) => it.ident.name); + const scopeDeclaration = factory.createScopeDeclaration(returnTypeInfo.node, hash, parameterNames.length); + const memoParametersDeclaration = parameterNames.length + ? factory.createMemoParameterDeclaration(parameterNames) + : undefined; + const syntheticReturnStatement = factory.createSyntheticReturnStatement(!!returnTypeInfo.isStableThis); + const isVoidValue = !!returnTypeInfo.isVoid; + const unchangedCheck = factory.createIfStatementWithSyntheticReturnStatement( + syntheticReturnStatement, + isVoidValue + ); + return [ + arkts.factory.updateBlock(node, [ + ...node.statements.slice(0, gensymParamsCount), + scopeDeclaration, + ...(memoParametersDeclaration ? [memoParametersDeclaration] : []), + unchangedCheck, + ...node.statements.slice(gensymParamsCount), + ...(mayAddLastReturn(node) ? [arkts.factory.createReturnStatement()] : []), + ]), + paramInfos, + memoParametersDeclaration, + syntheticReturnStatement, + ]; + } + + static updateMemoTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): arkts.TypeNode | undefined { + if (!typeAnnotation || !arkts.isTypeNode(typeAnnotation)) { + return undefined; + } + + if (arkts.isETSFunctionType(typeAnnotation)) { + return factory.updateFunctionTypeWithMemoParameters(typeAnnotation); + } else if (arkts.isETSUnionType(typeAnnotation)) { + return arkts.factory.updateUnionType( + typeAnnotation, + typeAnnotation.types.map((it) => { + if (arkts.isETSFunctionType(it)) { + return factory.updateFunctionTypeWithMemoParameters(it); + } + return it; + }) + ); + } + return typeAnnotation; + } + + static insertHiddenArgumentsToCall( + node: arkts.CallExpression, + hash: arkts.NumberLiteral | arkts.StringLiteral + ): arkts.CallExpression { + return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ + ...factory.createHiddenArguments(hash), + ...node.arguments, + ]); + } } diff --git a/arkui-plugins/memo-plugins/parameter-transformer.ts b/arkui-plugins/memo-plugins/parameter-transformer.ts index 757e45f77..d5e615e99 100644 --- a/arkui-plugins/memo-plugins/parameter-transformer.ts +++ b/arkui-plugins/memo-plugins/parameter-transformer.ts @@ -17,21 +17,37 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { - hasMemoAnnotation, - hasMemoIntrinsicAnnotation, + buildReturnTypeInfo, + castParameters, + findReturnTypeFromTypeAnnotation, + isMemoETSParameterExpression, isMemoParametersDeclaration, + isUnmemoizedInFunction, + isVoidType, + MemoInfo, + ParamInfo, PositionalIdTracker, + ReturnTypeInfo, + RuntimeNames, } from './utils'; +import { ReturnTransformer } from './return-transformer'; export interface ParameterTransformerOptions extends VisitorOptions { positionalIdTracker: PositionalIdTracker; } +interface RewriteMemoInfo extends MemoInfo { + rewritePeer: number; +} + export class ParameterTransformer extends AbstractVisitor { private rewriteIdentifiers?: Map arkts.MemberExpression | arkts.Identifier>; - private rewriteCalls?: Map arkts.CallExpression>; + private rewriteCalls?: Map arkts.CallExpression>; + private rewriteMemoInfos?: Map; + private rewriteThis?: boolean; private skipNode?: arkts.VariableDeclaration; - private readonly positionalIdTracker: PositionalIdTracker; + + private positionalIdTracker: PositionalIdTracker; constructor(options: ParameterTransformerOptions) { super(options); @@ -42,37 +58,29 @@ export class ParameterTransformer extends AbstractVisitor { super.reset(); this.rewriteIdentifiers = undefined; this.rewriteCalls = undefined; + this.rewriteMemoInfos = undefined; this.skipNode = undefined; } - withParameters(parameters: arkts.ETSParameterExpression[]): ParameterTransformer { + withThis(flag: boolean): ParameterTransformer { + this.rewriteThis = flag; + return this; + } + + withParameters(parameters: ParamInfo[]): ParameterTransformer { this.rewriteCalls = new Map( parameters - .filter((it) => it.type && (arkts.isETSFunctionType(it.type) || arkts.isETSUnionType(it.type))) + .filter( + (it) => + it.param.type && (arkts.isETSFunctionType(it.param.type) || arkts.isETSUnionType(it.param.type)) + ) .map((it) => { return [ - it.peer, - (passArgs: arkts.AstNode[]) => { - if (hasMemoAnnotation(it) || hasMemoIntrinsicAnnotation(it)) { - if (it.type && arkts.isETSFunctionType(it.type) && !it.optional) { - return factory.createMemoParameterAccessMemoWithScope( - it.identifier.name, - this.positionalIdTracker?.id(), - passArgs - ); - } else { - return factory.createMemoParameterAccessMemoWithoutScope( - it.identifier.name, - this.positionalIdTracker?.id(), - passArgs - ); - } - } - return factory.createMemoParameterAccessCall( - it.identifier.name, - this.positionalIdTracker?.id(), - passArgs - ); + it.param.identifier.name.startsWith(RuntimeNames.GENSYM) + ? it.ident.originalPeer + : it.param.originalPeer, + (passArgs: arkts.Expression[]) => { + return factory.createMemoParameterAccessCall(it.ident.name, passArgs); }, ]; }) @@ -80,12 +88,25 @@ export class ParameterTransformer extends AbstractVisitor { this.rewriteIdentifiers = new Map( parameters.map((it) => { return [ - it.peer, + it.param.identifier.name.startsWith(RuntimeNames.GENSYM) + ? it.ident.originalPeer + : it.param.originalPeer, () => { - if ((it.type && arkts.isETSFunctionType(it.type)) || it.optional) { - return arkts.factory.createIdentifier(it.identifier.name); - } - return factory.createMemoParameterAccess(it.identifier.name); + return factory.createMemoParameterAccess(it.ident.name); + }, + ]; + }) + ); + this.rewriteMemoInfos = new Map( + parameters.map((it) => { + return [ + it.param.identifier.name.startsWith(RuntimeNames.GENSYM) + ? it.ident.originalPeer + : it.param.originalPeer, + { + name: it.param.identifier.name, + rewritePeer: it.param.identifier.originalPeer, + isMemo: isMemoETSParameterExpression(it.param), }, ]; }) @@ -98,33 +119,174 @@ export class ParameterTransformer extends AbstractVisitor { return this; } + private updateArrowFunctionFromVariableDeclareInit( + initializer: arkts.ArrowFunctionExpression, + returnType: arkts.TypeNode | undefined + ): arkts.ArrowFunctionExpression { + const scriptFunction = initializer.scriptFunction; + if (!scriptFunction.body || !arkts.isBlockStatement(scriptFunction.body)) { + return initializer; + } + if (isUnmemoizedInFunction(scriptFunction.params)) { + return initializer; + } + const returnTypeInfo: ReturnTypeInfo = buildReturnTypeInfo( + returnType ?? scriptFunction.returnTypeAnnotation, + true + ); + const [body, parameterIdentifiers, memoParametersDeclaration, syntheticReturnStatement] = + factory.updateFunctionBody( + scriptFunction.body, + castParameters(scriptFunction.params), + returnTypeInfo, + this.positionalIdTracker.id() + ); + const afterParameterTransformer = new ParameterTransformer({ + positionalIdTracker: this.positionalIdTracker, + }) + .withParameters(parameterIdentifiers) + .skip(memoParametersDeclaration) + .visitor(body); + const afterReturnTransformer = new ReturnTransformer() + .skip(syntheticReturnStatement) + .registerReturnTypeInfo(returnTypeInfo) + .visitor(afterParameterTransformer); + const updateScriptFunction = factory.updateScriptFunctionWithMemoParameters( + scriptFunction, + afterReturnTransformer, + returnTypeInfo.node + ); + return arkts.factory.updateArrowFunction(initializer, updateScriptFunction); + } + + private updateVariableDeclareInit( + initializer: T | undefined, + returnType: arkts.TypeNode | undefined + ): T | undefined { + if (!initializer) { + return undefined; + } + if (arkts.isConditionalExpression(initializer)) { + return arkts.factory.updateConditionalExpression( + initializer, + initializer.test, + this.updateVariableDeclareInit(initializer.consequent, returnType), + this.updateVariableDeclareInit(initializer.alternate, returnType) + ) as unknown as T; + } + if (arkts.isTSAsExpression(initializer)) { + return arkts.factory.updateTSAsExpression( + initializer, + this.updateVariableDeclareInit(initializer.expr, returnType), + factory.updateMemoTypeAnnotation(initializer.typeAnnotation), + initializer.isConst + ) as unknown as T; + } + if (arkts.isArrowFunctionExpression(initializer)) { + return this.updateArrowFunctionFromVariableDeclareInit(initializer, returnType) as unknown as T; + } + return initializer; + } + + private updateParamReDeclare(node: arkts.VariableDeclarator, memoInfo: RewriteMemoInfo): arkts.VariableDeclarator { + const shouldUpdate: boolean = node.name.name !== memoInfo.name && memoInfo.isMemo; + if (!shouldUpdate) { + return node; + } + const decl = arkts.getPeerDecl(memoInfo.rewritePeer); + if (!decl || !arkts.isEtsParameterExpression(decl)) { + return node; + } + + let typeAnnotation: arkts.TypeNode | undefined; + if ( + !!node.name.typeAnnotation && + !(typeAnnotation = factory.updateMemoTypeAnnotation(node.name.typeAnnotation)) + ) { + console.error(`ETSFunctionType or ETSUnionType expected for @memo-variable-type ${node.name.name}`); + throw 'Invalid @memo usage'; + } + + const returnType = findReturnTypeFromTypeAnnotation(decl.type); + return arkts.factory.updateVariableDeclarator( + node, + node.flag, + arkts.factory.updateIdentifier(node.name, node.name.name, typeAnnotation), + this.updateVariableDeclareInit(node.initializer, returnType) + ); + } + + private updateVariableReDeclarationFromParam(node: arkts.VariableDeclaration): arkts.VariableDeclaration { + const that = this; + return arkts.factory.updateVariableDeclaration( + node, + node.modifiers, + node.declarationKind, + node.declarators.map((declarator) => { + if (that.rewriteMemoInfos?.has(declarator.name.originalPeer)) { + const memoInfo = that.rewriteMemoInfos.get(declarator.name.originalPeer)!; + return that.updateParamReDeclare(declarator, memoInfo); + } + if (!!declarator.initializer && arkts.isIdentifier(declarator.initializer)) { + const decl = arkts.getPeerDecl(declarator.initializer.originalPeer); + if (decl && that.rewriteIdentifiers?.has(decl.originalPeer)) { + return arkts.factory.updateVariableDeclarator( + declarator, + declarator.flag, + declarator.name, + that.rewriteIdentifiers.get(decl.originalPeer)!() + ); + } + } + return declarator; + }) + ); + } + + private updateCallReDeclare( + node: arkts.CallExpression, + oriName: arkts.Identifier, + memoInfo: RewriteMemoInfo + ): arkts.CallExpression { + const shouldUpdate: boolean = oriName.name !== memoInfo.name && memoInfo.isMemo; + if (!shouldUpdate) { + return node; + } + return factory.insertHiddenArgumentsToCall(node, this.positionalIdTracker.id(oriName.name)); + } + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { // TODO: temporary checking skip nodes by comparison with expected skip nodes // Should be fixed when update procedure implemented properly - if (!beforeChildren) { - return beforeChildren; - } if (/* beforeChildren === this.skipNode */ isMemoParametersDeclaration(beforeChildren)) { return beforeChildren; } - if (arkts.isCallExpression(beforeChildren)) { - if (arkts.isIdentifier(beforeChildren.expression)) { - const decl = arkts.getDecl(beforeChildren.expression); - if (decl && arkts.isEtsParameterExpression(decl) && this.rewriteCalls?.has(decl.peer)) { - return this.rewriteCalls.get(decl.peer)!(beforeChildren.arguments.map((it) => this.visitor(it))); + if (arkts.isVariableDeclaration(beforeChildren)) { + return this.updateVariableReDeclarationFromParam(beforeChildren); + } + if (arkts.isCallExpression(beforeChildren) && arkts.isIdentifier(beforeChildren.expression)) { + const decl = arkts.getPeerDecl(beforeChildren.expression.originalPeer); + if (decl && this.rewriteCalls?.has(decl.originalPeer)) { + const updateCall = this.rewriteCalls.get(decl.originalPeer)!( + beforeChildren.arguments.map((it) => this.visitor(it) as arkts.Expression) + ); + if (this.rewriteMemoInfos?.has(decl.originalPeer)) { + const memoInfo = this.rewriteMemoInfos.get(decl.originalPeer)!; + return this.updateCallReDeclare(updateCall, beforeChildren.expression, memoInfo); } + return updateCall; } } const node = this.visitEachChild(beforeChildren); if (arkts.isIdentifier(node)) { - const decl = arkts.getDecl(node); - if (decl && arkts.isEtsParameterExpression(decl) && this.rewriteIdentifiers?.has(decl.peer)) { - const res = this.rewriteIdentifiers.get(decl.peer)!(); - if (arkts.isMemberExpression(res)) { - return res; - } + const decl = arkts.getPeerDecl(node.originalPeer); + if (decl && this.rewriteIdentifiers?.has(decl.originalPeer)) { + return this.rewriteIdentifiers.get(decl.originalPeer)!(); } } + if (arkts.isThisExpression(node) && this.rewriteThis) { + return factory.createMemoParameterAccess(RuntimeNames.THIS); + } return node; } } diff --git a/arkui-plugins/memo-plugins/return-transformer.ts b/arkui-plugins/memo-plugins/return-transformer.ts index 563d55621..c2c0fac2e 100644 --- a/arkui-plugins/memo-plugins/return-transformer.ts +++ b/arkui-plugins/memo-plugins/return-transformer.ts @@ -16,16 +16,18 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; import { AbstractVisitor } from '../common/abstract-visitor'; -import { isSyntheticReturnStatement } from './utils'; +import { isSyntheticReturnStatement, ReturnTypeInfo } from './utils'; export class ReturnTransformer extends AbstractVisitor { private skipNode?: arkts.ReturnStatement | arkts.BlockStatement; private stableThis: boolean = false; + private returnTypeInfo: ReturnTypeInfo | undefined; reset() { super.reset(); this.skipNode = undefined; this.stableThis = false; + this.returnTypeInfo = undefined; } skip(syntheticReturnStatement?: arkts.ReturnStatement | arkts.BlockStatement): ReturnTransformer { @@ -38,6 +40,11 @@ export class ReturnTransformer extends AbstractVisitor { return this; } + registerReturnTypeInfo(returnTypeInfo: ReturnTypeInfo): ReturnTransformer { + this.returnTypeInfo = returnTypeInfo; + return this; + } + visitor(beforeChildren: arkts.AstNode): arkts.AstNode { // TODO: temporary checking skip nodes by comparison with expected skip nodes // Should be fixed when update procedure implemented properly @@ -58,7 +65,20 @@ export class ReturnTransformer extends AbstractVisitor { node, ]); } - return arkts.factory.updateReturnStatement(node, factory.createRecacheCall(node.argument)); + + let argument = node.argument; + if ( + !!this.returnTypeInfo?.node && + this.returnTypeInfo.isMemo && + arkts.isArrowFunctionExpression(argument) + ) { + argument = arkts.factory.updateArrowFunction( + argument, + factory.updateScriptFunctionWithMemoParameters(argument.scriptFunction) + ); + } + + return arkts.factory.updateReturnStatement(node, factory.createRecacheCall(argument)); } return node; } diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index 985d57d5c..610114613 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -18,6 +18,22 @@ import { factory } from './memo-factory'; import { hasMemoAnnotation, hasMemoIntrinsicAnnotation } from './utils'; import { AbstractVisitor } from '../common/abstract-visitor'; +function isScriptFunctionFromGetter(node: arkts.ScriptFunction): boolean { + return ( + arkts.isFunctionExpression(node.parent) && + arkts.isMethodDefinition(node.parent.parent) && + node.parent.parent.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET + ); +} + +function isScriptFunctionFromSetter(node: arkts.ScriptFunction): boolean { + return ( + arkts.isFunctionExpression(node.parent) && + arkts.isMethodDefinition(node.parent.parent) && + node.parent.parent.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET + ); +} + export class SignatureTransformer extends AbstractVisitor { public modified = false; @@ -32,17 +48,23 @@ export class SignatureTransformer extends AbstractVisitor { if (memo) { this.modified = true; } + const isFromGetter = isScriptFunctionFromGetter(node); + const isFromSetter = isScriptFunctionFromSetter(node); + const shouldAddMemoParam = memo && !isFromGetter && !isFromSetter; + const shouldApplyMemoToParamExpr = memo && isFromSetter; + const shouldApplyMemoToReturnType = memo && isFromGetter; + const newParams = node.params.map((it) => this.visitor(it, shouldApplyMemoToParamExpr)); return arkts.factory.updateScriptFunction( node, node.body, arkts.factory.createFunctionSignature( node.typeParams, - [...(memo ? factory.createHiddenParameters() : []), ...node.params.map((it) => this.visitor(it))], + shouldAddMemoParam ? factory.createHiddenParameterIfNotAdded(newParams) : newParams, node.returnTypeAnnotation - ? this.visitor(node.returnTypeAnnotation) + ? this.visitor(node.returnTypeAnnotation, shouldApplyMemoToReturnType) : memo - ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) - : undefined, + ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + : undefined, node.hasReceiver ), node.flags, @@ -50,7 +72,7 @@ export class SignatureTransformer extends AbstractVisitor { ) as any as T; } if (arkts.isEtsParameterExpression(node)) { - const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); + const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo; if (!node.type) { if (memo) { console.error(`@memo parameter ${node.identifier.name} without type annotatation`); @@ -66,11 +88,12 @@ export class SignatureTransformer extends AbstractVisitor { if (memo) { this.modified = true; } + const newParams = node.params.map((it) => this.visitor(it)); return arkts.factory.updateFunctionType( node, arkts.factory.createFunctionSignature( undefined, - [...(memo ? factory.createHiddenParameters() : []), ...node.params.map((it) => this.visitor(it))], + memo ? factory.createHiddenParameterIfNotAdded(newParams) : newParams, this.visitor(node.returnType!), false ), @@ -86,7 +109,26 @@ export class SignatureTransformer extends AbstractVisitor { if (arkts.isETSUndefinedType(node)) { return node as any as T; } + if (arkts.isETSTypeReference(node) && applyMemo) { + if (!node.part || !node.part.name) { + console.error(`@memo parameter has no type reference`); + throw 'Invalid @memo usage'; + } + const expr = node.part.name; + const decl = arkts.getDecl(expr); + if (!decl || !arkts.isTSTypeAliasDeclaration(decl)) { + console.error(`@memo parameter's type has not been declared`); + throw 'Invalid @memo usage'; + } + const memoDecl = hasMemoAnnotation(decl) || hasMemoIntrinsicAnnotation(decl); + if (memoDecl) { + return node as any as T; + } + console.error(`@memo parameter type reference has no @memo type declaration`); + throw 'Invalid @memo usage'; + } if (applyMemo) { + console.error(`@memo parameter's signature has invalid type`); throw 'Invalid @memo usage'; } return node; diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index cae4fa891..e013100ac 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -21,12 +21,14 @@ export enum RuntimeNames { __CONTEXT = '__context', __ID = '__id', ANNOTATION = 'memo', + ANNOTATION_ENTRY = 'memo_entry', ANNOTATION_INTRINSIC = 'memo_intrinsic', ANNOTATION_STABLE = 'memo_stable', COMPUTE = 'compute', CONTEXT = '__memo_context', CONTEXT_TYPE = '__memo_context_type', CONTEXT_TYPE_DEFAULT_IMPORT = '@ohos.arkui.StateManagement.runtime', + GENSYM = 'gensym%%_', ID = '__memo_id', ID_TYPE = '__memo_id_type', INTERNAL_PARAMETER_STATE = 'param', @@ -36,9 +38,27 @@ export enum RuntimeNames { INTERNAL_VALUE_OK = 'unchanged', PARAMETER = '__memo_parameter', SCOPE = '__memo_scope', + THIS = 'this', VALUE = 'value', } +export interface ReturnTypeInfo { + node: arkts.TypeNode | undefined; + isMemo?: boolean; + isVoid?: boolean; + isStableThis?: boolean; +} + +export interface ParamInfo { + ident: arkts.Identifier; + param: arkts.ETSParameterExpression; +} + +export interface MemoInfo { + name?: string; + isMemo: boolean; +} + function baseName(path: string): string { return path.replace(/^.*\/(.*)$/, '$1'); } @@ -88,7 +108,9 @@ export type MemoAstNode = | arkts.ClassProperty | arkts.TSTypeAliasDeclaration | arkts.ETSFunctionType - | arkts.ArrowFunctionExpression; + | arkts.ArrowFunctionExpression + | arkts.ETSTypeReference + | arkts.VariableDeclaration; export function hasMemoAnnotation(node: T): boolean { return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION)); @@ -98,6 +120,10 @@ export function hasMemoIntrinsicAnnotation(node: T): bool return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC)); } +export function hasMemoEntryAnnotation(node: T): boolean { + return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_ENTRY)); +} + export function hasMemoStableAnnotation(node: arkts.ClassDefinition): boolean { return node.annotations.some( (it) => it.expr !== undefined && arkts.isIdentifier(it.expr) && it.expr.name === RuntimeNames.ANNOTATION_STABLE @@ -109,6 +135,7 @@ export function removeMemoAnnotation(node: T): T { (it) => !isMemoAnnotation(it, RuntimeNames.ANNOTATION) && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC) && + !isMemoAnnotation(it, RuntimeNames.ANNOTATION_ENTRY) && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) ); if (arkts.isEtsParameterExpression(node)) { @@ -216,6 +243,15 @@ export function castArrowFunctionExpression(value: arkts.Expression | undefined) return value as unknown as arkts.ArrowFunctionExpression; } +/** + * es2panda API is weird here + * + * @deprecated + */ +export function castIdentifier(value: arkts.AstNode | undefined): arkts.Identifier { + return value as unknown as arkts.Identifier; +} + /** * es2panda API is weird here * @@ -231,7 +267,60 @@ export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.Ar // handling anonymous arrow function call if (arkts.isCallExpression(node.parent) && node.parent.expression.peer === node.peer) return true; - return !arkts.isClassProperty(node.parent) && !(arkts.isCallExpression(node.parent) && node.parent.expression); + return ( + !arkts.isVariableDeclarator(node.parent) && + !arkts.isClassProperty(node.parent) && + !(arkts.isCallExpression(node.parent) && node.parent.expression) + ); +} + +export function isFunctionProperty(node: arkts.AstNode): node is arkts.Property { + return ( + arkts.isProperty(node) && + !!node.key && + arkts.isIdentifier(node.key) && + !!node.value && + arkts.isArrowFunctionExpression(node.value) + ); +} + +export function isThisAttributeAssignment(node: arkts.AstNode): node is arkts.AssignmentExpression { + if (!arkts.isAssignmentExpression(node)) { + return false; + } + if (!node.left || !node.right) { + return false; + } + const isAssignOperator = node.operatorType === arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION; + const isThisAttribute = + arkts.isMemberExpression(node.left) && + arkts.isThisExpression(node.left.object) && + arkts.isIdentifier(node.left.property); + return isAssignOperator && isThisAttribute; +} + +export function findThisAttribute(node: arkts.AstNode): arkts.Identifier | undefined { + if (!arkts.isMemberExpression(node) || !arkts.isIdentifier(node.property)) { + return undefined; + } + return node.property; +} + +export function isMemoThisAttribute(node: arkts.Identifier, value: arkts.ArrowFunctionExpression): boolean { + let isMemo: boolean = isMemoArrowFunction(value); + if (isMemo) { + return true; + } + const decl: arkts.AstNode | undefined = getDeclResolveAlias(node); + if (!decl) { + return false; + } + if (arkts.isClassProperty(decl)) { + isMemo ||= isMemoClassProperty(decl); + } else if (arkts.isMethodDefinition(decl)) { + isMemo ||= isMemoDeclaredMethod(decl); + } + return isMemo; } export function isMemoClassProperty(node: arkts.ClassProperty): boolean { @@ -246,7 +335,11 @@ export function isMemoClassProperty(node: arkts.ClassProperty): boolean { } export function isMemoMethodDefinition(node: arkts.MethodDefinition): boolean { - return hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction); + return ( + hasMemoAnnotation(node.scriptFunction) || + hasMemoIntrinsicAnnotation(node.scriptFunction) || + hasMemoEntryAnnotation(node.scriptFunction) + ); } export function isMemoArrowFunction(node: arkts.ArrowFunctionExpression): boolean { @@ -259,11 +352,105 @@ export function isMemoTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration) return isMemo; } -export function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | undefined): boolean { +export function isMemoETSParameterExpression(param: arkts.ETSParameterExpression): boolean { + const type = param.identifier.typeAnnotation; + if (!type) { + return false; + } + let isMemo: boolean = hasMemoAnnotation(param) || hasMemoIntrinsicAnnotation(param); + isMemo ||= findMemoFromTypeAnnotation(type); + let decl: arkts.AstNode | undefined; + if ( + arkts.isETSTypeReference(type) && + !!type.part && + !!type.part.name && + !!(decl = getDeclResolveAlias(type.part.name)) + ) { + if (arkts.isTSTypeAliasDeclaration(decl)) { + isMemo ||= hasMemoAnnotation(decl) || hasMemoIntrinsicAnnotation(decl); + isMemo ||= findMemoFromTypeAnnotation(decl.typeAnnotation); + return isMemo; + } + } + return isMemo; +} + +export function isMemoVariableDeclaration(node: arkts.VariableDeclaration): boolean { + return hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); +} + +export function isMemoVariableDeclarator(node: arkts.VariableDeclarator): boolean { + let isMemo: boolean = false; + if (!!node.name.typeAnnotation) { + isMemo ||= findMemoFromTypeAnnotation(node.name.typeAnnotation); + } + if (!!node.initializer && arkts.isArrowFunctionExpression(node.initializer)) { + isMemo ||= isMemoArrowFunction(node.initializer); + } + if (arkts.isVariableDeclaration(node.parent)) { + isMemo ||= isMemoVariableDeclaration(node.parent); + } + return isMemo; +} + +export function isMemoProperty(node: arkts.Property, value: arkts.ArrowFunctionExpression): boolean { + let isMemo: boolean = isMemoArrowFunction(value); + if (isMemo) { + return true; + } + let decl: arkts.AstNode | undefined; + if (!node.key || !(decl = getDeclResolveAlias(node.key))) { + return false; + } + if (arkts.isMethodDefinition(decl)) { + isMemo ||= isMemoDeclaredMethod(decl); + } + return isMemo; +} + +export function isMemoDeclaredMethod(decl: arkts.MethodDefinition): boolean { + if ( + decl.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET && + findMemoFromTypeAnnotation(decl.scriptFunction.returnTypeAnnotation) + ) { + return true; + } + return isMemoMethodDefinition(decl); +} + +export function isDeclaredMethodWithMemoParams(decl: arkts.MethodDefinition): boolean { + if (decl.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET) { + return false; + } + return decl.scriptFunction.params.some((param) => { + return arkts.isEtsParameterExpression(param) && isMemoETSParameterExpression(param); + }); +} + +export function isMemoDeclaredIdentifier(decl: arkts.Identifier): boolean { + if (findMemoFromTypeAnnotation(decl.typeAnnotation)) { + return true; + } + if (arkts.isVariableDeclarator(decl.parent)) { + return isMemoVariableDeclarator(decl.parent); + } + return false; +} + +export function isMemoDeclaredClassProperty(decl: arkts.ClassProperty): boolean { + return isMemoClassProperty(decl); +} + +export function findMemoFromTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): boolean { if (!typeAnnotation) { return false; } - if (arkts.isETSFunctionType(typeAnnotation)) { + if (arkts.isETSTypeReference(typeAnnotation) && !!typeAnnotation.part && !!typeAnnotation.part.name) { + let decl: arkts.AstNode | undefined = arkts.getDecl(typeAnnotation.part.name); + if (!!decl && arkts.isTSTypeAliasDeclaration(decl)) { + return hasMemoAnnotation(decl) || hasMemoIntrinsicAnnotation(decl); + } + } else if (arkts.isETSFunctionType(typeAnnotation)) { return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation); } else if (arkts.isETSUnionType(typeAnnotation)) { return typeAnnotation.types.some( @@ -272,3 +459,101 @@ export function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | unde } return false; } + +export function findReturnTypeFromTypeAnnotation( + typeAnnotation: arkts.AstNode | undefined +): arkts.TypeNode | undefined { + if (!typeAnnotation) { + return undefined; + } + if (arkts.isETSTypeReference(typeAnnotation) && !!typeAnnotation.part && !!typeAnnotation.part.name) { + let decl: arkts.AstNode | undefined = arkts.getDecl(typeAnnotation.part.name); + if (!!decl && arkts.isTSTypeAliasDeclaration(decl)) { + return findReturnTypeFromTypeAnnotation(decl.typeAnnotation); + } + return undefined; + } + if (arkts.isETSFunctionType(typeAnnotation)) { + return typeAnnotation.returnType; + } + if (arkts.isETSUnionType(typeAnnotation)) { + return typeAnnotation.types.find((type) => arkts.isETSFunctionType(type))?.returnType; + } + return undefined; +} + +export function getDeclResolveAlias(node: arkts.AstNode): arkts.AstNode | undefined { + const decl = arkts.getDecl(node); + if (!!decl && arkts.isIdentifier(decl) && arkts.isVariableDeclarator(decl.parent)) { + if (!!decl.parent.initializer && arkts.isIdentifier(decl.parent.initializer)) { + return getDeclResolveAlias(decl.parent.initializer); + } + if (!!decl.parent.initializer && arkts.isMemberExpression(decl.parent.initializer)) { + return getDeclResolveAlias(decl.parent.initializer.property); + } + } + return decl; +} + +export function mayAddLastReturn(node: arkts.BlockStatement): boolean { + return ( + node.statements.length === 0 || + (!arkts.isReturnStatement(node.statements[node.statements.length - 1]) && + !arkts.isThrowStatement(node.statements[node.statements.length - 1])) + ); +} + +export function fixGensymParams(params: ParamInfo[], body: arkts.BlockStatement): number { + let gensymParamsCount = 0; + for (let i = 0; i < params.length; i++) { + if (params[i].ident.name.startsWith(RuntimeNames.GENSYM)) { + if (gensymParamsCount >= body.statements.length) { + throw new Error(`Expected ${params[i].ident.name} replacement to original parameter`); + } + const declaration = body.statements[gensymParamsCount]; + if (!arkts.isVariableDeclaration(declaration)) { + throw new Error(`Expected ${params[i].ident.name} replacement to original parameter`); + } + if (!arkts.isIdentifier(declaration.declarators[0].name)) { + throw new Error(`Expected ${params[i].ident.name} replacement to original parameter`); + } + params[i].ident = declaration.declarators[0].name; + gensymParamsCount++; + } + } + return gensymParamsCount; +} + +export function isUnmemoizedInFunction(params?: readonly arkts.Expression[]): boolean { + const _params = params ?? []; + const first = _params.at(0); + const isContextAdded = + !!first && arkts.isEtsParameterExpression(first) && first.identifier.name === RuntimeNames.CONTEXT; + const second = _params.at(1); + const isIdAdded = !!second && arkts.isEtsParameterExpression(second) && second.identifier.name === RuntimeNames.ID; + return isContextAdded && isIdAdded; +} + +export function buildReturnTypeInfo( + returnType: arkts.TypeNode | undefined, + isMemo?: boolean, + isStableThis?: boolean +): ReturnTypeInfo { + const newReturnType = !!returnType + ? returnType.clone() + : arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); + return { + node: newReturnType, + isMemo, + isVoid: isVoidType(newReturnType), + isStableThis, + }; +} + +export function buildeParamInfos(parameters: readonly arkts.ETSParameterExpression[]): ParamInfo[] { + return [ + ...parameters.map((it) => { + return { ident: it.identifier, param: it }; + }), + ]; +} diff --git a/arkui-plugins/package.json b/arkui-plugins/package.json index b82e4b40f..0267fb00d 100644 --- a/arkui-plugins/package.json +++ b/arkui-plugins/package.json @@ -10,8 +10,9 @@ "local:install": "chmod 777 ./npm_preinstall.sh && ./npm_preinstall.sh --init", "compile:plugins": "./node_modules/.bin/babel . --out-dir lib --extensions .ts", "compile:clean": "rm -rf lib", + "clean:test": "rm -rf dist && rm -rf coverage", "prepare:test": "cp -rf $INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/koala-wrapper/build/native/ ../koala-wrapper/build/", - "test": "npm run prepare:test && LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib jest --config ./jest-test.config.js --silent", + "test": "npm run clean:test && npm run prepare:test && LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib jest --coverage --logHeapUsage --config ./jest-test.config.js --silent", "compile": "npm run compile:clean && npm run compile:plugins && cp -rf ./lib $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/" }, "devDependencies": { diff --git a/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets b/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets index 86801284d..4f0f3b5cf 100644 --- a/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets +++ b/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets @@ -14,7 +14,7 @@ */ import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" -import { Column, ColumnAttribute } from "@ohos.arkui.component" +import { Column, UIColumnAttribute } from "arkui.component.column" class MyStateSample { @memo build() { diff --git a/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets b/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets new file mode 100644 index 000000000..54263a552 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +@memo function memo_arg_call( + arg1: number, + arg2: (x: number) => number, + @memo arg3: (x: number) => number, + arg4?: (x: number) => number, + @memo arg5?: (x: number) => number, +) { + arg2(arg1) + arg3(arg1) + arg4?.(arg1) + arg5?.(arg1) +} + +@memo +function memo_arg_call_with_lowering( + arg1: number, + arg4?: (x: number) => number, + @memo arg5?: (x: number) => number, +) { + {let gensym___1 = arg4; + ((gensym___1 == null) ? undefined : gensym___1(arg1))}; + {let gensym___2 = arg5; + ((gensym___2 == null) ? undefined : gensym___2(arg1))}; +} + +@memo +function args_with_default_values( + arg1: int = 10, + @memo arg2: () => int = () => { return 20 }, + arg3: int = arg1, + arg4?: int +): void { + console.log(arg1, arg2, arg3, arg4) + console.log(arg2()) +} diff --git a/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets b/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets new file mode 100644 index 000000000..ac8324d22 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +@memo +declare function funcA(): void; + +class A { + @memo foo() { + funcA(); + } +} + +@memo +function funcB(): void { + funcA(); +} + +@memo +() => { + funcA(); +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets b/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets new file mode 100644 index 000000000..313164b28 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +@memo +function foo() { } + +@memo +function bar() { + const qux = @memo () => { + foo(); + } + + const other = () => {} +} + +class A { + @memo goo() { + let func = () => {}; + let func2 = @memo () => { + foo(); + } + } +} diff --git a/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets b/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets new file mode 100644 index 000000000..cc0f993ec --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +@memo +function funcNum(): number { + return 1; +} + +@memo +function funcStr(): string { + return "1"; +} + +@memo +function funcBool(): boolean { + return false; +} + +interface A { + str: string; +} + +@memo +function funcA(): A { + return { str: "1" }; +} + +type B = (str: string) => void; + +@memo +function funcB(): B { + return (str: string) => {}; +} + +class C { + str: string; + constructor(str: string) { + this.str = str; + } +} + +@memo +function funcC(): C { + return new C("1"); +} + +@memo +function funcD(): () => void { + return () => {}; +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets b/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets new file mode 100644 index 000000000..be715df95 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +@memo type ItemBuilder = (item: Item) => void; + +interface Item { + item: T; +} + +interface Attribute { + @memo each(@memo itemGenerator: ItemBuilder): Attribute; +} + +@memo +export declare function A(): Attribute + +@memo +function func(): ItemBuilder { + return (item: Item): void => {}; +} + +class B { + @memo build() { + A().each((ri: Item) => {}) + } +} diff --git a/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets b/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets index 7ac6d38e6..840c84aaf 100644 --- a/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets +++ b/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo } from "@ohos.arkui.stateManagement" +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" @memo function func(): void { diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets b/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets new file mode 100644 index 000000000..def28807a --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +(arg: (()=>void)) => {}(() => {}); + +(arg: @memo (()=>void)) => {}(@memo () => {}); + +(arg: @memo (()=>void) = () => {}) => {}(@memo () => {}); + +@memo +() => { + (@memo (arg: @memo (()=>void) = () => {}) => {})(@memo () => {}); +} + +@memo +() => { + let goo = @memo (name: string = "old") => {} + + goo(); +} + +() => { + let foo = (arg: @memo (()=>void) = () => {}) => {} + + foo(@memo () => {}); +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets b/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets new file mode 100644 index 000000000..08d252f58 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +class A { + @memo foo(p?: ()=>void): void {} + + goo(@memo p?: ()=>void): void {} + + @memo koo(@memo p?: ()=>void): void {} +} + +@memo +function bar(f?: ()=>void): void {} + +function par(f?: @memo ()=>void): void {} + +@memo +function kar(@memo f?: ()=>void): void {} + +@memo +() => { + let a = new A(); + a.foo() { console.log(); } + a.goo() { console.log(); } + a.koo() { console.log(); } + + bar() { console.log(); } + par() { console.log(); } + kar() { console.log(); } +} diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets b/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets new file mode 100644 index 000000000..fb757d8b6 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +@memo +(): void => { + return; +} + +@memo +(arg?: () => string): void => { + return; +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets b/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets new file mode 100644 index 000000000..b54c9c6c2 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +class Person { + constructor() {} +} + +function fullName(this: Person, @memo arg?: () => void): void { + return; +} + +class A {} + +type F1 = (this: A, @memo arg?: () => void) => void; +type F2 = (a: A, @memo arg?: () => void) => void; + +function foo(this: A, @memo arg?: () => void): void {} +function goo(a: A, @memo arg?: () => void): void {} + +@memo +() => { + let x = new Person(); + x.fullName(() => {}); + + let f1: F1 = foo; + f1 = goo; + + let f2: F2 = goo; + f2 = foo; + f1 = f2; + + let a = new A(); + a.f1(() => {}); + f1(a, () => {}); + + f2(a, () => {}); +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets b/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets new file mode 100644 index 000000000..5f799140f --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +class Test { + @memo lambda_arg(@memo arg: () => void) { + + } + + @memo lambda_arg_with_arg(@memo arg: (value: string) => string) { + + } + + @memo memo_content(@memo content: () => void) { + content() + } + + @memo compute_test( + @memo arg1: (() => void) | undefined, + arg2: (() => void) | undefined, + content: (() => void) | undefined + ): void { + + } +} + +class Use { + @memo test() { + const test = new Test() + + test.lambda_arg((): void => {}) + test.lambda_arg_with_arg((value: string): string => value) + + test.compute_test(() => {}, () => {}, () => {}) + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/methods/callable.ets b/arkui-plugins/test/demo/mock/memo/methods/callable.ets new file mode 100644 index 000000000..2f4e2a401 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/methods/callable.ets @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +class A { + @memo + static $_invoke(): void {} +} + +class B { + static $_invoke(@memo p?: () => void): void {} +} + +class C { + @memo + static $_instantiate(factory: () => C): C { + return factory(); + } +} + +class D { + static $_instantiate(factory: () => D, @memo content?: () => void): D { + return factory(); + } +} + +@memo +() => { + A(); + B(() => {}); + + let x: C | D = C(); + x = D(); +} diff --git a/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets b/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets new file mode 100644 index 000000000..e28c85361 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +declare abstract class A { + @memo + x(): void; + + test_signature( + @memo arg1: () => void, + @memo arg2: (() => void) | undefined, + @memo arg3: ((() => void) | undefined) | ((() => int) | undefined), + @memo x: (y: (z: @memo () => void) => void) => void, + ): @memo () => void; +} + +class AA extends A { + @memo x(): void {} +} + +@memo +() => { + new AA().x(); + + const a: A = new AA(); + a.x(); +} + diff --git a/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets b/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets new file mode 100644 index 000000000..7ef4cdb0e --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +export declare function __context(): __memo_context_type +export declare function __id(): __memo_id_type +type MemoType = @memo () => void + +class Test { + @memo void_method(): void { + } + + @memo internal_call() { + this.void_method() + } + + @memo method_with_internals() { + __context() + __id() + } + + memo_lambda() { + @memo () => { + + } + } + + @memo memo_variables() { + @memo const f = (): number => { + return 123 + }, g = (x: number): number => { + return 123 + x + } + + const h = @memo (): number => { + return 1 + } + + f() + g(1) + h() + } + + @memo args_with_default_values( + arg1: int = 10, + arg2: () => int = () => { return 20 }, + arg3: int = arg1, + arg4?: int + ): void { + console.log(arg1, arg2, arg3, arg4) + console.log(arg2()) + } + + @memo optional_args( + arg1?: int, + arg2?: () => int + ) { + console.log(arg1) + console.log(arg2) + console.log(arg2?.()) + } + + @memo type_alias( + arg: MemoType + ) { + arg() + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets b/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets new file mode 100644 index 000000000..06df30297 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +@Retention({policy:"SOURCE"}) @interface memo_intrinsic {} +@Retention({policy:"SOURCE"}) @interface memo_entry {} + +export declare function __context(): __memo_context_type +export declare function __id(): __memo_id_type + +class Test { + @memo void_method(): void { + } + + @memo string_method_with_return(arg: string): string { + return arg + } + + @memo method_with_type_parameter(arg: T): T { + return arg + } + + @memo_intrinsic intrinsic_method(): int { + return 0 + } + + @memo_intrinsic intrinsic_method_with_this(): int { + this.void_method() + return 0 + } + + @memo_entry memoEntry(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo entry: () => R): R { + const getContext = () => { + return __context() + } + const getId = () => { + return __id() + } + { + const __memo_context = getContext() + const __memo_id = getId() + return entry() + } + } +} + +class Use { + @memo test() { + const test = new Test() + + test.string_method_with_return("a string") + test.method_with_type_parameter("I'm string") + } +} diff --git a/arkui-plugins/test/demo/mock/memo/methods/void-method.ets b/arkui-plugins/test/demo/mock/memo/methods/void-method.ets new file mode 100644 index 000000000..ed3339dd1 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/methods/void-method.ets @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +class A { + x: int + y: int +} + +class Test { + @memo void_method(): void { + } + + @memo a_method_with_implicit_return_type() { + } + + @memo void_method_with_arg(arg: string) { + } + + @memo void_method_with_return(arg: string) { + return + } + + @memo static static_method_with_type_parameter(arg: T): void { + return + } + + @memo obj_arg(arg: A) { + + } +} + +class Use { + @memo test() { + const test = new Test() + + test.void_method() + test.void_method_with_arg("an arg") + test.void_method_with_return("a value") + Test.static_method_with_type_parameter("I'm static") + + test.obj_arg({ x: 1, y: 2 }) + } +} diff --git a/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets b/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets new file mode 100644 index 000000000..725d2702b --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +interface A { + @memo a: () => void +} + +class AA { + + @memo a: (() => void) | undefined + + constructor(arg?: A) { + this.a = arg?.a; + } + + @memo + build() { + this.a?.(); + } +} + +@memo +() => { + let a = new AA({ a: () => {} }) ; +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets b/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets new file mode 100644 index 000000000..9fe1e5dc4 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +class A { + arg: () => void + @memo memo_arg: () => void + @memo memo_optional_arg?: () => void + @memo memo_union_arg: (() => void) | undefined = () => {} + + arg_memo_type: @memo () => void + + constructor() { + this.arg = () => {}; + this.memo_arg = () => {}; + this.arg_memo_type = () => {}; + } + + @memo + build() { + this.arg(); + this.memo_arg(); + this.arg_memo_type(); + } + +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/properties/implements.ets b/arkui-plugins/test/demo/mock/memo/properties/implements.ets new file mode 100644 index 000000000..ad61b2a7a --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/properties/implements.ets @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +interface A { + @memo prop: (() => void) | undefined +} + +class AA implements A { + @memo prop: (() => void) | undefined +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets b/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets new file mode 100644 index 000000000..c46a181e5 --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" + +interface A { + arg: () => void + @memo memo_arg: () => void + @memo memo_optional_arg?: () => void + @memo memo_union_arg: (() => void) | undefined + + arg_memo_type: @memo () => void +} + +@memo() (() => { + let a: A = { + arg: (() => {}), + memo_arg: (() => {}), + memo_union_arg: (() => {}), + arg_memo_type: (() => {}), + }; +}); \ No newline at end of file diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts new file mode 100644 index 000000000..4665140d4 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const FUNCTION_DIR_PATH: string = 'memo/functions'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'argument-call.ets')]; + +const pluginTester = new PluginTester('test memo function', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +function memo_arg_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg2: ((x: number)=> number), @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number), arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 5); + const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_arg3 = __memo_scope.param(2, arg3), __memo_parameter_arg4 = __memo_scope.param(3, arg4), __memo_parameter_arg5 = __memo_scope.param(4, arg5); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + __memo_parameter_arg2.value(__memo_parameter_arg1.value); + __memo_parameter_arg3.value(__memo_context, ((__memo_id) + ()), __memo_parameter_arg1.value); + ({let gensym%%_ = __memo_parameter_arg4.value; + (((gensym%%_) == (null)) ? undefined : gensym%%_(__memo_parameter_arg1.value))}); + ({let gensym%%_ = __memo_parameter_arg5.value; + (((gensym%%_) == (null)) ? undefined : gensym%%_(__memo_context, ((__memo_id) + ()), __memo_parameter_arg1.value))}); + { + __memo_scope.recache(); + return; + } +} +function memo_arg_call_with_lowering(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 3); + const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg4 = __memo_scope.param(1, arg4), __memo_parameter_arg5 = __memo_scope.param(2, arg5); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + let gensym___ = __memo_parameter_arg4.value; + (((gensym___) == (null)) ? undefined : gensym___(__memo_parameter_arg1.value)); + } + { + let gensym___ = __memo_parameter_arg5.value; + (((gensym___) == (null)) ? undefined : gensym___(__memo_context, ((__memo_id) + ()), __memo_parameter_arg1.value)); + } + { + __memo_scope.recache(); + return; + } +} +function args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: int, @memo() gensym%%_?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int), gensym%%_?: int, arg4?: int): void { + let arg1: int = (((gensym%%_) !== (undefined)) ? gensym%%_ : (10 as int)); + let arg2: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int) = (((gensym%%_) !== (undefined)) ? gensym%%_ : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): int => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(20); + }) as ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int))); + let arg3: int = (((gensym%%_) !== (undefined)) ? gensym%%_ : (arg1 as int)); + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 4); + const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_arg3 = __memo_scope.param(2, arg3), __memo_parameter_arg4 = __memo_scope.param(3, arg4); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + console.log(__memo_parameter_arg1.value, __memo_parameter_arg2.value, __memo_parameter_arg3.value, __memo_parameter_arg4.value); + console.log(__memo_parameter_arg2.value(__memo_context, ((__memo_id) + ()))); + { + __memo_scope.recache(); + return; + } +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform argument calls in functions', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts new file mode 100644 index 000000000..db15946ae --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const FUNCTION_DIR_PATH: string = 'memo/functions'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'declare-and-call.ets'), +]; + +const pluginTester = new PluginTester('test memo function', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + funcA(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } +}); +@memo() function funcA(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void +function funcB(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + funcA(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } +} +class A { + public foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + funcA(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform declare functions and calls', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts new file mode 100644 index 000000000..8e5494643 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const FUNCTION_DIR_PATH: string = 'memo/functions'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'inner-functions.ets'), +]; + +const pluginTester = new PluginTester('test memo function', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } +} +function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + const qux = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + foo(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } + }); + const other = (() => {}); + { + __memo_scope.recache(); + return; + } +} +class A { + public goo(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + let func = (() => {}); + let func2 = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + foo(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } + }); + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform inner functions', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts new file mode 100644 index 000000000..53e3243e1 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const FUNCTION_DIR_PATH: string = 'memo/functions'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'non-void-return-type.ets'), +]; + +const pluginTester = new PluginTester('test memo function', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +function funcNum(__memo_context: __memo_context_type, __memo_id: __memo_id_type): number { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(1); +} +function funcStr(__memo_context: __memo_context_type, __memo_id: __memo_id_type): string { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(\"1\"); +} +function funcBool(__memo_context: __memo_context_type, __memo_id: __memo_id_type): boolean { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(false); +} +function funcA(__memo_context: __memo_context_type, __memo_id: __memo_id_type): A { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache({ + str: \"1\", + }); +} +function funcB(__memo_context: __memo_context_type, __memo_id: __memo_id_type): B { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(((str: string) => {})); +} +function funcC(__memo_context: __memo_context_type, __memo_id: __memo_id_type): C { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(new C(\"1\")); +} +function funcD(__memo_context: __memo_context_type, __memo_id: __memo_id_type): (()=> void) { + const __memo_scope = __memo_context.scope<(()=> void)>(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache((() => {})); +} +interface A { + set str(str: string) + get str(): string +} +type B = ((str: string)=> void); +class C { + public str: string; + public constructor(str: string) { + (this).str = str; + } +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform functions with non-void return type', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts new file mode 100644 index 000000000..7db7cd676 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const FUNCTION_DIR_PATH: string = 'memo/functions'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'type-reference.ets'), +]; + +const pluginTester = new PluginTester('test memo function', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() function A(__memo_context: __memo_context_type, __memo_id: __memo_id_type): Attribute +function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): ItemBuilder { + const __memo_scope = __memo_context.scope>(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(((__memo_context: __memo_context_type, __memo_id: __memo_id_type, item: Item): void => {})); +} +@memo() type ItemBuilder = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, item: Item)=> void); +interface Item { + set item(item: T) + get item(): T +} +interface Attribute { + @memo() each(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() itemGenerator: ItemBuilder): Attribute +} +class B { + public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + A(__memo_context, ((__memo_id) + ())).each(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, ri: Item): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_ri = __memo_scope.param(0, ri); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform functions with type reference', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts index 72555dd78..08c0eb3bd 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts @@ -29,14 +29,11 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo function', buildConfig); -function testMemoTransformer(this: PluginTestContext): void { - const expectedScript: string = ` -import { memo as memo } from \"@ohos.arkui.stateManagement\"; - +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; function main() {} - function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + (7245993)), 0); + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); if (__memo_scope.unchanged) { __memo_scope.cached; return; @@ -47,6 +44,8 @@ function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): v } } `; + +function testMemoTransformer(this: PluginTestContext): void { expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); } diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts new file mode 100644 index 000000000..f23a8d252 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const LAMBDA_DIR_PATH: string = 'memo/lambdas'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'argument-call.ets')]; + +const pluginTester = new PluginTester('test memo lambda', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +((arg: (()=> void)) => {})((() => {})); + +((arg: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) => {})(@memo() (() => {})); + +((gensym%%_1?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) => { + let arg: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) = (((gensym%%_1) !== (undefined)) ? gensym%%_1 : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + (201676739)), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }) as @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))); +})(@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + (209782503)), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } +})); + +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void => { + let arg: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) = (((gensym%%_) !== (undefined)) ? gensym%%_ : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }) as @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))); + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })(__memo_context, ((__memo_id) + ()), @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); + { + __memo_scope.recache(); + return; + } +}); + +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + let goo = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: string): void => { + let name: string = (((gensym%%_) !== (undefined)) ? gensym%%_ : (\"old\" as string)); + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_name = __memo_scope.param(0, name); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }); + goo(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } +}); + +(() => { + let foo = ((gensym%%_?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) => { + let arg: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) = (((gensym%%_) !== (undefined)) ? gensym%%_ : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }) as @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))); + }); + foo(@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); +}); +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform argument calls in lambdas', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts new file mode 100644 index 000000000..7f326a4c0 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const LAMBDA_DIR_PATH: string = 'memo/lambdas'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'trailing-lambdas.ets'), +]; + +const pluginTester = new PluginTester('test memo lambda', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + let a = new A(); + a.foo(__memo_context, ((__memo_id) + ()), (() => { + console.log(); + })); + a.goo(((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + console.log(); + { + __memo_scope.recache(); + return; + } + })); + a.koo(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + console.log(); + { + __memo_scope.recache(); + return; + } + })); + bar(__memo_context, ((__memo_id) + ()), (() => { + console.log(); + })); + par(((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + console.log(); + { + __memo_scope.recache(); + return; + } + })); + kar(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + console.log(); + { + __memo_scope.recache(); + return; + } + })); + { + __memo_scope.recache(); + return; + } +}); +function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, f?: (()=> void)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_f = __memo_scope.param(0, f); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } +} +function par(f?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +function kar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() f?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_f = __memo_scope.param(0, f); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } +} +class A { + public foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, p?: (()=> void)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_p = __memo_scope.param(0, p); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public goo(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} + public koo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_p = __memo_scope.param(0, p); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform trailing lambdas', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts new file mode 100644 index 000000000..59b48a024 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const LAMBDA_DIR_PATH: string = 'memo/lambdas'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'void-lambda.ets'), +]; + +const pluginTester = new PluginTester('test memo lambda', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } +}); +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg?: (()=> string)): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } +}); +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform lambdas with void return type', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts new file mode 100644 index 000000000..b6ac3bd35 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const LAMBDA_DIR_PATH: string = 'memo/lambdas'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'with-receiver.ets'), +]; + +const pluginTester = new PluginTester('test memo lambda', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + let x = new Person(); + fullName(x, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); + let f1: F1 = foo; + f1 = goo; + let f2: F2 = goo; + f2 = foo; + f1 = f2; + let a = new A(); + f1(a, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); + f1(a, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); + f2(a, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); + { + __memo_scope.recache(); + return; + } +}); +function fullName(this: Person, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { + return; +} +function foo(this: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +function goo(a: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +class Person { + public constructor() {} +} +class A { + public constructor() {} +} +type F1 = ((this: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))=> void); +type F2 = ((a: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))=> void); +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform lambdas with receiver', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts new file mode 100644 index 000000000..de72519e7 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const METHOD_DIR_PATH: string = 'memo/methods'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'argument-call.ets')]; + +const pluginTester = new PluginTester('test memo method', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +class Test { + public lambda_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public lambda_arg_with_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, value: string)=> string)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public memo_content(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() content: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_content = __memo_scope.param(0, content); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + __memo_parameter_content.value(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } + } + public compute_test(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() arg1: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined, arg2: (()=> void) | undefined, content: (()=> void) | undefined): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 3); + const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_content = __memo_scope.param(2, content); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +class Use { + public test(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + const test = new Test(); + test.lambda_arg(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); + test.lambda_arg_with_arg(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, value: string): string => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_value = __memo_scope.param(0, value); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(__memo_parameter_value.value); + })); + test.compute_test(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }), (() => {}), (() => {})); + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform argument calls in methods', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts new file mode 100644 index 000000000..c0f81bd4c --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const METHOD_DIR_PATH: string = 'memo/methods'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'callable.ets')]; + +const pluginTester = new PluginTester('test memo method', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + A.$_invoke(__memo_context, ((__memo_id) + ())); + B.$_invoke(((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + })); + let x: C | D = C.$_instantiate(__memo_context, ((__memo_id) + ()), (() => { + return new C(); + })); + x = D.$_instantiate((() => { + return new D(); + })); + { + __memo_scope.recache(); + return; + } +}); +class A { + public static $_invoke(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +class B { + public static $_invoke(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} + public constructor() {} +} +class C { + public static $_instantiate(__memo_context: __memo_context_type, __memo_id: __memo_id_type, factory: (()=> C)): C { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_factory = __memo_scope.param(0, factory); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(__memo_parameter_factory.value()); + } + public constructor() {} +} +class D { + public static $_instantiate(factory: (()=> D), @memo() content?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): D { + return factory(); + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform callable class', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts new file mode 100644 index 000000000..0a669b4c0 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const METHOD_DIR_PATH: string = 'memo/methods'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'declare-and-call.ets'), +]; + +const pluginTester = new PluginTester('test memo method', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + new AA().x(__memo_context, ((__memo_id) + ())); + const a: A = new AA(); + a.x(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } +}); +declare abstract class A { + @memo() public x(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void + public test_signature(@memo() arg1: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void), @memo() arg2: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined, @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined | ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int) | undefined, @memo() x: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, y: ((z: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))=> void))=> void)): @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) + public constructor() {} +} +class AA extends A { + public x(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform declare methods and calls', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts new file mode 100644 index 000000000..e85c7ccc7 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const METHOD_DIR_PATH: string = 'memo/methods'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'internal-calls.ets')]; + +const pluginTester = new PluginTester('test memo method', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +function __context(): __memo_context_type +function __id(): __memo_id_type +type MemoType = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); +class Test { + public void_method(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public internal_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + (this).void_method(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } + } + public method_with_internals(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + __context(); + __id(); + { + __memo_scope.recache(); + return; + } + } + public memo_lambda() { + @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }); + } + public memo_variables(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + @memo() const f = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): number => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(123); + }), g = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number): number => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_x = __memo_scope.param(0, x); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(((123) + (x))); + }); + const h = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): number => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(1); + }); + f(__memo_context, ((__memo_id) + ())); + g(__memo_context, ((__memo_id) + ()), 1); + h(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } + } + public args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_1?: int, gensym%%_2?: (()=> int), gensym%%_3?: int, arg4?: int): void { + let arg1: int = (((gensym%%_1) !== (undefined)) ? gensym%%_1 : (10 as int)); + let arg2: (()=> int) = (((gensym%%_2) !== (undefined)) ? gensym%%_2 : ((() => { + return 20; + }) as (()=> int))); + let arg3: int = (((gensym%%_3) !== (undefined)) ? gensym%%_3 : (arg1 as int)); + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 4); + const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_arg3 = __memo_scope.param(2, arg3), __memo_parameter_arg4 = __memo_scope.param(3, arg4); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + console.log(__memo_parameter_arg1.value, __memo_parameter_arg2.value, __memo_parameter_arg3.value, __memo_parameter_arg4.value); + console.log(__memo_parameter_arg2.value()); + { + __memo_scope.recache(); + return; + } + } + public optional_args(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1?: int, arg2?: (()=> int)): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 2); + const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + console.log(__memo_parameter_arg1.value); + console.log(__memo_parameter_arg2.value); + console.log(({let gensym%%_166 = __memo_parameter_arg2.value; + (((gensym%%_166) == (null)) ? undefined : gensym%%_166())})); + { + __memo_scope.recache(); + return; + } + } + public type_alias(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: MemoType): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + __memo_parameter_arg.value(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform inner calls in methods', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts new file mode 100644 index 000000000..f8bba95f0 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const METHOD_DIR_PATH: string = 'memo/methods'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'non-void-method.ets')]; + +const pluginTester = new PluginTester('test memo method', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +function __context(): __memo_context_type +function __id(): __memo_id_type +@Retention({policy:"SOURCE"}) @interface memo_intrinsic {} +@Retention({policy:"SOURCE"}) @interface memo_entry {} +class Test { + public void_method(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public string_method_with_return(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: string): string { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(__memo_parameter_arg.value); + } + public method_with_type_parameter(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: T): T { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + return __memo_scope.recache(__memo_parameter_arg.value); + } + public intrinsic_method(): int { + return 0; + } + public intrinsic_method_with_this(): int { + (this).void_method(__memo_context, ((__memo_id) + ())); + return 0; + } + public memoEntry(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() entry: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> R)): R { + const getContext = (() => { + return __context(); + }); + const getId = (() => { + return __id(); + }); + { + const __memo_context = getContext(); + const __memo_id = getId(); + return entry(__memo_context, ((__memo_id) + ())); + } + } + public constructor() {} +} +class Use { + public test(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + const test = new Test(); + test.string_method_with_return(__memo_context, ((__memo_id) + ()), "a string"); + test.method_with_type_parameter(__memo_context, ((__memo_id) + ()), "I'm string"); + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform methods with non-void return type', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts new file mode 100644 index 000000000..953742b8a --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const METHOD_DIR_PATH: string = 'memo/methods'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'void-method.ets'), +]; + +const pluginTester = new PluginTester('test memo method', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +class A { + public x: int; + public y: int; + public constructor() {} +} +class Test { + public void_method(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public a_method_with_implicit_return_type(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public void_method_with_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: string): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public void_method_with_return(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: string): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public static static_method_with_type_parameter(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: T): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public obj_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: A): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); + const __memo_parameter_arg = __memo_scope.param(0, arg); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +class Use { + public test(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + const test = new Test(); + test.void_method(__memo_context, ((__memo_id) + ())); + test.void_method_with_arg(__memo_context, ((__memo_id) + ()), "an arg"); + test.void_method_with_return(__memo_context, ((__memo_id) + ()), "a value"); + Test.static_method_with_type_parameter(__memo_context, ((__memo_id) + ()), "I'm static"); + test.obj_arg(__memo_context, ((__memo_id) + ()), { + x: 1, + y: 2, + }); + { + __memo_scope.recache(); + return; + } + } + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform methods with void return type', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts new file mode 100644 index 000000000..c912aba8d --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const PROPERTY_DIR_PATH: string = 'memo/properties'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, PROPERTY_DIR_PATH, 'class-constructor.ets'), +]; + +const pluginTester = new PluginTester('test memo property', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + let a = new AA({ + a: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }), + }); + { + __memo_scope.recache(); + return; + } +}); +interface A { + @memo() set a(a: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void + @memo() get a(): ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) +} +class AA { + @memo() public a: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined; + constructor() { + (this)(undefined); + } + public constructor(arg: A | undefined) { + (this).a = ({let gensym%%_ = arg; + (((gensym%%_) == (null)) ? undefined : gensym%%_.a)}); + } + public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + ({let gensym%%_ = (this).a; + (((gensym%%_) == (null)) ? undefined : gensym%%_(__memo_context, ((__memo_id) + ())))}); + { + __memo_scope.recache(); + return; + } + } +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform properties in class constructor', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts new file mode 100644 index 000000000..3be259236 --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const PROPERTY_DIR_PATH: string = 'memo/properties'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, PROPERTY_DIR_PATH, 'class-properties.ets'), +]; + +const pluginTester = new PluginTester('test memo property', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +function main() {} +class A { + public arg: (()=> void); + @memo() public memo_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); + @memo() public memo_optional_arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined; + @memo() public memo_union_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }); + public arg_memo_type: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); + public constructor() { + (this).arg = (() => {}); + (this).memo_arg = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }); + (this).arg_memo_type = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }); + } + public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + (this).arg(); + (this).memo_arg(__memo_context, ((__memo_id) + ())); + (this).arg_memo_type(__memo_context, ((__memo_id) + ())); + { + __memo_scope.recache(); + return; + } + } +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform properties in class', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts new file mode 100644 index 000000000..99053d0ef --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; + +const PROPERTY_DIR_PATH: string = 'memo/properties'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, PROPERTY_DIR_PATH, 'interfaces.ets')]; + +const pluginTester = new PluginTester('test memo property', buildConfig); + +const expectedScript: string = ` +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +function main() {} +@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + let a: A = { + arg: (() => {}), + memo_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }), + memo_union_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }), + arg_memo_type: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } + }), + }; + { + __memo_scope.recache(); + return; + } +}); +interface A { + set arg(arg: (()=> void)) + get arg(): (()=> void) + @memo() set memo_arg(memo_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void + @memo() get memo_arg(): ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) + @memo() set memo_optional_arg(memo_optional_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined): void + @memo() get memo_optional_arg(): ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined + @memo() set memo_union_arg(memo_union_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined): void + @memo() get memo_union_arg(): ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined + set arg_memo_type(arg_memo_type: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) + get arg_memo_type(): @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform interface properties', + [memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts index 3c8f13a7d..37b4605ad 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts @@ -32,7 +32,7 @@ const pluginTester = new PluginTester('test builder-lambda simple component', bu function testBuilderLambdaTransformer(this: PluginTestContext): void { const expectedScript: string = ` import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -import { Column as Column, ColumnAttribute as ColumnAttribute } from \"@ohos.arkui.component\"; +import { Column as Column, UIColumnAttribute as UIColumnAttribute } from \"arkui.component.column\"; function main() {} class MyStateSample { @memo() public build() { @@ -47,21 +47,25 @@ class MyStateSample { function testMemoTransformer(this: PluginTestContext): void { const expectedScript: string = ` import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -import { Column as Column, ColumnAttribute as ColumnAttribute } from \"@ohos.arkui.component\"; +import { Column as Column, UIColumnAttribute as UIColumnAttribute } from \"arkui.component.column\"; function main() {} class MyStateSample { - public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type) { + public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { const __memo_scope = __memo_context.scope(((__memo_id) + (263357132)), 0); if (__memo_scope.unchanged) { __memo_scope.cached; return; } - Column(__memo_context, ((__memo_id) + (65509320)), undefined, undefined, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { - const __memo_scope = __memo_context.scope(((__memo_id) + (147296800)), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } + Column(__memo_context, ((__memo_id) + (65509320)), undefined, undefined, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + const __memo_scope = __memo_context.scope(((__memo_id) + (147296800)), 0); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + { + __memo_scope.recache(); + return; + } })); { __memo_scope.recache(); diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index d70732041..ce062418c 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -388,6 +388,32 @@ KNativePointer impl_ETSParserGetGlobalProgramAbsName(KNativePointer contextPtr) } KOALA_INTEROP_1(ETSParserGetGlobalProgramAbsName, KNativePointer, KNativePointer) +KNativePointer impl_ClassVariableDeclaration(KNativePointer context, KNativePointer classInstance) +{ + const auto _context = reinterpret_cast(context); + const auto _classInstance = reinterpret_cast(classInstance); + auto _typedTsType = GetImpl()->TypedTsType(_context, _classInstance); + if (_typedTsType == nullptr) { + return nullptr; + } + const auto _instanceType = reinterpret_cast(_typedTsType); + auto _typeVar = GetImpl()->TypeVariable(_context, _instanceType); + if (_typeVar == nullptr) { + return nullptr; + } + const auto result = reinterpret_cast(GetImpl()->VariableDeclaration(_context, _typeVar)); + const auto declNode = GetImpl()->DeclNode(_context, result); + return declNode; +} +KOALA_INTEROP_2(ClassVariableDeclaration, KNativePointer, KNativePointer, KNativePointer) + +KBoolean impl_IsMethodDefinition(KNativePointer nodePtr) +{ + auto node = reinterpret_cast(nodePtr); + return GetImpl()->IsMethodDefinition(node); +} +KOALA_INTEROP_1(IsMethodDefinition, KBoolean, KNativePointer) + KNativePointer impl_CreateETSImportDeclaration(KNativePointer context, KNativePointer source, KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind, KNativePointer programPtr, KInt flags) diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index ee30a3abf..551481a4f 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -817,6 +817,14 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _ClassVariableDeclaration(context: KNativePointer, classInstance: KNativePointer): KNativePointer { + throw new Error('Not implemented'); + } + + _IsMethodDefinition(node: KPtr): KBoolean { + throw new Error('Not implemented'); + } + _AstNodeRangeConst(context: KNativePointer, node: KNativePointer): KNativePointer { throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); } diff --git a/koala-wrapper/src/arkts-api/factory/nodeTests.ts b/koala-wrapper/src/arkts-api/factory/nodeTests.ts index 6f2d9590f..62c02275a 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeTests.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeTests.ts @@ -28,7 +28,8 @@ import { StructDeclaration, VariableDeclaration, VariableDeclarator, - AssignmentExpression + AssignmentExpression, + NumberLiteral } from "../types" import { MemberExpression } from "../to-be-generated/MemberExpression" import { AstNode } from "../peers/AstNode" @@ -46,7 +47,7 @@ export function isFunctionDeclaration(node: AstNode): node is FunctionDeclaratio } export function isMethodDefinition(node: AstNode): node is MethodDefinition { - return node instanceof MethodDefinition + return global.es2panda._IsMethodDefinition(node.peer); } export function isEtsScript(node: AstNode): node is EtsScript { @@ -91,4 +92,8 @@ export function isVariableDeclarator(node: AstNode): node is VariableDeclarator export function isAssignmentExpression(node: AstNode): node is AssignmentExpression { return node instanceof AssignmentExpression; +} + +export function isNumberLiteral(node: AstNode): node is NumberLiteral { + return node instanceof NumberLiteral; } \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts index 24432ec6d..0bd18e52d 100644 --- a/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts +++ b/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts @@ -33,6 +33,10 @@ export function updateVariableDeclaration( return original; } - const update = updateThenAttach(VariableDeclaration.update, attachModifiers); + const update = updateThenAttach( + VariableDeclaration.update, + attachModifiers, + (node: VariableDeclaration, original: VariableDeclaration) => node.setAnnotations(original.annotations) + ); return update(original, modifiers, kind, declarators); } diff --git a/koala-wrapper/src/arkts-api/peers/AstNode.ts b/koala-wrapper/src/arkts-api/peers/AstNode.ts index 634da8e17..62a0b78d2 100644 --- a/koala-wrapper/src/arkts-api/peers/AstNode.ts +++ b/koala-wrapper/src/arkts-api/peers/AstNode.ts @@ -31,7 +31,12 @@ export abstract class AstNode extends ArktsObject { } public get originalPeer(): KNativePointer { - return global.generatedEs2panda._AstNodeOriginalNodeConst(global.context, this.peer) + const result = global.generatedEs2panda._AstNodeOriginalNodeConst(global.context, this.peer) + if (result === nullptr) { + this.originalPeer = this.peer + return this.peer + } + return result } public set originalPeer(peer: KNativePointer) { diff --git a/koala-wrapper/src/arkts-api/types.ts b/koala-wrapper/src/arkts-api/types.ts index 3faf2f690..ca450782c 100644 --- a/koala-wrapper/src/arkts-api/types.ts +++ b/koala-wrapper/src/arkts-api/types.ts @@ -793,6 +793,22 @@ export class VariableDeclaration extends AstNode { return new VariableDeclaration(peer); } + get annotations(): readonly AnnotationUsage[] { + return unpackNodeArray( + global.generatedEs2panda._VariableDeclarationAnnotationsConst(global.context, this.peer) + ); + } + /** @deprecated */ + setAnnotations(annotations: readonly AnnotationUsage[]): this { + global.generatedEs2panda._VariableDeclarationSetAnnotations( + global.context, + this.peer, + passNodeArray(annotations), + annotations.length + ); + return this; + } + readonly declarationKind: Es2pandaVariableDeclarationKind; readonly declarators: readonly VariableDeclarator[]; } diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index 6b1bf7d57..2b21e625b 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -13,90 +13,165 @@ * limitations under the License. */ -import { global } from "../static/global" -import { isNumber, throwError, getEnumName } from "../../utils" -import { KNativePointer, KInt, nullptr, withStringResult } from "@koalaui/interop" -import { passNode, passString, unpackNodeArray, unpackNonNullableNode } from "./private" -import { isFunctionDeclaration, isMemberExpression } from "../factory/nodeTests" -import { Es2pandaContextState, Es2pandaModifierFlags } from "../../generated/Es2pandaEnums" -import type { AstNode } from "../peers/AstNode" -import { ClassDefinition, ClassProperty, ETSImportDeclaration, ImportSpecifier, isClassDefinition, isScriptFunction, type AnnotationUsage } from "../../generated" -import { Program } from "../peers/Program" -import { clearNodeCache } from "../class-by-peer" -import { SourcePosition } from "../peers/SourcePosition" - +import { global } from '../static/global'; +import { isNumber, throwError, getEnumName } from '../../utils'; +import { KNativePointer, KInt, nullptr, withStringResult } from '@koalaui/interop'; +import { passNode, passString, unpackNodeArray, unpackNonNullableNode } from './private'; +import { isFunctionDeclaration, isMemberExpression, isMethodDefinition, isNumberLiteral } from '../factory/nodeTests'; +import { + Es2pandaContextState, + Es2pandaMethodDefinitionKind, + Es2pandaModifierFlags, +} from '../../generated/Es2pandaEnums'; +import type { AstNode } from '../peers/AstNode'; +import { + ClassDefinition, + ClassProperty, + ETSImportDeclaration, + ImportSpecifier, + isClassDefinition, + isIdentifier, + isObjectExpression, + isProperty, + isScriptFunction, + isTSInterfaceDeclaration, + Property, + type AnnotationUsage, +} from '../../generated'; +import { Program } from '../peers/Program'; +import { clearNodeCache } from '../class-by-peer'; +import { SourcePosition } from '../peers/SourcePosition'; +import { MemberExpression } from '../to-be-generated/MemberExpression'; export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { - console.log("[TS WRAPPER] PROCEED TO STATE: ", getEnumName(Es2pandaContextState, state)); + console.log('[TS WRAPPER] PROCEED TO STATE: ', getEnumName(Es2pandaContextState, state)); if (state <= global.es2panda._ContextState(global.context)) { - console.log("[TS WRAPPER] PROCEED TO STATE: SKIPPING"); - return + console.log('[TS WRAPPER] PROCEED TO STATE: SKIPPING'); + return; } - clearNodeCache() + clearNodeCache(); try { - global.es2panda._ProceedToState(global.context, state) - if (global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && !forceDtsEmit) { - const errorMessage = withStringResult(global.es2panda._ContextErrorMessage(global.context)) + global.es2panda._ProceedToState(global.context, state); + if ( + global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && + !forceDtsEmit + ) { + const errorMessage = withStringResult(global.es2panda._ContextErrorMessage(global.context)); if (errorMessage === undefined) { - throwError(`Could not get ContextErrorMessage`) + throwError(`Could not get ContextErrorMessage`); } - throwError( - [ - `Failed to proceed to ${Es2pandaContextState[state]}`, - errorMessage - ] - .join(`\n`) - ) + throwError([`Failed to proceed to ${Es2pandaContextState[state]}`, errorMessage].join(`\n`)); } } catch (e) { - global.es2panda._DestroyContext(global.context) - throw e + global.es2panda._DestroyContext(global.context); + throw e; } } export function startChecker(): boolean { - return global.es2panda._CheckerStartChecker(global.context) + return global.es2panda._CheckerStartChecker(global.context); } export function recheckSubtree(node: AstNode): void { - global.es2panda._AstNodeRecheck(global.context, node.peer) + global.es2panda._AstNodeRecheck(global.context, node.peer); } export function rebindSubtree(node: AstNode): void { - global.es2panda._AstNodeRebind(global.context, node.peer) + global.es2panda._AstNodeRebind(global.context, node.peer); } export function getDecl(node: AstNode): AstNode | undefined { if (isMemberExpression(node)) { - return getDecl(node.property) + return getDeclFromArrayOrObjectMember(node); + } + if (isObjectExpression(node)) { + return getPeerObjectDecl(passNode(node)); + } + const decl = getPeerDecl(passNode(node)); + if (!!decl) { + return decl; + } + if (isProperty(node.parent)) { + return getDeclFromProperty(node.parent); + } + return undefined; +} + +function getDeclFromProperty(node: Property): AstNode | undefined { + if (!node.key) { + return undefined; + } + if (!isObjectExpression(node.parent)) { + return getPeerDecl(passNode(node.key)); + } + return getDeclFromObjectExpressionProperty(node); +} + +function getDeclFromObjectExpressionProperty(node: Property): AstNode | undefined { + const declNode = getPeerObjectDecl(passNode(node.parent)); + if (!declNode || !node.key || !isIdentifier(node.key)) { + return undefined; } - const decl = global.es2panda._DeclarationFromIdentifier(global.context, passNode(node)) + let body: readonly AstNode[] = []; + if (isClassDefinition(declNode)) { + body = declNode.body; + } else if (isTSInterfaceDeclaration(declNode)) { + body = declNode.body?.body ?? []; + } + return body.find( + (statement) => + isMethodDefinition(statement) && + statement.kind === Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET && + !!statement.name && + !!node.key && + isIdentifier(node.key) && + statement.name.name === node.key.name + ); +} + +function getDeclFromArrayOrObjectMember(node: MemberExpression): AstNode | undefined { + if (isNumberLiteral(node.property)) { + return getDecl(node.object); + } + return getDecl(node.property); +} + +export function getPeerDecl(peer: KNativePointer): AstNode | undefined { + const decl = global.es2panda._DeclarationFromIdentifier(global.context, peer); if (decl === nullptr) { - return undefined + return undefined; } - return unpackNonNullableNode(decl) + return unpackNonNullableNode(decl); +} + +export function getPeerObjectDecl(peer: KNativePointer): AstNode | undefined { + const decl = global.es2panda._ClassVariableDeclaration(global.context, peer); + if (decl === nullptr) { + return undefined; + } + return unpackNonNullableNode(decl); } export function getAnnotations(node: AstNode): readonly AnnotationUsage[] { if (!isFunctionDeclaration(node) && !isScriptFunction(node) && !isClassDefinition(node)) { - throwError('for now annotations allowed only for: functionDeclaration, scriptFunction, classDefinition') + throwError('for now annotations allowed only for: functionDeclaration, scriptFunction, classDefinition'); } - return unpackNodeArray(global.es2panda._AnnotationAllowedAnnotations(global.context, node.peer, nullptr)) + return unpackNodeArray(global.es2panda._AnnotationAllowedAnnotations(global.context, node.peer, nullptr)); } export function getOriginalNode(node: AstNode): AstNode { if (node === undefined) { // TODO: fix this - throwError('there is no arkts pair of ts node (unable to getOriginalNode)') + throwError('there is no arkts pair of ts node (unable to getOriginalNode)'); } if (node.originalPeer === nullptr) { - return node + return node; } - return unpackNonNullableNode(node.originalPeer) + return unpackNonNullableNode(node.originalPeer); } export function getFileName(): string { - return global.filePath + return global.filePath; } export function classDefinitionSetFromStructModifier(node: ClassDefinition): void { @@ -120,12 +195,12 @@ export function ImportSpecifierIsRemovableConst(node: ImportSpecifier): boolean // Use this function if you need // the language level modifiers: public, declare, export, etc. export function classDefinitionFlags(node: ClassDefinition): Es2pandaModifierFlags { - return global.generatedEs2panda._AstNodeModifiers(global.context, node.peer) + return global.generatedEs2panda._AstNodeModifiers(global.context, node.peer); } // TODO: Import statements should be inserted to the statements export function importDeclarationInsert(node: ETSImportDeclaration, program: Program): void { - global.es2panda._InsertETSImportDeclarationAndParse(global.context, program.peer, node.peer) + global.es2panda._InsertETSImportDeclarationAndParse(global.context, program.peer, node.peer); } export function hasModifierFlag(node: AstNode, flag: Es2pandaModifierFlags): boolean { @@ -135,7 +210,7 @@ export function hasModifierFlag(node: AstNode, flag: Es2pandaModifierFlags): boo if (isClassDefinition(node)) { modifiers = classDefinitionFlags(node); } else { - modifiers = node.modifiers + modifiers = node.modifiers; } return (modifiers & flag) === flag; } @@ -153,10 +228,11 @@ export function classPropertySetOptional(node: ClassProperty, value: boolean): C export function modifiersToString(modifiers: Es2pandaModifierFlags): string { return Object.values(Es2pandaModifierFlags) .filter(isNumber) - .map(it => { - console.log(it.valueOf(), Es2pandaModifierFlags[it], modifiers.valueOf() & it) - return ((modifiers.valueOf() & it) === it) ? Es2pandaModifierFlags[it] : "" - }).join(" ") + .map((it) => { + console.log(it.valueOf(), Es2pandaModifierFlags[it], modifiers.valueOf() & it); + return (modifiers.valueOf() & it) === it ? Es2pandaModifierFlags[it] : ''; + }) + .join(' '); } export function destroyConfig(config: KNativePointer): void { global.es2panda._DestroyConfig(config); @@ -164,11 +240,16 @@ export function destroyConfig(config: KNativePointer): void { } export function setAllParents(ast: AstNode) { - global.es2panda._AstNodeUpdateAll(global.context, ast.peer) + global.es2panda._AstNodeUpdateAll(global.context, ast.peer); } export function generateTsDeclarationsFromContext(outputDeclEts: string, outputEts: string, exportAll: boolean): KInt { - return global.es2panda._GenerateTsDeclarationsFromContext(global.context, passString(outputDeclEts), passString(outputEts), exportAll) + return global.es2panda._GenerateTsDeclarationsFromContext( + global.context, + passString(outputDeclEts), + passString(outputEts), + exportAll + ); } export function isDefaultAccessModifierClassProperty(property: ClassProperty): boolean { @@ -181,4 +262,4 @@ export function getStartPosition(node: AstNode): SourcePosition { export function getEndPosition(node: AstNode): SourcePosition { return new SourcePosition(global.es2panda._AstNodeEndConst(global.context, node.peer)); -} \ No newline at end of file +} diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index 76d531c12..3125fb088 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -43,6 +43,8 @@ import { Expression, isETSNewClassInstanceExpression, isTemplateLiteral, + isBlockExpression, + isReturnStatement, } from '../generated'; import { isEtsScript, @@ -162,6 +164,10 @@ function visitOuterExpression(node: AstNode, visitor: Visitor): AstNode { if (updated) { return node; } + if (isBlockExpression(node)) { + updated = true; + return factory.updateBlockExpression(node, nodesVisitor(node.statements, visitor)); + } if (isCallExpression(node)) { updated = true; const call = factory.updateCallExpression( @@ -363,6 +369,10 @@ function visitStatement(node: AstNode, visitor: Visitor): AstNode { nodeVisitor(node.alternate, visitor) ); } + if (isReturnStatement(node)) { + updated = true; + return factory.updateReturnStatement(node, nodeVisitor(node.argument, visitor)); + } // TODO return node; } -- Gitee From 32c0e1e049735e2c57028c1affed1048e5a340bf Mon Sep 17 00:00:00 2001 From: wangweiyuan Date: Tue, 29 Apr 2025 20:39:19 +0800 Subject: [PATCH 081/123] add ui-syntax-plugins(39/51) Signed-off-by: wangweiyuan --- .../consumer-provider-decorator-check.ts | 271 ++++++++++++++++++ .../ui-syntax-plugins/rules/index.ts | 24 ++ .../rules/reuse-attribute-check.ts | 107 +++++++ .../rules/struct-missing-decorator.ts | 74 +++++ .../rules/struct-property-decorator.ts | 52 ++++ .../rules/struct-variable-initialization.ts | 72 +++++ .../rules/track-decorator-check.ts | 146 ++++++++++ .../rules/type-decorator-check.ts | 167 +++++++++++ .../rules/validate-build-in-struct.ts | 135 +++++++++ ...iable-initialization-via-component-cons.ts | 210 ++++++++++++++ .../rules/watch-decorator-function.ts | 128 +++++++++ .../rules/watch-decorator-regular.ts | 60 ++++ .../rules/wrap-builder-check.ts | 109 +++++++ 13 files changed, 1555 insertions(+) create mode 100644 arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/struct-variable-initialization.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/type-decorator-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-cons.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts diff --git a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts new file mode 100644 index 000000000..cb4f7fcd8 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, MultiMap, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +// Traverse the member variables of the struct, recording the members of the @Consumer modifications +function processStructMembers( + node: arkts.StructDeclaration, + structName: string, + componentv2WithConsumer: MultiMap +): void { + node.definition.body.forEach((member) => { + // When a member variable is @consumer modified, it is stored to mark fields that cannot be initialized + if (arkts.isClassProperty(member)) { + const memberName = member?.key?.dumpSrc(); + structName && memberName ? componentv2WithConsumer.add(structName, memberName) : null; + } + }); +} +function rememberStructName(node: arkts.AstNode, componentv2WithConsumer: MultiMap): void { + // First it has to be of the struct type + if (arkts.isStructDeclaration(node)) { + node?.definition?.annotations.forEach((anno) => { + // Second, it must be decorated with a @component v2 decorator + if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2) { + const structName = node.definition.ident?.name ?? ''; + processStructMembers(node, structName, componentv2WithConsumer); + } + }); + } +} +function findDecorator(member: arkts.ClassProperty, decorator: string): arkts.AnnotationUsage | undefined { + return member.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() === decorator + ); +} +// Verify that the @Consumer decorator is used on the method +function validateConsumerOnMethod(member: arkts.MethodDefinition, context: UISyntaxRuleContext): void { + const annotationNode = member.scriptFunction.annotations?.find(annotation => + annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.CONSUMER + ); + if (annotationNode) { + context.report({ + node: annotationNode, + message: rule.messages.consumerOnlyOnMember, + fix: (annotationNode) => { + const startPosition = arkts.getStartPosition(annotationNode); + const endPosition = arkts.getEndPosition(annotationNode); + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); + } +} +// @Consumer Bugs that conflict with other decorators +function reportMultipleBuiltInDecorators( + hasConsumeDecorator: arkts.AnnotationUsage, + otherDecorators: arkts.AnnotationUsage, + context: UISyntaxRuleContext, +): void { + context.report({ + node: hasConsumeDecorator, + message: rule.messages.multipleBuiltInDecorators, + fix: (hasConsumeDecorator) => { + const startPosition = arkts.getStartPosition(otherDecorators); + const endPosition = arkts.getEndPosition(otherDecorators); + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); +} +// Report a bug where @Provider is missing @ComponentV2 +function reportProviderRequiresComponentV2( + hasProviderDecorator: arkts.AnnotationUsage, + hasComponent: arkts.AnnotationUsage | undefined, + node: arkts.AstNode, + context: UISyntaxRuleContext, +): void { + if (hasComponent) { + context.report({ + node: hasProviderDecorator, + message: rule.messages.providerRequiresComponentV2, + fix: (hasProviderDecorator) => { + const startPosition = arkts.getStartPosition(hasComponent); + const endPosition = arkts.getEndPosition(hasComponent); + return { + range: [startPosition, endPosition], + code: `@${PresetDecorators.COMPONENT_V2}`, + }; + } + }); + } else { + context.report({ + node: hasProviderDecorator, + message: rule.messages.providerRequiresComponentV2, + fix: (hasProviderDecorator) => { + const startPosition = arkts.getStartPosition(node); + const endPosition = startPosition; + return { + range: [startPosition, endPosition], + code: `@${PresetDecorators.COMPONENT_V2}\n`, + }; + } + }); + } +} +// Verify decorator conflicts on member variables +function validateMemberDecorators(member: arkts.ClassProperty, + hasComponentV2: arkts.AnnotationUsage | undefined, + hasComponent: arkts.AnnotationUsage | undefined, + node: arkts.AstNode, + context: UISyntaxRuleContext +): void { + const hasConsumeDecorator = findDecorator(member, PresetDecorators.CONSUMER); + const hasProviderDecorator = findDecorator(member, PresetDecorators.PROVIDER); + const otherDecorators = member.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() !== PresetDecorators.CONSUMER + ); + if (hasConsumeDecorator && otherDecorators) { + reportMultipleBuiltInDecorators(hasConsumeDecorator, otherDecorators, context); + } + if (hasProviderDecorator && !hasComponentV2) { + reportProviderRequiresComponentV2(hasProviderDecorator, hasComponent, node, context); + } +} +// Verify that @Provider is being used in the class +function validateProviderInClass(member: arkts.ClassProperty, context: UISyntaxRuleContext): void { + const hasProviderDecorator = findDecorator(member, PresetDecorators.PROVIDER); + if (hasProviderDecorator) { + context.report({ + node: hasProviderDecorator, + message: rule.messages.providerOnlyInStruct, + fix: (hasProviderDecorator) => { + const startPosition = arkts.getStartPosition(hasProviderDecorator); + const endPosition = arkts.getEndPosition(hasProviderDecorator); + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); + } +} +// Verify that the current identifier is an illegally initialized @Consumer member variable +function reportValidateConsumer( + currentNode: arkts.Identifier, + callExpName: string, + componentv2WithConsumer: MultiMap, + context: UISyntaxRuleContext +): void { + if (componentv2WithConsumer.get(callExpName).includes(currentNode.dumpSrc())) { + context.report({ + node: currentNode.parent, + message: rule.messages.forbiddenInitialization, + data: { + value: currentNode.dumpSrc(), + structName: callExpName + }, + fix: () => { + const startPosition = arkts.getStartPosition(currentNode.parent); + const endPosition = arkts.getEndPosition(currentNode.parent); + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); + } +} +// Verify that the @Consumer-decorated property is initialized +function validateConsumerInitialization(node: arkts.CallExpression, componentv2WithConsumer: MultiMap, + context: UISyntaxRuleContext): void { + const callExpName: string = node.expression.dumpSrc(); + if (componentv2WithConsumer.has(callExpName)) { + const queue: Array = [node]; + while (queue.length > 0) { + const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; + if (arkts.isIdentifier(currentNode)) { + reportValidateConsumer(currentNode, callExpName, componentv2WithConsumer, context); + } + const children = currentNode.getChildren(); + for (const child of children) { + queue.push(child); + } + } + } +} +function collectStructsWithConsumer(node: arkts.AstNode, componentv2WithConsumer: MultiMap): void { + // Used to document all V2 structs that use '@Consumer' + if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + // Breadth traversal is done through while and queues + const queue: Array = [node]; + while (queue.length > 0) { + const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; + // Filter and record the nodes of the tree + rememberStructName(currentNode, componentv2WithConsumer); + const children = currentNode.getChildren(); + for (const child of children) { + queue.push(child); + } + } + } +} +function validateStructDecoratorsAndMembers(node: arkts.AstNode, context: UISyntaxRuleContext): void { + if (arkts.isStructDeclaration(node)) { + const hasComponentV2 = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); + const hasComponent = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); + node.definition.body.forEach(member => { + if (arkts.isMethodDefinition(member)) { + validateConsumerOnMethod(member, context); + } + if (arkts.isClassProperty(member)) { + validateMemberDecorators(member, hasComponentV2, hasComponent, node, context); + } + }); + } +} +function validateProviderInClasses(node: arkts.AstNode, context: UISyntaxRuleContext): void { + if (arkts.isClassDeclaration(node)) { + node.definition?.body.forEach(member => { + if (arkts.isClassProperty(member)) { + validateProviderInClass(member, context); + } + }); + } +} +const rule: UISyntaxRule = { + name: 'consumer-provider-decorator-check', + messages: { + consumerOnlyOnMember: `'@Consumer' can only decorate member property.`, + multipleBuiltInDecorators: `The struct member variable can not be decorated by multiple built-in decorators.`, + providerRequiresComponentV2: `The '@Provider' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, + providerOnlyInStruct: `The '@Provider' decorator can only be used with 'struct'.`, + forbiddenInitialization: `Property '{{value}}' in the custom component '{{structName}}' cannot be initialized here (forbidden to specify).`, + }, + setup(context) { + // Used to record the names of the corresponding structs and member variables that are @consumer modified + let componentv2WithConsumer: MultiMap = new MultiMap(); + return { + parsed: (node): void => { + collectStructsWithConsumer(node, componentv2WithConsumer); + validateStructDecoratorsAndMembers(node, context); + validateProviderInClasses(node, context); + if (arkts.isCallExpression(node)) { + validateConsumerInitialization(node, componentv2WithConsumer, context); + } + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/index.ts b/arkui-plugins/ui-syntax-plugins/rules/index.ts index 391d52435..ecb2d9888 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/index.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/index.ts @@ -18,6 +18,7 @@ import { UISyntaxRule } from './ui-syntax-rule'; import BuildRootNode from './build-root-node'; import CheckConstructPrivateParameter from './check-construct-private-parameter'; import ComponentV2MixCheck from './componentV2-mix-check'; +import ConsumerProviderDecoratorCheck from './consumer-provider-decorator-check'; import CustomDialogMissingController from './custom-dialog-missing-controller'; import DecoratorsInUIComponentOnly from './decorators-in-ui-component-only'; import EntryLoacalStorageCheck from './entry-localstorage-check'; @@ -27,11 +28,23 @@ import NoDuplicateDecorators from './no-duplicate-decorators'; import NoDuplicateStateManager from './no-duplicate-state-manager'; import NoPropLinkObjectlinkInEntry from './no-prop-link-objectlink-in-entry'; import NoSameAsBuiltInAttribute from './no-same-as-built-in-attribute'; +import ReuseAttributeCheck from './reuse-attribute-check'; +import StructMissingDecorator from './struct-missing-decorator'; +import StructPropertyDecorator from './struct-property-decorator'; +import StructVariableInitialization from './struct-variable-initialization'; +import TrackDecoratorCheck from './track-decorator-check'; +import TypeDecoratorCheck from './type-decorator-check'; +import ValidateBuildInStruct from './validate-build-in-struct'; +import VariableInitializationViaComponentCons from './variable-initialization-via-component-cons'; +import WatchDecoratorFunction from './watch-decorator-function'; +import WatchDecoratorRegular from './watch-decorator-regular'; +import WrapBuilderCheck from './wrap-builder-check'; const rules: UISyntaxRule[] = [ BuildRootNode, CheckConstructPrivateParameter, ComponentV2MixCheck, + ConsumerProviderDecoratorCheck, CustomDialogMissingController, DecoratorsInUIComponentOnly, EntryLoacalStorageCheck, @@ -41,6 +54,17 @@ const rules: UISyntaxRule[] = [ NoDuplicateStateManager, NoPropLinkObjectlinkInEntry, NoSameAsBuiltInAttribute, + ReuseAttributeCheck, + StructMissingDecorator, + StructPropertyDecorator, + StructVariableInitialization, + TrackDecoratorCheck, + TypeDecoratorCheck, + ValidateBuildInStruct, + VariableInitializationViaComponentCons, + WatchDecoratorFunction, + WatchDecoratorRegular, + WrapBuilderCheck, ]; export default rules; diff --git a/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts b/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts new file mode 100644 index 000000000..773b133ac --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +import { PresetDecorators, getAnnotationUsage } from '../utils'; + +function findStructsWithReusableAndComponentV2(node: arkts.AstNode, reusableV2ComponentV2Struct: string[]): void { + //Go through all the children of Program + for (const childNode of node.getChildren()) { + // Check whether the type is struct + if (!arkts.isStructDeclaration(childNode)) { + continue; + } + // Check that the current component has @ComponentV2 and @ReusableV2 decorators + const hasReusableV2Decorator = getAnnotationUsage(childNode, PresetDecorators.REUSABLE_V2); + const hasComponentV2Decorator = getAnnotationUsage(childNode, PresetDecorators.COMPONENT_V2); + if (hasReusableV2Decorator && hasComponentV2Decorator) { + const struceName = childNode.definition?.ident?.name ?? ''; + reusableV2ComponentV2Struct.push(struceName); + } + } +} + +function validateReuseOrReuseIdUsage(context: UISyntaxRuleContext, node: arkts.MemberExpression, + reusableV2ComponentV2Struct: string[]): void { + const structNode = node.object; + // Gets the reuse or reuseId attribute + const decoratedNode = node.property; + if (arkts.isCallExpression(structNode)) { + const Node = structNode.expression; + if (decoratedNode.dumpSrc() === 'reuse' && !reusableV2ComponentV2Struct.includes(Node.dumpSrc())) { + reportInvalidReuseUsage(context, node, structNode, rule); + } + else if (decoratedNode.dumpSrc() === 'reuseId' && reusableV2ComponentV2Struct.includes(Node.dumpSrc())) { + reportInvalidReuseIdUsage(context, node, structNode, rule); + } + } +} + +function reportInvalidReuseUsage(context: UISyntaxRuleContext, node: arkts.AstNode, structNode: arkts.AstNode, + rule: any): void { + context.report({ + node: node, + message: rule.messages.invalidReuseUsage, + fix: (node) => { + const startPosition = arkts.getStartPosition(node); + const endPosition = arkts.getEndPosition(node); + return { + range: [startPosition, endPosition], + code: `${structNode.dumpSrc()}.reuseId`, + }; + }, + }); +} + +function reportInvalidReuseIdUsage(context: UISyntaxRuleContext, node: arkts.AstNode, structNode: arkts.AstNode, + rule: any): void { + context.report({ + node: node, + message: rule.messages.invalidReuseIdUsage, + fix: (node) => { + const startPosition = arkts.getStartPosition(node); + const endPosition = arkts.getEndPosition(node); + return { + range: [startPosition, endPosition], + code: `${structNode.dumpSrc()}.reuse`, + }; + }, + }); +} + +const rule: UISyntaxRule = { + name: 'reuse-attribute-check', + messages: { + invalidReuseUsage: `The reuse attribute is only applicable to custom components decorated with both @ComponentV2 and @ReusableV2.`, + invalidReuseIdUsage: `The reuseId attribute is not applicable to custom components decorated with both @ComponentV2 and @ReusableV2.`, + }, + setup(context) { + const reusableV2ComponentV2Struct: string[] = []; + return { + parsed: (node): void => { + // Check whether the type is "Program" + if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + findStructsWithReusableAndComponentV2(node, reusableV2ComponentV2Struct); + } + if (arkts.isMemberExpression(node)) { + validateReuseOrReuseIdUsage(context, node, reusableV2ComponentV2Struct); + } + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts new file mode 100644 index 000000000..7ca8e7b3a --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, PresetDecorators } from '../utils'; +import { UISyntaxRule } from './ui-syntax-rule'; + +const rule: UISyntaxRule = { + name: 'struct-missing-decorator', + messages: { + missingComponentDecorator: `struct '{{structName}}' is missing '@Component' or '@CustomDialog' decorators`, + misusedPreview: `struct '{{structName}}' misused '@Preview' decorator. it should be decorated by '@Component' or '@CustomDialog'`, + misusedObserved: `struct '{{structName}}' misused '@Observed' decorator. it should be decorated by '@Component' or '@CustomDialog'`, + }, + setup(context) { + function hasDecorator(node: arkts.StructDeclaration, decorator: string): boolean { + return !!getAnnotationUsage(node, decorator); + } + + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + // Check for the presence of specific decorators on the struct + const structName = node.definition.ident?.name ?? ''; + const structNode = node.definition.ident; + const hasComponent = hasDecorator(node, PresetDecorators.COMPONENT_V1); + const hasComponentV2 = hasDecorator(node, PresetDecorators.COMPONENT_V2); + const hasCustomDialog = hasDecorator(node, PresetDecorators.CUSTOM_DIALOG); + const hasPreview = getAnnotationUsage(node, PresetDecorators.PREVIEW); + const hasObserved = getAnnotationUsage(node, PresetDecorators.OBSERVED_V1); + // If no valid component decorators (@Component or @CustomDialog) are found + if (!hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { + context.report({ + node: structNode, + message: rule.messages.missingComponentDecorator, + data: { structName }, + }); + } + // If the @Preview decorator is used but the struct is not decorated with @Component or @CustomDialog + if (hasPreview && !hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { + context.report({ + node: structNode, + message: rule.messages.misusedPreview, + data: { structName }, + }); + } + // If the @Observed decorator is used but the struct is not decorated with @Component or @CustomDialog + if (hasObserved && !hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { + context.report({ + node: structNode, + message: rule.messages.misusedObserved, + data: { structName }, + }); + } + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts new file mode 100644 index 000000000..9aaa53de0 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getClassPropertyAnnotationNames } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function checkInvalidStaticPropertyDecorations(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { + node.definition.body.forEach((member) => { + // Errors are reported when the node type is ClassProperty, + if (arkts.isClassProperty(member)) { + const propertyNameNode = member.key; + if ((member.isStatic && getClassPropertyAnnotationNames(member).length > 0) && propertyNameNode) { + context.report({ + node: propertyNameNode, + message: rule.messages.invalidStaticUsage + }); + } + } + }); +} + +const rule: UISyntaxRule = { + name: 'struct-property-decorator', + messages: { + invalidStaticUsage: `Static variables in custom components cannot be decorated by built-in variable decorators.` + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + checkInvalidStaticPropertyDecorations(context, node); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-variable-initialization.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-variable-initialization.ts new file mode 100644 index 000000000..63c06587f --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/struct-variable-initialization.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +// A list of decorators that needs to be initialized locally +const mustInitializeDecorators = ['State', 'StorageLink', 'StorageProp', 'LocalStorageLink', 'LocalStorageProp', + 'Provide']; +// Disables a list of decorators that are initialized locally +const prohibitInitializeDecorators = ['Link', 'Consume', 'ObjectLink']; + +function reportVariablesInitializationError(context: UISyntaxRuleContext, node: arkts.ClassProperty): void { + // Check whether the value field exists and whether it has been initialized + const valueExists = !!node.value; + // Iterate through each decorator and verify the initialization rules + node.annotations.forEach(annotation => { + const decoratorName = annotation.expr?.dumpSrc() ?? ''; + if (mustInitializeDecorators.includes(decoratorName)) { + // If it is a decorator that needs to be initialized + if (!valueExists) { + // If there is no initialization expression and there is no @Require, an error is reported + context.report({ + node: annotation, + message: rule.messages.mustBeInitializedLocally, + }); + } + } else if (prohibitInitializeDecorators.includes(decoratorName)) { + // If it is a decorator that prohibits initialization + if (valueExists) { + // If an initialization expression exists, an error is reported + context.report({ + node: annotation, + message: rule.messages.prohibitLocalInitialization, + }); + } + } + }); +} + +const rule: UISyntaxRule = { + name: 'struct-variable-initialization', + messages: { + mustBeInitializedLocally: `Variables decorated by '@State', '@StorageLink', '@StorageProp', '@LocalStorageLink', '@LocalStorageProp' and '@Provide' must be initialized locally.`, + prohibitLocalInitialization: `Variables decorated by '@Link', '@Consume', and '@ObjectLink' cannot be initialized locally.` + }, + setup(context) { + return { + parsed: (node): void => { + // Check if the current node is a class attribute + if (!arkts.isClassProperty(node)) { + return; + } + reportVariablesInitializationError(context, node); + } + }; + } +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts new file mode 100644 index 000000000..db909687b --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +import { PresetDecorators } from '../utils/index'; + +const rule: UISyntaxRule = { + name: 'track-decorator-check', + messages: { + invalidTarget: `The '@Track' decorator can only be used on class member variables.`, + invalidClass: `The '@Track' decorator can only be used within a 'class' decorated with '@Observed'.` + }, + setup(context) { + return { + parsed: (node): void => { + if (arkts.isStructDeclaration(node)) { + checkInvalidTrackAnnotations(context, node); + } + // Check if the current node is a class declaration + if (arkts.isClassDeclaration(node)) { + checkTrackOnlyUsedWithObserved(context, node); + } + } + }; + } +}; + +function checkInvalidTrackAnnotations(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { + // Traverse all members of the struct body + node.definition.body.forEach((member) => { + // Check whether it is a member variable + if (arkts.isClassProperty(member)) { + const hasTrackDecorator = findClassPropertyAnnotation(member, PresetDecorators.TRACK); + // If a member variable is decorated with @Track, an error is reported immediately + if (hasTrackDecorator) { + reportInvalidTarget(context, hasTrackDecorator); + } + } + // Check whether this is the method + if (arkts.isMethodDefinition(member)) { + const hasTrackDecorator = getMethodAnnotation(member, PresetDecorators.TRACK); + // If the method is decorated with @Track, an error is reported immediately + if (hasTrackDecorator) { + reportInvalidTarget(context, hasTrackDecorator); + } + } + },); +} + +function checkTrackOnlyUsedWithObserved(context: UISyntaxRuleContext, node: arkts.ClassDeclaration): void { + // Check if the class is decorated with @Observed + const hasObservedDecorator = node.definition?.annotations?.find( + annotations => + annotations.expr && + arkts.isIdentifier(annotations.expr) && + annotations.expr.name === PresetDecorators.OBSERVED_V1 + ); + // Traverse all members of the body class + node.definition?.body.forEach((member) => { + // Check whether it is a class attribute + if (arkts.isClassProperty(member)) { + const hasTrackDecorator = findClassPropertyAnnotation(member, PresetDecorators.TRACK); + // If the class is not decorated with @Observed and has decorators, an error is reported + if (!hasObservedDecorator && hasTrackDecorator) { + reportInvalidClass(context, hasTrackDecorator); + } + } + // Check whether this is the method + if (arkts.isMethodDefinition(member)) { + const hasTrackDecorator = getMethodAnnotation(member, PresetDecorators.TRACK); + // If the method is decorated with @Track, an error is reported immediately + if (hasTrackDecorator) { + reportInvalidTarget(context, hasTrackDecorator); + } + } + }); +} + +function reportInvalidClass(context: UISyntaxRuleContext, hasTrackDecorator: arkts.AnnotationUsage): void { + context.report({ + node: hasTrackDecorator, + message: rule.messages.invalidClass, + fix: (hasTrackDecorator) => { + const startPosition = arkts.getStartPosition(hasTrackDecorator); + const endPosition = arkts.getEndPosition(hasTrackDecorator); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +function getMethodAnnotation( + node: arkts.MethodDefinition, + annotationName: string) + : arkts.AnnotationUsage | undefined { + return node.scriptFunction.annotations?.find( + annotation => + annotation.expr && + annotation.expr.dumpSrc() === annotationName + ); +} + +function findClassPropertyAnnotation( + node: arkts.ClassProperty, + annotationName: string) + : arkts.AnnotationUsage | undefined { + return node.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() === annotationName + ); +} + +function reportInvalidTarget( + context: UISyntaxRuleContext, + node: arkts.AnnotationUsage) + : void { + context.report({ + node: node, + message: rule.messages.invalidTarget, + fix: (node) => { + const startPosition = arkts.getStartPosition(node); + const endPosition = arkts.getEndPosition(node); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/type-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/type-decorator-check.ts new file mode 100644 index 000000000..79c60be2e --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/type-decorator-check.ts @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationName, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function findTypeDecorator( + annotations: readonly arkts.AnnotationUsage[] +): arkts.AnnotationUsage | undefined { + let hasTypeDecorator = annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() === PresetDecorators.TYPE + ); + return hasTypeDecorator; +} + +function hasDecoratorType( + node: arkts.ClassDeclaration, +): arkts.AnnotationUsage | undefined { + let hasTypeDecorator: arkts.AnnotationUsage | undefined; + node.definition?.body.forEach(member => { + if (arkts.isClassProperty(member) && member.annotations) { + hasTypeDecorator = findTypeDecorator(member.annotations); + } + }); + return hasTypeDecorator; +} + +// rule1: @Type can only be used for class +function checkTypeInStruct( + node: arkts.StructDeclaration, + context: UISyntaxRuleContext, +): void { + let hasTypeDecorator: arkts.AnnotationUsage | undefined; + node.definition?.body.forEach(member => { + if (arkts.isClassProperty(member) && member.annotations) { + hasTypeDecorator = findTypeDecorator(member.annotations); + reportInvalidTypeUsageInStruct(hasTypeDecorator, context); + } + }); +} + +function reportInvalidTypeUsageInStruct( + hasTypeDecorator: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + if (!hasTypeDecorator) { + return; + } + context.report({ + node: hasTypeDecorator, + message: rule.messages.invalidType, + fix: (hasTypeDecorator) => { + const startPosition = arkts.getStartPosition(hasTypeDecorator); + const endPosition = arkts.getEndPosition(hasTypeDecorator); + return { + range: [startPosition, endPosition], + code: '' + }; + } + }); +} + +// rule2: Conflict between @Type and @Observed +function checkObservedAndTypeConflict( + node: arkts.ClassDeclaration, + context: UISyntaxRuleContext +): void { + let hasTypeDecorator: arkts.AnnotationUsage | undefined; + node.definition?.annotations.forEach(member => { + const annotation = getAnnotationName(member); + hasTypeDecorator = hasDecoratorType(node); + if (annotation === PresetDecorators.OBSERVED_V1) { + reportObservedAndTypeDecoratorConflict(hasTypeDecorator, context); + } + }); +} + +function reportObservedAndTypeDecoratorConflict( + hasTypeDecorator: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + if (!hasTypeDecorator) { + return; + } + context.report({ + node: hasTypeDecorator, + message: rule.messages.invalidDecoratorWith, + fix: () => { + const startPosition = arkts.getStartPosition(hasTypeDecorator); + const endPosition = arkts.getEndPosition(hasTypeDecorator); + return { + range: [startPosition, endPosition], + code: '' + }; + } + }); +} + +// rule3: @TypeCannot be used for function members +function validateScriptFunctionForTypeDecorator( + node: arkts.ScriptFunction, + context: UISyntaxRuleContext +): void { + const hasTypeDecorator = findTypeDecorator(node.annotations); + reportInvalidTypeDecorator(hasTypeDecorator, context); +} + +function reportInvalidTypeDecorator( + hasTypeDecorator: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + if (!hasTypeDecorator) { + return; + } + context.report({ + node: hasTypeDecorator, + message: rule.messages.invalidTypeMember, + fix: (hasTypeDecorator) => { + const startPosition = arkts.getStartPosition(hasTypeDecorator); + const endPosition = arkts.getEndPosition(hasTypeDecorator); + return { + range: [startPosition, endPosition], + code: '' + }; + } + }); +} + +const rule: UISyntaxRule = { + name: 'type-decorator-check', + messages: { + invalidType: `The @Type decorator can only be used in 'class'.`, + invalidDecoratorWith: `The @Type decorator can not be used within a 'class' decorated with @Observed.`, + invalidTypeMember: `The @Type can decorate only member variables in a 'class'.` + }, + setup(context) { + return { + parsed: (node): void => { + // Check the decorator on the class + if (arkts.isClassDeclaration(node)) { + checkObservedAndTypeConflict(node, context); + } + if (arkts.isStructDeclaration(node)) { + checkTypeInStruct(node, context); + } + if (arkts.isScriptFunction(node) && node.annotations) { + validateScriptFunctionForTypeDecorator(node, context); + } + }, + }; + }, +}; +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts new file mode 100644 index 000000000..938c3a210 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getIdentifierName } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const NOT_PARAM_LENGTH: number = 0; +const BUILD_NAME: string = 'build'; +const BUILD_FUNCTION_COUNT_INI: number = 0; +const BUILD_FUNCTION_COUNT: number = 1; +const NOT_STATEMENT_LENGTH: number = 0; + +// rule1: Check if the build function contains arguments and report an error +function validateBuildFunctionParameters(buildFunction: arkts.MethodDefinition, context: UISyntaxRuleContext): void { + const paramsNodes = buildFunction.scriptFunction.params; + if (paramsNodes.length > NOT_PARAM_LENGTH) { + paramsNodes.forEach((param) => { + if (arkts.isEtsParameterExpression(param)) { + reportBuildParamNotAllowed(param, context); + } + }); + } +} + +// Report an error with an unallowed parameter in the build function +function reportBuildParamNotAllowed( + param: arkts.ETSParameterExpression, + context: UISyntaxRuleContext +): void { + context.report({ + node: param, + message: rule.messages.invalidComponet, + fix: (param) => { + const startPosition = arkts.getStartPosition(param); + const endPosition = arkts.getEndPosition(param); + return { + range: [startPosition, endPosition], + code: '' + }; + } + }); +} + +function validateConstructorForBuildFunction( + node: arkts.StructDeclaration, + member: arkts.MethodDefinition, + buildFunctionCount: number, + context: UISyntaxRuleContext +): void { + const blockStatement = member.scriptFunction.body; + if (!blockStatement || !arkts.isBlockStatement(blockStatement)) { + return; + } + const statements = blockStatement.statements; + const structName = node.definition.ident; + if (buildFunctionCount !== BUILD_FUNCTION_COUNT && + statements.length === NOT_STATEMENT_LENGTH) { + reportMissingBuildInStruct(structName, blockStatement, context); + } +} + +function reportMissingBuildInStruct( + structName: arkts.Identifier | undefined, + blockStatement: arkts.BlockStatement, + context: UISyntaxRuleContext +): void { + if (!structName) { + return; + } + context.report({ + node: structName, + message: rule.messages.invalidBuild, + fix: (structName) => { + const startPosition = arkts.getStartPosition(blockStatement); + const endPosition = startPosition; + return { + range: [startPosition, endPosition], + code: '{\nbuild {\n}' + }; + } + }); +} + +function validateBuild( + node: arkts.StructDeclaration, + buildFunctionCount: number, + context: UISyntaxRuleContext, +): void { + node.definition.body.forEach((member) => { + // Check if the member is defined for the method and the method name is 'build' + if (arkts.isMethodDefinition(member) && getIdentifierName(member.name) === BUILD_NAME) { + buildFunctionCount++; + validateBuildFunctionParameters(member, context); + } + // rule2: This rule validates the use of the 'build' function + if (arkts.isMethodDefinition(member) && + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR === member.kind) { + validateConstructorForBuildFunction(node, member, buildFunctionCount, context); + } + }); +} + +const rule: UISyntaxRule = { + name: 'validate-build-in-struct', + messages: { + invalidComponet: `A custom component can have only one 'build' function, which does not require parameters.`, + invalidBuild: `This rule validates the use of the 'build' function`, + }, + setup(context) { + return { + parsed: (node: arkts.AstNode): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + let buildFunctionCount: number = BUILD_FUNCTION_COUNT_INI; + validateBuild(node, buildFunctionCount, context); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-cons.ts b/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-cons.ts new file mode 100644 index 000000000..7660e6624 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-cons.ts @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getIdentifierName, getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +// Define a function to add property data to the property map +function addProperty(propertyMap: Map>, structName: string, + propertyName: string, annotationName: string): void { + if (!propertyMap.has(structName)) { + propertyMap.set(structName, new Map()); + } + const structProperties = propertyMap.get(structName); + if (structProperties) { + structProperties.set(propertyName, annotationName); + } +} +// categorizePropertyBasedOnAnnotations +function checkPropertyByAnnotations( + item: arkts.AstNode, + structName: string, + mustInitMap: Map>, + cannotInitMap: Map> = new Map(), + mustInitArray: string[][], + cannotInitArray: string[][] +): void { + if (!arkts.isClassProperty(item)) { + return; + } + const propertyName: string = item.key?.dumpSrc() ?? ''; + if (item.annotations.length === 0 || propertyName === '') { + return; + } + const annotationArray: string[] = getClassPropertyAnnotationNames(item); + // If the member variable is decorated, it is added to the corresponding map + mustInitArray.forEach(arr => { + if (arr.every(annotation => annotationArray.includes(annotation))) { + const annotationName: string = arr[0]; + addProperty(mustInitMap, structName, propertyName, annotationName); + } + }); + cannotInitArray.forEach(arr => { + if (arr.every(annotation => annotationArray.includes(annotation))) { + const annotationName: string = arr[0]; + addProperty(cannotInitMap, structName, propertyName, annotationName); + } + }); +} + +function initMap( + node: arkts.AstNode, + mustInitMap: Map>, + cannotInitMap: Map> = new Map(), + mustInitArray: string[][], + cannotInitArray: string[][] +): void { + if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + return; + } + node.getChildren().forEach((member) => { + if (!arkts.isStructDeclaration(member)) { + return; + } + const structName: string = member.definition.ident?.name ?? ''; + if (structName === '') { + return; + } + member.definition?.body.forEach((item) => { + checkPropertyByAnnotations(item, structName, mustInitMap, cannotInitMap, mustInitArray, cannotInitArray); + }); + }); +} + +function getChildKeyNameArray(member: arkts.AstNode): string[] { + const childkeyNameArray: string[] = []; + member.getChildren().forEach((property) => { + if (arkts.isProperty(property)) { + const childkeyName = property.key?.dumpSrc() ?? ''; + if (childkeyName !== '') { + childkeyNameArray.push(childkeyName); + } + } + }); + return childkeyNameArray; +} + +function checkMustInitialize( + node: arkts.AstNode, + context: UISyntaxRuleContext, + mustInitMap: Map> +): void { + if (!arkts.isIdentifier(node)) { + return; + } + const structName: string = getIdentifierName(node); + if (!mustInitMap.has(structName)) { + return; + } + const parentNode: arkts.AstNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + } + // Get all the properties of a record via StructName + const mustInitName: Map = mustInitMap.get(structName)!; + parentNode.arguments?.forEach((member) => { + const childkeyNameArray: string[] = getChildKeyNameArray(member); + mustInitName.forEach((value, key) => { + // If an attribute that must be initialized is not initialized, an error is reported + if (!childkeyNameArray.includes(key)) { + context.report({ + node: parentNode, + message: rule.messages.mustInitializeRule, + data: { + annotationName: value, + propertyName: key, + }, + }); + } + }); + }); +} + +function checkCannotInitialize( + node: arkts.AstNode, + context: UISyntaxRuleContext, + cannotInitMap: Map> +): void { + if (!arkts.isIdentifier(node)) { + return; + } + const structName: string = getIdentifierName(node); + if (!cannotInitMap.has(structName)) { + return; + } + const parentNode: arkts.AstNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + } + // Get all the properties of a record via StructName + const cannotInitName: Map = cannotInitMap.get(structName)!; + parentNode.arguments.forEach((member) => { + member.getChildren().forEach((property) => { + if (!arkts.isProperty(property)) { + return; + } + if (!property.key) { + return; + } + const propertyName = property.key.dumpSrc(); + // If a property that cannot be initialized is initialized, an error is reported + if (cannotInitName.has(propertyName)) { + context.report({ + node: property.key, + message: rule.messages.cannotInitializeRule, + data: { + annotationName: cannotInitName.get(propertyName)!, + propertyName: propertyName, + }, + }); + } + }); + }); +} + +const rule: UISyntaxRule = { + name: 'variable-initialization-via-component-cons', + messages: { + mustInitializeRule: `'@{{annotationName}}' decorated '{{propertyName}}' must be initialized through the component constructor.`, + cannotInitializeRule: `'@{{annotationName}}' decorated '{{propertyName}}' cannot be initialized through the component constructor.`, + }, + setup(context) { + let mustInitMap: Map> = new Map(); + let cannotInitMap: Map> = new Map(); + const mustInitArray: string[][] = [ + [PresetDecorators.REQUIRE, PresetDecorators.PROP], + [PresetDecorators.REQUIRE, PresetDecorators.BUILDER_PARAM], + [PresetDecorators.LINK], + [PresetDecorators.OBJECT_LINK] + ]; + const cannotInitArray: string[][] = [ + [PresetDecorators.STORAGE_LINK], + [PresetDecorators.STORAGE_PROP], + [PresetDecorators.CONSUME], + [PresetDecorators.LOCAL_STORAGE_LINK], + [PresetDecorators.LOCAL_STORAGE_PROP] + ]; + return { + parsed: (node): void => { + initMap(node, mustInitMap, cannotInitMap, mustInitArray, cannotInitArray); + checkMustInitialize(node, context, mustInitMap); + checkCannotInitialize(node, context, cannotInitMap); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts new file mode 100644 index 000000000..dae346a79 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getIdentifierName, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +// Gets the names of all methods in the struct +function getMethodNames(node: arkts.StructDeclaration): string[] { + const methodNames: string[] = []; + node.definition.body.forEach((member) => { + if (arkts.isMethodDefinition(member)) { + const methodName = getIdentifierName(member.name); + if (methodName) { + methodNames.push(methodName); + } + } + }); + return methodNames; +} + +// Invalid @Watch decorator bugs are reported +function reportInvalidWatch( + member: arkts.ClassProperty, + methodName: string, + hasWatchDecorator: arkts.AnnotationUsage, + context: UISyntaxRuleContext +): void { + context.report({ + node: hasWatchDecorator, + message: rule.messages.invalidWatch, + data: { methodName }, + fix: () => { + const startPosition = arkts.getEndPosition(member); + const endPosition = arkts.getEndPosition(member); + return { + range: [startPosition, endPosition], + code: `\n${methodName}(){\n}`, + }; + }, + }); +} + +function validateWatchDecorator( + member: arkts.ClassProperty, + methodNames: string[], + hasWatchDecorator: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + member.annotations.forEach((annotation) => { + validateWatchProperty(annotation, member, methodNames, hasWatchDecorator, context); + }); +} + +function validateWatchProperty( + annotation: arkts.AnnotationUsage, + member: arkts.ClassProperty, + methodNames: string[], + hasWatchDecorator: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + if ( + annotation.expr && + annotation.expr.dumpSrc() === PresetDecorators.WATCH + ) { + annotation.properties.forEach((element) => { + if (!arkts.isClassProperty(element)) { + return; + } + const methodName = element.value?.dumpSrc().slice(1, -1); + if (hasWatchDecorator && methodName && !methodNames.includes(methodName)) { + reportInvalidWatch(member, methodName, hasWatchDecorator, context); + } + }); + } + +} + +function validateWatch( + node: arkts.StructDeclaration, + methodNames: string[], + context: UISyntaxRuleContext +): void { + node.definition.body.forEach(member => { + if (!arkts.isClassProperty(member)) { + return; + } + const hasWatchDecorator = member.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() === PresetDecorators.WATCH + ); + // Determine whether it contains @watch decorators + validateWatchDecorator(member, methodNames, hasWatchDecorator, context); + }); +} + +const rule: UISyntaxRule = { + name: 'watch-decorator-function', + messages: { + invalidWatch: `The '@Watch' decorated parameter must be a callback '{{methodName}}' of a function in a custom component.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + // Get all method names + const methodNames = getMethodNames(node); + validateWatch(node, methodNames, context); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts new file mode 100644 index 000000000..22eb47c74 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const PROPERTY_ANNOTATION_NUM: number = 2; + +function validateWatchDecorator(node: arkts.StructDeclaration, context: UISyntaxRuleContext): void { + node.definition.body.forEach(member => { + if (!arkts.isClassProperty(member)) { + return; + } + const hasWatchDecorator = member.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() === PresetDecorators.WATCH + ); + const propertyAnnotationNames = getClassPropertyAnnotationNames(member); + // Determine if there are any decorations other than @watch decorations + // rule1: The @Watch decorator must be used with other decorators + if (hasWatchDecorator && propertyAnnotationNames.length < PROPERTY_ANNOTATION_NUM) { + context.report({ + node: hasWatchDecorator, + message: rule.messages.invalidWatch, + }); + } + }); +} + +const rule: UISyntaxRule = { + name: 'watch-decorator-regular', + messages: { + invalidWatch: `The @Watch decorator must be used with other decorators.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + validateWatchDecorator(node, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts b/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts new file mode 100644 index 000000000..5f87ef3fc --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getIdentifierName, getAnnotationName, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const WRAPBUILDER_NAME: string = 'wrapBuilder'; +// Collect all the function names that are decorated with @Builder +function collectBuilderFunctions(node: arkts.EtsScript, builderFunctionNames: string[]): void { + node.statements.forEach((statement) => { + if (!arkts.isFunctionDeclaration(statement)) { + return; + } + const annotations = statement.annotations; + if (!annotations) { + return; + } + annotations.forEach((annotation) => { + const decoratorName = getAnnotationName(annotation); + // Find all the functions that are decorated with @Builder and note their names + if (!decoratorName.includes(PresetDecorators.BUILDER)) { + return; + } + const functionName = statement.scriptFunction.id?.name; + if (!functionName || builderFunctionNames.includes(functionName)) { + return; + } + builderFunctionNames.push(functionName); + }); + }); +} + +// Verify that the wrapBuilder's arguments are decorated with @Builder +function validateWrapBuilderArguments( + member: arkts.ClassProperty, + context: UISyntaxRuleContext, + builderFunctionNames: string[] +): void { + member.getChildren().forEach((child) => { + if (!arkts.isCallExpression(child) || child.expression.dumpSrc() !== WRAPBUILDER_NAME) { + return; + } + let functionName: string | undefined; + child.arguments.forEach(firstArgument => { + if (arkts.isMemberExpression(firstArgument)) { + functionName = getIdentifierName(firstArgument.property); + } else if (arkts.isIdentifier(firstArgument)) { + functionName = firstArgument.name; + } + // Verify that wrapBuilder's arguments are decorated with @Builder + // rule1: The wrapBuilder accepts only a function decorated by '@Builder' + if (functionName && !builderFunctionNames.includes(functionName)) { + context.report({ + node: firstArgument, + message: rule.messages.invalidBuilderCheck, + }); + } + }); + }); +} + +function validateWrapBuilder( + node: arkts.StructDeclaration, + builderFunctionNames: string[], + context: UISyntaxRuleContext +): void { + node.definition.body.forEach(member => { + if (!arkts.isClassProperty(member)) { + return; + } + validateWrapBuilderArguments(member, context, builderFunctionNames); + }); +} + +const rule: UISyntaxRule = { + name: 'wrap-builder-check', + messages: { + invalidBuilderCheck: 'The wrapBuilder accepts only a function decorated by @Builder.', + }, + setup(context) { + let builderFunctionNames: string[] = []; + return { + parsed: (node): void => { + if (arkts.isEtsScript(node)) { + collectBuilderFunctions(node, builderFunctionNames); + } + if (!arkts.isStructDeclaration(node)) { + return; + } + validateWrapBuilder(node, builderFunctionNames, context); + }, + }; + }, +}; + +export default rule; -- Gitee From 1010701b262c61b0875f77cee5541fb34704b81e Mon Sep 17 00:00:00 2001 From: y00896775 Date: Sat, 12 Apr 2025 19:46:32 +0800 Subject: [PATCH 082/123] update bindable compatibility Signed-off-by: y00896775 Change-Id: I7bfab8212067fe740eadc04c48735546318186f9 --- arkui-plugins/common/predefines.ts | 3 +- .../builder-lambda-translators/factory.ts | 148 +++++++++++++++++- .../builder-lambda-translators/utils.ts | 101 +++++++++++- koala-wrapper/src/arkts-api/index.ts | 1 + 4 files changed, 247 insertions(+), 6 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 510f03fc5..d4667b424 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -38,7 +38,7 @@ export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ ]; export const IMPORT_SOURCE_MAP: Map> = new Map>([ - ['@ohos.arkui.component', new Set(['$r', '$rawfile', '_r', '_rawfile'])], + ['@ohos.arkui.component', new Set(['$r', '$rawfile', '_r', '_rawfile', 'Bindable'])], [ '@ohos.arkui.stateManagement', new Set([ @@ -99,6 +99,7 @@ export const OUTPUT_DEPENDENCY_MAP: Map = new Map `Radio().checked({value: xxx, onChange: xxx})`. + */ + static updateBindableStyleArguments(bindableArg: arkts.Expression): arkts.Expression { + const valueType: arkts.TypeNode = getDecalTypeFromValue(bindableArg); + const objExp: arkts.ObjectExpression = arkts.factory.createObjectExpression( + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + [factory.generateValueProperty(bindableArg), factory.generateOnChangeArrowFunc(bindableArg, valueType)], + false + ); + return arkts.factory.createTSAsExpression( + objExp, + factory.createBindableType(valueType), + false + ); + } + /* * create style instance call, e.g. `instance.margin(10)`. */ static createStyleLambdaBody(lambdaBody: arkts.AstNode, call: arkts.CallExpression): arkts.CallExpression { + const newArgs: arkts.Expression[] = factory.getTransformedStyle(call); return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( lambdaBody, @@ -79,7 +125,7 @@ export class factory { false ), undefined, - call.arguments.map((arg) => { + newArgs.map((arg) => { if (arkts.isArrowFunctionExpression(arg)) { return this.processArgArrowFunction(arg); } @@ -188,9 +234,9 @@ export class factory { func, !!func.body && arkts.isBlockStatement(func.body) ? arkts.factory.updateBlock( - func.body, - func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st)) - ) + func.body, + func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st)) + ) : undefined, arkts.FunctionSignature.createFunctionSignature( func.typeParams, @@ -245,6 +291,19 @@ export class factory { currentStructInfo: arkts.StructInfo, properties: arkts.Property[] ): void { + const decl = prop.key ? arkts.getDecl(prop.key) : undefined; + if (decl && arkts.isMethodDefinition(decl)) { + const type: arkts.TypeNode | undefined = decl.scriptFunction.returnTypeAnnotation; + if ( + type && + hasBindableProperty(type, BindableDecl.BINDABLE) && + arkts.isProperty(prop) && + prop.value && + isDoubleDollarCall(prop.value) + ) { + properties[index] = factory.updateBindableProperty(prop); + } + } if ( !!prop.key && !!prop.value && @@ -444,4 +503,85 @@ export class factory { const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo); return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); } + + /* + * update bindableProperty, e.g. `text: $$(this.text)` => `text: { value: xxx , onChange: xxx }`. + */ + static updateBindableProperty(prop: arkts.Property, type?: arkts.TypeNode): arkts.Property { + let res: arkts.Property[] = []; + let valueType: arkts.TypeNode; + if ( + prop.value && + arkts.isCallExpression(prop.value) && + prop.value.arguments && + prop.value.arguments.length === 1 + ) { + let bindableArg = prop.value.arguments[0]; + valueType = getDecalTypeFromValue(bindableArg); + res.push( + factory.generateValueProperty(bindableArg), + factory.generateOnChangeArrowFunc(bindableArg, valueType) + ); + } else { + return prop; + } + const asObjProp: arkts.TSAsExpression = arkts.factory.createTSAsExpression( + arkts.ObjectExpression.createObjectExpression( + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + res, + false + ), + factory.createBindableType(valueType), + false + ); + return arkts.factory.updateProperty(prop, prop.key, asObjProp); + } + + /* + * generate `value: ` in object. + */ + static generateValueProperty(bindableArg: arkts.Expression): arkts.Property { + return arkts.factory.createProperty(arkts.factory.createIdentifier('value'), bindableArg.clone()); + } + + /* + * generate `onChange: (value) => = value` in object. + */ + static generateOnChangeArrowFunc(bindableArg: arkts.Expression, valueType: arkts.TypeNode): arkts.Property { + return arkts.factory.createProperty( + arkts.factory.createIdentifier('onChange'), + PropertyFactory.createArrowFunctionWithParamsAndBody( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('value', valueType.clone()), + undefined + ), + ], + undefined, + false, + [ + arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + bindableArg.clone(), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + arkts.factory.createIdentifier('value') + ) + ), + ] + ) + ); + } + + /* + * generate `Bindable`. + */ + static createBindableType(valueType: arkts.TypeNode): arkts.ETSTypeReference { + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(BindableDecl.BINDABLE), + arkts.factory.createTSTypeParameterInstantiation([valueType.clone()]) + ) + ); + } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index 0f3f2fa92..248599783 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -15,7 +15,7 @@ import * as arkts from '@koalaui/libarkts'; import { isAnnotation } from '../../common/arkts-utils'; -import { BuilderLambdaNames } from '../utils'; +import { BuilderLambdaNames, Dollars } from '../utils'; export type BuilderLambdaDeclInfo = { isFunctionCall: boolean; // isFunctionCall means it is from $_instantiate. @@ -23,6 +23,10 @@ export type BuilderLambdaDeclInfo = { returnType: arkts.TypeNode | undefined; }; +export enum BindableDecl { + BINDABLE = 'Bindable', +} + export type BuilderLambdaAstNode = arkts.ScriptFunction | arkts.ETSParameterExpression | arkts.FunctionDeclaration; /** @@ -309,3 +313,98 @@ export function builderLambdaFunctionName(node: arkts.CallExpression): string | } return undefined; } + +/** + * Determine whether the node `` is `` bindable property. + * + * @param type type node + * @param bindableDecl bindable decalaration name + */ +export function hasBindableProperty(type: arkts.AstNode, bindableDecl: BindableDecl): boolean { + let res: boolean = false; + if (arkts.isETSUnionType(type)) { + type.types.forEach((item: arkts.TypeNode) => { + res = res || hasBindableProperty(item, bindableDecl); + }); + } + if (arkts.isETSTypeReference(type)) { + res = + res || + (!!type.part && + !!type.part.name && + arkts.isIdentifier(type.part.name) && + type.part.name.name === bindableDecl); + } + + return res; +} + +/** + * Determine whether `` is `$$()` call expression node. + * + * @param value expression node + */ +export function isDoubleDollarCall(value: arkts.Expression): boolean { + if ( + arkts.isCallExpression(value) && + value.expression && + arkts.isIdentifier(value.expression) && + value.expression.name + ) { + return value.expression.name === Dollars.DOLLAR_DOLLAR; + } + return false; +} + +/** + * get declaration type from `{xxx: }` or `fun()`. + * + * @param value type node + */ +export function getDecalTypeFromValue(value: arkts.Expression): arkts.TypeNode { + const decl: arkts.AstNode | undefined = arkts.getDecl(value); + if (!decl || !arkts.isClassProperty(decl)) { + throw new Error('cannot get declaration'); + } + if (isArrayType(decl.typeAnnotation!)) { + return getElementTypeFromArray(decl.typeAnnotation!)!; + } + return decl.typeAnnotation!; +} + +/** + * Determine whether `` is array type, e.g. `xxx[]` or `Array`. + * + * @param type type node + */ +export function isArrayType(type: arkts.TypeNode): boolean { + return ( + arkts.isTSArrayType(type) || + (arkts.isETSTypeReference(type) && + !!type.part && + arkts.isETSTypeReferencePart(type.part) && + !!type.part.name && + arkts.isIdentifier(type.part.name) && + type.part.name.name === 'Array') + ); +} + +/** + * get element type from array type node ``. + * + * @param arrayType array type node + */ +export function getElementTypeFromArray(arrayType: arkts.TypeNode): arkts.TypeNode | undefined { + if (arkts.isTSArrayType(arrayType)) { + return arrayType.elementType?.clone(); + } else if ( + arkts.isETSTypeReference(arrayType) && + !!arrayType.part && + arkts.isETSTypeReferencePart(arrayType.part) && + !!arrayType.part.typeParams && + arrayType.part.typeParams.params.length + ) { + return arrayType.part.typeParams.params[0].clone(); + } + return undefined; +} diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index ad1378dd9..c8b9fcb70 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -58,6 +58,7 @@ export * from "../generated/peers/Property" export * from "../generated/peers/BlockExpression" export * from "../generated/peers/TSClassImplements" export * from "../generated/peers/BooleanLiteral" +export * from "../generated/peers/TSArrayType" export * from "./types" export * from "./utilities/private" -- Gitee From 11c1ff6b236d4d410cecf3ed0d764e4e1a24c1c8 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 7 May 2025 17:38:28 +0800 Subject: [PATCH 083/123] use safe type in new style params Signed-off-by: Jiakai Shi Change-Id: Ib1b869df4d67da99557166d0a7e459e651f5b418 --- .../method-declarations/internal-calls.test.ts | 2 +- .../builder-lambda-translators/factory.ts | 7 ++++--- .../builder-lambda-translators/utils.ts | 16 ++++++++-------- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts index e85c7ccc7..ffaeaf4b1 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts @@ -101,7 +101,7 @@ class Test { if (__memo_scope.unchanged) { return __memo_scope.cached; } - return __memo_scope.recache(((123) + (x))); + return __memo_scope.recache(((123) + (__memo_parameter_x.value))); }); const h = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): number => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index f9784e560..ab58a0170 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -26,6 +26,7 @@ import { findBuilderLambdaDeclInfo, isBuilderLambda, isBuilderLambdaFunctionCall, + isSafeType, replaceBuilderLambdaDeclMethodName, } from './utils'; import { DecoratorNames } from '../property-translators/utils'; @@ -112,9 +113,9 @@ export class factory { if (!lambdaBody) { return arkts.factory.createUndefinedLiteral(); } - + const safeType: arkts.TypeNode | undefined = isSafeType(typeNode) ? typeNode : undefined; const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, typeNode), + arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, safeType), undefined ); @@ -442,6 +443,6 @@ export class factory { } const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo); - return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); + return arkts.factory.updateCallExpression(node, replace, leaf.typeArguments, filterDefined(args)); } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index 0f3f2fa92..6179a6776 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -259,15 +259,15 @@ export function callIsGoodForBuilderLambda(leaf: arkts.CallExpression): boolean return arkts.isIdentifier(node) || arkts.isMemberExpression(node); } -export function builderLambdaType(leaf: arkts.CallExpression): arkts.TypeNode | undefined { - const name: string | undefined = builderLambdaTypeName(leaf); - if (!name) { - return undefined; +export function isSafeType(type: arkts.TypeNode | undefined): boolean { + if (!type) { + return false; } - // TODO: it should be the return type of the function annotated with the @BuilderLambda - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(`${name}Attribute`)) - ); + // type can be generic (not safe) if includes any type params in a type reference. + if (arkts.isETSTypeReference(type) && !!type.part && !!type.part.typeParams) { + return false; + } + return true; } export function builderLambdaMethodDeclType(method: arkts.MethodDefinition): arkts.TypeNode | undefined { -- Gitee From 9c4833e924d63ac195c8d7690aec10ce358d438e Mon Sep 17 00:00:00 2001 From: Keerecles Date: Thu, 8 May 2025 23:01:32 +0800 Subject: [PATCH 084/123] comfile abc template Signed-off-by: Keerecles Change-Id: I0c68f6053a5499ab9b244e73d091988d042d0806 --- arkui-plugins/BUILD.gn | 9 +++++++++ koala-wrapper/BUILD.gn | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/arkui-plugins/BUILD.gn b/arkui-plugins/BUILD.gn index a262ea4c0..ef1316286 100755 --- a/arkui-plugins/BUILD.gn +++ b/arkui-plugins/BUILD.gn @@ -12,6 +12,7 @@ # limitations under the License. import("//build/ohos.gni") +import("//build/config/components/ets_frontend/ets2abc_config.gni") npm_path = "//prebuilts/build-tools/common/nodejs/current/bin/npm" @@ -41,3 +42,11 @@ ohos_copy("ui_plugin") { subsystem_name = "developtools" part_name = "ace_ets2bundle" } + +ohos_copy("ohos_ets_ui_plugins") { + deps = [ ":gen_ui_plugins" ] + sources = [ rebase_path("$target_gen_dir") ] + outputs = [ ohos_ets_ui_plugins_path ] + subsystem_name = "developtools" + part_name = "ace_ets2bundle" +} \ No newline at end of file diff --git a/koala-wrapper/BUILD.gn b/koala-wrapper/BUILD.gn index d9ad69899..58807818d 100644 --- a/koala-wrapper/BUILD.gn +++ b/koala-wrapper/BUILD.gn @@ -12,6 +12,7 @@ # limitations under the License. import("//build/ohos.gni") +import("//build/config/components/ets_frontend/ets2abc_config.gni") npm_path = "//prebuilts/build-tools/common/nodejs/current/bin/npm" @@ -43,3 +44,11 @@ ohos_copy("ets2panda_koala_wrapper") { subsystem_name = "developtools" part_name = "ace_ets2bundle" } + +ohos_copy("ohos_ets_koala_wrapper") { + deps = [ ":gen_sdk_ts_wrapper" ] + sources = [ rebase_path("$target_gen_dir") ] + outputs = [ ohos_ets_koala_wrapper_path ] + subsystem_name = "developtools" + part_name = "ace_ets2bundle" +} \ No newline at end of file -- Gitee From a42d88d85ae5c8169c2f96bc149ade37333e5bae Mon Sep 17 00:00:00 2001 From: fengyuxin Date: Sun, 27 Apr 2025 11:38:35 +0800 Subject: [PATCH 085/123] animation transform Signed-off-by: fengyuxin Change-Id: I56a357523f0a69b93c1a385f27725ac35b78bd52 --- .../demo/mock/animation/animation-basic.ets | 17 +++ .../animation/animation-basic.test.ts | 121 ++++++++++++++++++ .../builder-lambda-translators/factory.ts | 31 +++++ .../ui-plugins/checked-transformer.ts | 13 +- .../ui-plugins/struct-translators/factory.ts | 61 ++++++++- arkui-plugins/ui-plugins/utils.ts | 3 + 6 files changed, 242 insertions(+), 4 deletions(-) create mode 100644 arkui-plugins/test/demo/mock/animation/animation-basic.ets create mode 100644 arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts diff --git a/arkui-plugins/test/demo/mock/animation/animation-basic.ets b/arkui-plugins/test/demo/mock/animation/animation-basic.ets new file mode 100644 index 000000000..35c26e459 --- /dev/null +++ b/arkui-plugins/test/demo/mock/animation/animation-basic.ets @@ -0,0 +1,17 @@ +import { Text, Column, Component, Color, Curve } from "@ohos.arkui.component" +import { Entry } from "@ohos.arkui.component" + +@Entry +@Component +struct AnimatablePropertyExample { + build() { + Column() { + Text("AnimatableProperty") + .backgroundColor(Color.Red) + .animation({ duration: 2000, curve: Curve.Ease }) + .fontSize(20) + .animation({ duration: 2000, curve: Curve.Ease }) + .width("100%") + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts new file mode 100644 index 000000000..732dd8d69 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { uiNoRecheck } from '../../../utils/plugins'; +import { uiTransform } from '../../../../ui-plugins'; +import { Plugins } from '../../../../common/plugin-context'; + +const ANIMATION_DIR_PATH: string = 'animation'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, ANIMATION_DIR_PATH, 'animation-basic.ets'), +]; + +const animationTransform: Plugins = { + name: 'animation', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test basic animation transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; + +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Text as Text, Column as Column, Component as Component, Color as Color, Curve as Curve } from "@ohos.arkui.component"; + +import { Entry as Entry } from "@ohos.arkui.component"; + +function main() {} + + + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class AnimatablePropertyExample extends CustomComponent { + public __initializeStruct(initializers: __Options_AnimatablePropertyExample | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_AnimatablePropertyExample | undefined): void {} + + @memo() public _build(@memo() style: ((instance: AnimatablePropertyExample)=> AnimatablePropertyExample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_AnimatablePropertyExample | undefined): void { + Column(undefined, undefined, (() => { + Text(@memo() ((instance: UITextAttribute): void => { + instance.animationStart({ + duration: 2000, + curve: Curve.Ease, + }).backgroundColor(Color.Red).animationStop({ + duration: 2000, + curve: Curve.Ease, + }).animationStart({ + duration: 2000, + curve: Curve.Ease, + }).fontSize(20).animationStop({ + duration: 2000, + curve: Curve.Ease, + }).width("100%"); + return; + }), "AnimatableProperty", undefined, undefined); + })); + } + + public constructor() {} + +} + +interface __Options_AnimatablePropertyExample { + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + AnimatablePropertyExample._instantiateImpl(undefined, (() => { + return new AnimatablePropertyExample(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} +`; + +function testAnimationTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test observed only transform', + [animationTransform, uiNoRecheck], + { + checked: [testAnimationTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index f9784e560..49879b3ff 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -405,6 +405,36 @@ export class factory { ).setOverloads(newOverloads); } + /** + * transform `.animation(...)` to `.animationStart(...) and .animationStop(...)` + */ + static updateAnimation(instanceCalls: arkts.CallExpression[]): void { + let lastAniIdx = 0; + let curIdx = 0; + + while (curIdx < instanceCalls.length) { + const property: arkts.Identifier = instanceCalls[curIdx].expression as arkts.Identifier; + if (property.name === BuilderLambdaNames.ANIMATION_NAME) { + const aniStart: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier(BuilderLambdaNames.ANIMATION_START), + undefined, + instanceCalls[curIdx].arguments + ); + const aniStop: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier(BuilderLambdaNames.ANIMATION_STOP), + undefined, + instanceCalls[curIdx].arguments.map((arg)=>arg.clone()) + ); + instanceCalls.splice(lastAniIdx, 0, aniStart); + instanceCalls[curIdx + 1] = aniStop; + curIdx += 2; + lastAniIdx = curIdx; + } else { + curIdx++; + } + } + } + /** * transform `@ComponentBuilder` in non-declared calls. */ @@ -435,6 +465,7 @@ export class factory { let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; if (instanceCalls.length > 0) { instanceCalls = instanceCalls.reverse(); + this.updateAnimation(instanceCalls); lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); instanceCalls.forEach((call) => { lambdaBody = this.createStyleLambdaBody(lambdaBody!, call); diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 08c246d38..ff99c5843 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -26,7 +26,6 @@ import { getCustomComponentOptionsName, getTypeNameFromTypeParameter, getTypeParamsFromClassDecl, - BuilderLambdaNames, getGettersFromClassDecl, addMemoAnnotation, } from './utils'; @@ -114,13 +113,20 @@ export class CheckedTransformer extends AbstractVisitor { return transformResource(node, this.projectConfig); } else if (findCanAddMemoFromArrowFunction(node)) { return addMemoAnnotation(node); - } - else if (arkts.isClassDeclaration(node)) { + } else if (arkts.isClassDeclaration(node)) { return transformObservedTracked(node); + } else if ( + this.externalSourceName === 'arkui.component.common' && + arkts.isTSInterfaceDeclaration(node) && + !!node.id && + node.id.name === 'UICommonMethod' + ) { + return structFactory.modifyExternalComponentCommon(node); } return node; } } + export type ClassScopeInfo = { isObserved: boolean; classHasTrack: boolean; @@ -468,3 +474,4 @@ function transformResource( ]; return structFactory.generateTransformedResource(resourceNode, newArgs); } + diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index 2f07870cd..ac0144dcc 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -14,7 +14,7 @@ */ import * as arkts from '@koalaui/libarkts'; -import { CustomComponentNames, Dollars } from '../utils'; +import { BuilderLambdaNames, CustomComponentNames, Dollars } from '../utils'; import { factory as uiFactory } from '../ui-factory'; import { annotation } from '../../common/arkts-utils'; @@ -274,4 +274,63 @@ export class factory { arkts.classDefinitionFlags(definition) ); } + + /* + * add headers for animation in UICommonMethod + */ + static modifyExternalComponentCommon(node: arkts.TSInterfaceDeclaration): arkts.AstNode { + const animationStart = factory.createAnimationMethod(BuilderLambdaNames.ANIMATION_START); + const animationStop = factory.createAnimationMethod(BuilderLambdaNames.ANIMATION_STOP); + const updatedBody = arkts.factory.updateInterfaceBody(node.body!, [ + animationStart, + animationStop, + ...node.body!.body, + ]); + return arkts.factory.updateInterfaceDeclaration( + node, + node.extends, + node.id, + node.typeParams, + updatedBody, + node.isStatic, + node.isFromExternal + ); + } + + /* + * generate animationStart(...) and animationStop(...) + */ + static createAnimationMethod(key: string): arkts.MethodDefinition { + const aniparams: arkts.Expression[] = [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + 'value', + arkts.factory.createUnionType( + [ + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('AnimateParam')) + ), + arkts.factory.createETSUndefinedType() + ] + ) + ), + undefined + ), + ]; + const aniFuncExpr = arkts.factory.createFunctionExpression( + arkts.factory.createScriptFunction( + undefined, + arkts.factory.createFunctionSignature(undefined, aniparams, arkts.TSThisType.createTSThisType(), false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ) + ); + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + arkts.factory.createIdentifier(key), + aniFuncExpr, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + } } diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index c8a56dd06..73a22180b 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -42,6 +42,9 @@ export enum BuilderLambdaNames { STYLE_PARAM_NAME = 'style', STYLE_ARROW_PARAM_NAME = 'instance', CONTENT_PARAM_NAME = 'content', + ANIMATION_NAME = 'animation', + ANIMATION_START = 'animationStart', + ANIMATION_STOP = 'animationStop', } export enum Dollars { -- Gitee From d62fe89b3b846ec257907a7084ecfb5c5576a397 Mon Sep 17 00:00:00 2001 From: xuhangqi Date: Fri, 9 May 2025 11:52:46 +0800 Subject: [PATCH 086/123] Fix append evoDeclFilePath error Issue: https://gitee.com/openharmony/developtools_ace_ets2bundle/issues/IC6IZ4 Signed-off-by: xuhangqi Change-Id: I6a6fd91d538966a4783ac672b27d8b41adf16dd5 --- compiler/src/pre_define.ts | 1 + compiler/src/process_arkts_evolution.ts | 16 ++++++++-------- .../test/ark_compiler_ut/ets_checker.test.ts | 6 +++--- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/compiler/src/pre_define.ts b/compiler/src/pre_define.ts index 086fdd19e..5da8a4c27 100644 --- a/compiler/src/pre_define.ts +++ b/compiler/src/pre_define.ts @@ -648,3 +648,4 @@ export const INTEGRATED_HSP: string = 'integratedHsp'; export const ARKTS_1_2: string = '1.2'; export const ARKTS_1_1: string = '1.1'; +export const ARKTS_1_0: string = '1.0'; \ No newline at end of file diff --git a/compiler/src/process_arkts_evolution.ts b/compiler/src/process_arkts_evolution.ts index 79916f7cd..3fc8560b7 100644 --- a/compiler/src/process_arkts_evolution.ts +++ b/compiler/src/process_arkts_evolution.ts @@ -20,6 +20,7 @@ import ts from 'typescript'; import { EXTNAME_ETS, EXTNAME_D_ETS, + ARKTS_1_0, ARKTS_1_1, ARKTS_1_2 } from './pre_define'; @@ -98,23 +99,22 @@ export function getArkTSEvoDeclFilePath(resolvedFileInfo: ResolvedFileInfo): str for (const [pkgName, arkTSEvolutionModuleInfo] of arkTSEvolutionModuleMap) { const declgenV1OutPath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenV1OutPath); const modulePath: string = toUnixPath(arkTSEvolutionModuleInfo.modulePath); - const moduleName: string = arkTSEvolutionModuleInfo.moduleName; const declgenBridgeCodePath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenBridgeCodePath); if (resolvedFileName && resolvedFileName.startsWith(modulePath + '/') && !resolvedFileName.startsWith(declgenBridgeCodePath + '/')) { arktsEvoDeclFilePath = resolvedFileName - .replace(modulePath, toUnixPath(path.join(declgenV1OutPath, moduleName))) + .replace(modulePath, toUnixPath(path.join(declgenV1OutPath, pkgName))) .replace(EXTNAME_ETS, EXTNAME_D_ETS); break; } - if (moduleRequest === moduleName) { - arktsEvoDeclFilePath = path.join(declgenV1OutPath, moduleName, 'Index.d.ets'); + if (moduleRequest === pkgName) { + arktsEvoDeclFilePath = path.join(declgenV1OutPath, pkgName, 'Index.d.ets'); break; } - if (moduleRequest.startsWith(moduleName + '/')) { + if (moduleRequest.startsWith(pkgName + '/')) { arktsEvoDeclFilePath = moduleRequest.replace( - moduleName, - toUnixPath(path.join(declgenV1OutPath, moduleName, 'src/main/ets')) + pkgName, + toUnixPath(path.join(declgenV1OutPath, pkgName, 'src/main/ets')) ) + EXTNAME_D_ETS; break; } @@ -139,7 +139,7 @@ export function collectArkTSEvolutionModuleInfo(share: Object): void { share.throwArkTsCompilerError(red, 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + `Error Message: Failed to collect arkTs evolution module "${pkgName}" info from rollup.`, reset); } - } else if (dependentModuleInfo.language === ARKTS_1_1) { + } else if (dependentModuleInfo.language === ARKTS_1_1 || dependentModuleInfo.language === ARKTS_1_0) { if (dependentModuleInfo.declgenV2OutPath && dependentModuleInfo.declFilesPath) { arkTSModuleMap.set(pkgName, dependentModuleInfo); } else { diff --git a/compiler/test/ark_compiler_ut/ets_checker.test.ts b/compiler/test/ark_compiler_ut/ets_checker.test.ts index 0a143534d..6d5786792 100644 --- a/compiler/test/ark_compiler_ut/ets_checker.test.ts +++ b/compiler/test/ark_compiler_ut/ets_checker.test.ts @@ -274,9 +274,9 @@ mocha.describe('test ets_checker file api', function () { mocha.it('2-3: test resolveModuleNames parse the 1.2 module declaration file that the 1.1 module depends on', function () { const moduleNames: string[] = ['testhar/src/main/ets/test']; - arkTSEvolutionModuleMap.set('har', { + arkTSEvolutionModuleMap.set('testharPkg', { language: '1.2', - packageName: 'testhar', + packageName: 'testharPkg', moduleName: 'testhar', modulePath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar`, declgenV1OutPath: `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/build/default/intermediates/declgen/default/declgenV1`, @@ -284,7 +284,7 @@ mocha.describe('test ets_checker file api', function () { }) const filePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/${DEFAULT_ENTRY}/src/main/entryability/test.ets`; const arktsEvoTestFilePath: string = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/testhar/src/main/ets/test.ets`; - const arktsEvoTestDeclFilePath: string = `${arkTSEvolutionModuleMap.get('har').declgenV1OutPath}/testhar/src/main/ets/test.d.ets`; + const arktsEvoTestDeclFilePath: string = `${arkTSEvolutionModuleMap.get('testharPkg').declgenV1OutPath}/testharPkg/src/main/ets/test.d.ets`; const resolveModuleNameStub = sinon.stub(ts, 'resolveModuleName').returns({ resolvedModule: { resolvedFileName: arktsEvoTestFilePath, -- Gitee From a41b2d2e0ec8f44d253511c40e825bce31d57393 Mon Sep 17 00:00:00 2001 From: wangweiyuan Date: Tue, 29 Apr 2025 20:32:50 +0800 Subject: [PATCH 087/123] add ui-syntax-plugins(27/51) Signed-off-by: wangweiyuan --- .../check-construct-private-parameter.ts | 15 +- .../rules/check-decorated-property-type.ts | 77 +++++++ .../component-componentV2-mix-use-check.ts | 177 ++++++++++++++++ .../componentV2-state-usage-validation.ts | 168 +++++++++++++++ .../rules/construct-parameter-literal.ts | 112 ++++++++++ .../ui-syntax-plugins/rules/index.ts | 31 ++- .../rules/monitor-decorator-check.ts | 174 ++++++++++++++++ .../rules/nested-relationship.ts | 191 ++++++++++++++++++ .../rules/no-child-in-button.ts | 89 ++++++++ .../rules/no-duplicate-entry.ts | 72 +++++++ .../rules/no-duplicate-preview.ts | 73 +++++++ .../observed-heritage-compatible-check.ts | 106 ++++++++++ .../rules/observed-observedV2-check.ts | 47 +++++ .../observedV2-trace-usage-validation.ts | 146 +++++++++++++ .../rules/old-new-decorator-mix-use-check.ts | 111 ++++++++++ .../rules/once-decorator-check.ts | 187 +++++++++++++++++ .../rules/one-decorator-on-function-method.ts | 68 +++++++ 17 files changed, 1837 insertions(+), 7 deletions(-) create mode 100644 arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/old-new-decorator-mix-use-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts b/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts index 21325d687..7dfa570b0 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts @@ -17,9 +17,7 @@ import * as arkts from '@koalaui/libarkts'; import { getClassPropertyName, isPrivateClassProperty } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -let privateMap: Map = new Map(); - -function addProperty(item: arkts.AstNode, structName: string): void { +function addProperty(item: arkts.AstNode, structName: string, privateMap: Map): void { if (!arkts.isClassProperty(item) || !isPrivateClassProperty(item)) { return; } @@ -33,7 +31,11 @@ function addProperty(item: arkts.AstNode, structName: string): void { } } -function checkPrivateVariables(node: arkts.AstNode, context: UISyntaxRuleContext): void { +function checkPrivateVariables( + node: arkts.AstNode, + context: UISyntaxRuleContext, + privateMap: Map +): void { // Check if the current node is the root node if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { node.getChildren().forEach((member) => { @@ -42,7 +44,7 @@ function checkPrivateVariables(node: arkts.AstNode, context: UISyntaxRuleContext } const structName: string = member.definition.ident?.name ?? ''; member.definition?.body?.forEach((item) => { - addProperty(item, structName); + addProperty(item, structName, privateMap); }); }); } @@ -79,9 +81,10 @@ const rule: UISyntaxRule = { cannotInitializePrivateVariables: `Property '{{propertyName}}' is private and can not be initialized through the component constructor.`, }, setup(context) { + let privateMap: Map = new Map(); return { parsed: (node): void => { - checkPrivateVariables(node, context); + checkPrivateVariables(node, context, privateMap); }, }; }, diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts b/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts new file mode 100644 index 000000000..8448fa435 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +import { + getAnnotationUsage, getClassPropertyAnnotationNames, getClassPropertyName, + getClassPropertyType, PresetDecorators +} from '../utils'; + +function checkDecoratedPropertyType( + member: arkts.AstNode, + context: UISyntaxRuleContext, + relationship: Record +): void { + if (!arkts.isClassProperty(member)) { + return; + } + const propertyName = getClassPropertyName(member); + const propertyType = getClassPropertyType(member); + const propertyAnnotationNames = getClassPropertyAnnotationNames(member); + Object.entries(relationship).forEach(([decoratorName, invalidPropertyTypes]) => { + if (propertyAnnotationNames.some(annotationName => annotationName === decoratorName) && + invalidPropertyTypes + .some(invalidPropertyType => invalidPropertyType === propertyType)) { + if (!arkts.isClassProperty || member.key === undefined) { + return; + } + const errorNode = member.key; + context.report({ + node: errorNode, + message: rule.messages.invalidDecoratedPropertyType, + data: { decoratorName, propertyName, propertyType }, + }); + } + }); +} + +const rule: UISyntaxRule = { + name: 'check-decorated-property-type', + messages: { + invalidDecoratedPropertyType: `The {{decoratorName}} property '{{propertyName}}' cannot be a '{{propertyType}}' object.`, + }, + setup(context) { + const relationship: Record = { + [PresetDecorators.STATE]: ['CustomDialogController'], + }; + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + const componentDecorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); + if (!componentDecorator) { + return; + } + node.definition.body.forEach(member => { + checkDecoratedPropertyType(member, context, relationship); + }); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts new file mode 100644 index 000000000..ce7afdf8f --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +// Report an Observed version violation error +function reportObservedConflict( + node: arkts.ClassProperty, + context: UISyntaxRuleContext, + message: string +): void { + node.annotations.forEach((anno) => { + if (anno.expr?.dumpSrc()) { + context.report({ + node: anno, + message: message, + data: { + annotation: anno.expr?.dumpSrc(), + } + }); + } + }); +} + +function processNode( + node: arkts.ClassProperty, + annotationName: string, + observedV1Name: Set, + observedV2Name: Set, + context: UISyntaxRuleContext +): void { + const queue: Array = [node]; + while (queue.length > 0) { + const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; + if (arkts.isIdentifier(currentNode)) { + if (observedV1Name.has(currentNode.dumpSrc()) && annotationName === PresetDecorators.COMPONENT_V2) { + reportObservedConflict(node, context, rule.messages.observedv1_v2); + break; + } + if (observedV2Name.has(currentNode.dumpSrc()) && annotationName === PresetDecorators.COMPONENT_V1) { + reportObservedConflict(node, context, rule.messages.observedv2_v1); + break; + } + } + const children = currentNode.getChildren(); + for (const child of children) { + queue.push(child); + } + } +} + +function traverseTree( + node: arkts.AstNode, + annotationName: string, + observedV1Name: Set, + observedV2Name: Set, + context: UISyntaxRuleContext +): void { + if (arkts.isClassProperty(node)) { + processNode(node, annotationName, observedV1Name, observedV2Name, context); + } + const children = node.getChildren(); + for (const child of children) { + traverseTree(child, annotationName, observedV1Name, observedV2Name, context); + } +} + +function findAllObserved(node: arkts.AstNode, observedV1Name: Set, observedV2Name: Set): void { + if (arkts.isClassDeclaration(node)) { + node.definition?.annotations.forEach((anno) => { + if (anno.expr?.dumpSrc() === PresetDecorators.OBSERVED_V1) { + const componentV1Name = node?.definition?.ident?.name; + componentV1Name ? observedV1Name.add(componentV1Name) : null; + } + if (anno.expr?.dumpSrc() === PresetDecorators.OBSERVED_V2) { + const componentV2Name = node?.definition?.ident?.name; + componentV2Name ? observedV2Name.add(componentV2Name) : null; + } + }); + } + const children = node.getChildren(); + for (const child of children) { + findAllObserved(child, observedV1Name, observedV2Name); + } +} + +function findAllTSTypeAliasDeclaration( + node: arkts.AstNode, + observedV1Name: Set, + observedV2Name: Set +): void { + if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION) { + node.getChildren().forEach((child) => { + if (arkts.isIdentifier(child)) { + const typeName = child.dumpSrc(); + findAllObservedType(node, typeName, observedV1Name, observedV2Name); + } + }); + } + const children = node.getChildren(); + for (const child of children) { + findAllTSTypeAliasDeclaration(child, observedV1Name, observedV2Name); + } +} + +function findAllObservedType( + node: arkts.AstNode, + typeName: string, + observedV1Name: Set, + observedV2Name: Set +): void { + if (arkts.isIdentifier(node) && observedV1Name.has(node.dumpSrc())) { + observedV1Name.add(typeName); + } + if (arkts.isIdentifier(node) && observedV2Name.has(node.dumpSrc())) { + observedV2Name.add(typeName); + } + const children = node.getChildren(); + for (const child of children) { + findAllObservedType(child, typeName, observedV1Name, observedV2Name); + } +} + +function processComponentAnnotations( + node: arkts.StructDeclaration, + observedV1Name: Set, + observedV2Name: Set, + context: UISyntaxRuleContext +): void { + node?.definition?.annotations.forEach((anno) => { + if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2) { + traverseTree(node, PresetDecorators.COMPONENT_V2, observedV1Name, observedV2Name, context); + } + if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V1) { + traverseTree(node, PresetDecorators.COMPONENT_V1, observedV1Name, observedV2Name, context); + } + }); +} + +const rule: UISyntaxRule = { + name: 'component-componentV2-mix-use-check', + messages: { + observedv1_v2: `The type of the @{{annotation}} Decorator property can not be a class decorated with @Observed.`, + observedv2_v1: `The type of the @{{annotation}} Decorator property can not be a class decorated with @ObservedV2.` + }, + setup(context) { + let observedV1Name: Set = new Set(); + let observedV2Name: Set = new Set(); + return { + parsed: (node): void => { + if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + findAllObserved(node, observedV1Name, observedV2Name); + findAllTSTypeAliasDeclaration(node, observedV1Name, observedV2Name); + } + if (arkts.isStructDeclaration(node)) { + processComponentAnnotations(node, observedV1Name, observedV2Name, context); + } + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts new file mode 100644 index 000000000..b60587aee --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getClassPropertyAnnotationNames, PresetDecorators, getAnnotationUsage } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +// Helper functions for rules +const hasisComponentV2 = (node: arkts.StructDeclaration): boolean => !!getAnnotationUsage(node, + PresetDecorators.COMPONENT_V2); + +const hasComponent = (node: arkts.StructDeclaration): boolean => !!getAnnotationUsage(node, + PresetDecorators.COMPONENT_V1); +function checkMultipleBuiltInDecorators(context: UISyntaxRuleContext, member: arkts.ClassProperty, + propertyDecorators: string[]): void { + const builtInDecorators = [PresetDecorators.LOCAL, PresetDecorators.PARAM, PresetDecorators.EVENT]; + const appliedBuiltInDecorators = propertyDecorators.filter(d => builtInDecorators.includes(d)); + if (appliedBuiltInDecorators.length > 1) { + member.annotations?.forEach(annotation => { + const annotationsName = annotation.expr?.dumpSrc(); + reportMultipleBuiltInDecoratorsError(context, annotation, annotationsName, builtInDecorators); + }); + } +}; + +function reportMultipleBuiltInDecoratorsError(context: UISyntaxRuleContext, annotation: arkts.AstNode, + annotationsName: string | undefined, builtInDecorators: string[]): void { + if (annotationsName && builtInDecorators.includes(annotationsName)) { + context.report({ + node: annotation, + message: rule.messages.multipleBuiltInDecorators, + fix: (annotation) => { + const startPosition = arkts.getStartPosition(annotation); + const endPosition = arkts.getEndPosition(annotation); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); + } +} + +function checkDecoratorOnlyInisComponentV2(context: UISyntaxRuleContext, member: arkts.ClassProperty, + node: arkts.StructDeclaration, hasisComponentV2: boolean, hasComponent: boolean): void { + const builtInDecorators = [PresetDecorators.LOCAL, PresetDecorators.PARAM, PresetDecorators.EVENT]; + member.annotations?.forEach(annotation => { + const annotationsName = annotation.expr?.dumpSrc(); + if (annotationsName && builtInDecorators.includes(annotationsName) && !hasisComponentV2 && !hasComponent) { + reportDecoratorOnlyInisComponentV2Error(context, annotation, annotationsName, node); + } + }); +}; + +function reportDecoratorOnlyInisComponentV2Error(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage, + annotationsName: string, node: arkts.StructDeclaration): void { + context.report({ + node: annotation, + message: rule.messages.decoratorOnlyInisComponentV2, + data: { annotationsName }, + fix: (annotation) => { + const startPosition = arkts.getStartPosition(node); + return { + range: [startPosition, startPosition], + code: `@${PresetDecorators.COMPONENT_V2}\n`, + }; + }, + }); +} + +function checkParamRequiresRequire(context: UISyntaxRuleContext, member: arkts.ClassProperty, + propertyDecorators: string[]): void { + if (propertyDecorators.includes(PresetDecorators.PARAM) && !member.value && + !propertyDecorators.includes(PresetDecorators.REQUIRE) && member.key) { + const memberKey = member.key; + context.report({ + node: memberKey, + message: rule.messages.paramRequiresRequire, + fix: (memberKey) => { + const startPosition = arkts.getStartPosition(memberKey); + return { + range: [startPosition, startPosition], + code: `@${PresetDecorators.REQUIRE} `, + }; + }, + }); + } +}; + +function checkRequireOnlyWithParam(context: UISyntaxRuleContext, member: arkts.ClassProperty, + propertyDecorators: string[]): void { + const requireDecorator = member.annotations?.find(annotation => + annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.REQUIRE + ); + if (requireDecorator && !propertyDecorators.includes(PresetDecorators.PARAM)) { + context.report({ + node: requireDecorator, + message: rule.messages.requireOnlyWithParam, + fix: (requireDecorator) => { + const startPosition = arkts.getStartPosition(requireDecorator); + const endPosition = arkts.getEndPosition(requireDecorator); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); + } +}; + +function validateClassPropertyDecorators(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { + const isComponentV2 = hasisComponentV2(node); + const isComponent = hasComponent(node); + node.definition.body.forEach(member => { + if (!arkts.isClassProperty(member)) { + return; + } + const propertyDecorators = getClassPropertyAnnotationNames(member); + + // Rule 1: Multiple built-in decorators + checkMultipleBuiltInDecorators(context, member, propertyDecorators); + + // Rule 2: Built-in decorators only allowed in @isComponentV2 + checkDecoratorOnlyInisComponentV2(context, member, node, isComponentV2, isComponent); + + // Rule 3: @Param without default value must be combined with @Require + checkParamRequiresRequire(context, member, propertyDecorators); + + // Rule 4: @Require must be used together with @Param + checkRequireOnlyWithParam(context, member, propertyDecorators); + }); +} + +const rule: UISyntaxRule = { + name: 'iscomponentV2-state-usage-validation', + messages: { + multipleBuiltInDecorators: `The member property or method cannot be decorated by multiple built-in decorators.`, + decoratorOnlyInisComponentV2: `The '@{{annotationsName}}' decorator can only be used in a 'struct' decorated with '@isComponentV2'.`, + paramRequiresRequire: `When a variable decorated with @Param is not assigned a default value, it must also be decorated with @Require.`, + requireOnlyWithParam: `In a struct decorated with @isComponentV2, @Require can only be used with @Param. ` + }, + + setup(context) { + return { + parsed: (node): void => { + + if (!arkts.isStructDeclaration(node)) { + return; + } + validateClassPropertyDecorators(context, node); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts new file mode 100644 index 000000000..f893b01de --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +import { PresetDecorators } from '../utils'; + +function recordStructWithLinkDecorators(item: arkts.AstNode, structName: string, linkMap: Map): void { + if (!arkts.isClassProperty(item)) { + return; + } + item.annotations?.forEach((annotation) => { + const annotationName: string = annotation.expr?.dumpSrc() ?? ''; + if (annotationName === '') { + return; + } + // If the node has properties decorated with Link or ObjectLink, record this structure node + if (annotationName === PresetDecorators.LINK || annotationName === PresetDecorators.OBJECT_LINK) { + linkMap.set(structName, annotationName); + } + }); +} + +function initMap(node: arkts.AstNode, linkMap: Map): void { + // Check if the current node is the root node + if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + return; + } + node.getChildren().forEach((member) => { + if (!arkts.isStructDeclaration(member)) { + return; + } + const structName: string = member.definition.ident?.name ?? ''; + if (structName === '') { + return; + } + member.definition?.body?.forEach((item) => { + recordStructWithLinkDecorators(item, structName, linkMap); + }); + }); +} + +function checkInitializeWithLiteral(node: arkts.AstNode, context: UISyntaxRuleContext, + linkMap: Map +): void { + if (!arkts.isCallExpression(node)) { + return; + } + const componentName = node.expression.dumpSrc(); + // Only assignments to properties decorated with Link or ObjectLink trigger rule checks + if (!linkMap.has(componentName)) { + return; + } + node.arguments.forEach((member) => { + member.getChildren().forEach((property) => { + if (!arkts.isProperty(property)) { + return; + } + if (property.value === undefined) { + return; + } + const propertyType: arkts.Es2pandaAstNodeType = arkts.nodeType(property.value); + const key: string = property.key?.dumpSrc() ?? ''; + if (key === '') { + return; + } + const value = property.value?.dumpSrc() ? property.value.dumpSrc() : ''; + // If the assignment statement is not of type MemberExpression, throw an error + if (propertyType !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION) { + context.report({ + node: property, + message: rule.messages.cannotInitializeWithLiteral, + data: { + value: value, + annotationName: linkMap.get(componentName)!, + key: key, + }, + }); + } + }); + }); +} + +const rule: UISyntaxRule = { + name: 'construct-parameter-literal', + messages: { + cannotInitializeWithLiteral: `Assigning the attribute'{{value}}' to the '@{{annotationName}}' decorated attribute '{{key}}' is not allowed.`, + }, + setup(context) { + let linkMap: Map = new Map(); + return { + parsed: (node): void => { + initMap(node, linkMap); + checkInitializeWithLiteral(node, context, linkMap); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/index.ts b/arkui-plugins/ui-syntax-plugins/rules/index.ts index ecb2d9888..13b008b62 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/index.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/index.ts @@ -13,18 +13,26 @@ * limitations under the License. */ - import { UISyntaxRule } from './ui-syntax-rule'; import BuildRootNode from './build-root-node'; import CheckConstructPrivateParameter from './check-construct-private-parameter'; +import CheckDecoratedPropertyType from './check-decorated-property-type'; +import ComponentComponentV2MixUseCheck from './component-componentV2-mix-use-check'; import ComponentV2MixCheck from './componentV2-mix-check'; import ConsumerProviderDecoratorCheck from './consumer-provider-decorator-check'; +import ComponentV2StateUsageValidation from './componentV2-state-usage-validation'; +import ConstructParameterLiteral from './construct-parameter-literal'; import CustomDialogMissingController from './custom-dialog-missing-controller'; import DecoratorsInUIComponentOnly from './decorators-in-ui-component-only'; import EntryLoacalStorageCheck from './entry-localstorage-check'; import EntryStructNoExport from './entry-struct-no-export'; import LocalBuilderCheck from './local-builder-check'; +import MonitorDecoratorCheck from './monitor-decorator-check'; +import NestedRelationship from './nested-relationship'; +import NoChildInButton from './no-child-in-button'; import NoDuplicateDecorators from './no-duplicate-decorators'; +import NoDuplicateEntry from './no-duplicate-entry'; +import NoDuplicatePreview from './no-duplicate-preview'; import NoDuplicateStateManager from './no-duplicate-state-manager'; import NoPropLinkObjectlinkInEntry from './no-prop-link-objectlink-in-entry'; import NoSameAsBuiltInAttribute from './no-same-as-built-in-attribute'; @@ -39,18 +47,33 @@ import VariableInitializationViaComponentCons from './variable-initialization-vi import WatchDecoratorFunction from './watch-decorator-function'; import WatchDecoratorRegular from './watch-decorator-regular'; import WrapBuilderCheck from './wrap-builder-check'; +import ObservedHeritageCompatibleCheck from './observed-heritage-compatible-check'; +import ObservedObservedV2 from './observed-observedV2-check'; +import ObservedV2TraceUsageValidation from './observedV2-trace-usage-validation'; +import OnceDecoratorCheck from './once-decorator-check'; +import OneDecoratorOnFunctionMethod from './one-decorator-on-function-method'; +import OldNewDecoratorMixUseCheck from './old-new-decorator-mix-use-check'; const rules: UISyntaxRule[] = [ BuildRootNode, CheckConstructPrivateParameter, + CheckDecoratedPropertyType, + ComponentComponentV2MixUseCheck, ComponentV2MixCheck, ConsumerProviderDecoratorCheck, + ComponentV2StateUsageValidation, + ConstructParameterLiteral, CustomDialogMissingController, DecoratorsInUIComponentOnly, EntryLoacalStorageCheck, EntryStructNoExport, LocalBuilderCheck, + MonitorDecoratorCheck, + NestedRelationship, + NoChildInButton, NoDuplicateDecorators, + NoDuplicateEntry, + NoDuplicatePreview, NoDuplicateStateManager, NoPropLinkObjectlinkInEntry, NoSameAsBuiltInAttribute, @@ -65,6 +88,12 @@ const rules: UISyntaxRule[] = [ WatchDecoratorFunction, WatchDecoratorRegular, WrapBuilderCheck, + ObservedHeritageCompatibleCheck, + ObservedObservedV2, + ObservedV2TraceUsageValidation, + OnceDecoratorCheck, + OneDecoratorOnFunctionMethod, + OldNewDecoratorMixUseCheck, ]; export default rules; diff --git a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts new file mode 100644 index 000000000..e0696de48 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +// Function declarations moved to the top with explicit return types +function getLocalMonitorUsed(body: arkts.MethodDefinition): arkts.AnnotationUsage | undefined { + const localMonitorUsed = body.scriptFunction.annotations?.find( + annotation => annotation.expr && + annotation.expr.dumpSrc() === PresetDecorators.MONITOR + ); + return localMonitorUsed; +} + +function checkConflictingDecorators(context: UISyntaxRuleContext, body: arkts.MethodDefinition, + localMonitorUsed: arkts.AnnotationUsage): boolean { + const conflictingDecorators = body.scriptFunction.annotations?.filter( + annotation => annotation.expr && + annotation.expr.dumpSrc() !== PresetDecorators.MONITOR + ); + if (conflictingDecorators?.length > 0) { + reportConflictingDecorators(context, localMonitorUsed, conflictingDecorators); + return true; + } + return false; +} + +function reportConflictingDecorators(context: UISyntaxRuleContext, localMonitorUsed: arkts.AstNode, + conflictingDecorators: arkts.AnnotationUsage[]): void { + context.report({ + node: localMonitorUsed, + message: rule.messages.invalidUsage1, + fix: () => { + const startPositions = conflictingDecorators.map(annotation => + arkts.getStartPosition(annotation)); + const endPositions = conflictingDecorators.map(annotation => arkts.getEndPosition(annotation)); + const startPosition = startPositions[0]; + const endPosition = endPositions[endPositions.length - 1]; + return { + range: [startPosition, endPosition], + code: '' + }; + } + }); +} + +function checkIfClassIsObservedV2(node: arkts.ClassDeclaration): boolean { + return node.definition?.annotations?.some( + observedV2 => observedV2.expr?.dumpSrc() === PresetDecorators.OBSERVED_V2 + ) ?? false; +} + +function checkIfStructIsComponentV2(node: arkts.StructDeclaration): boolean { + return node.definition?.annotations?.some( + componentV2 => componentV2.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2 + ) ?? false; +} + +function reportInvalidUsage(context: UISyntaxRuleContext, node: arkts.AstNode, message: string, fixCode: string) + : void { + const startPosition = arkts.getStartPosition(node); + context.report({ + node, + message, + fix: () => ({ + range: [startPosition, startPosition], + code: fixCode, + }), + }); +} + +function checkMultipleDecorators( + node: arkts.ClassDeclaration | arkts.StructDeclaration, + context: UISyntaxRuleContext +): boolean { + // Traverse body of the class to check for @Monitor usage + let monitorUsed: boolean = false; + node.definition?.body.forEach(body => { + if (arkts.isMethodDefinition(body)) { + const localMonitorUsed = getLocalMonitorUsed(body); + if (localMonitorUsed) { + monitorUsed = true; + checkConflictingDecorators(context, body, localMonitorUsed); + return; // Stop further checks for this method + } + } + }); + return monitorUsed; +} + +function checkDecorateMethod( + node: arkts.ClassDeclaration | arkts.StructDeclaration, + context: UISyntaxRuleContext +): void { + // Check if @Monitor is used on a property (which is not allowed) + node.definition?.body.forEach(body => { + if (!arkts.isClassProperty(body)) { + return; + } + const monitorDecorator = body.annotations?.find( + annotation => annotation.expr?.dumpSrc() === PresetDecorators.MONITOR); + if (monitorDecorator === undefined) { + return; + } + context.report({ + node: monitorDecorator, + message: rule.messages.invalidUsage4, + fix: () => { + const startPosition = arkts.getStartPosition(monitorDecorator); + const endPosition = arkts.getEndPosition(monitorDecorator); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); + }); +} + +// The rule object with its setup method +const rule: UISyntaxRule = { + name: 'monitor-decorator-check', + messages: { + invalidUsage1: + `The member property or method can not be decorated by multiple built-in decorators.`, + invalidUsage2: + `The '@Monitor' can decorate only member method within a 'class' decorated with @ObservedV2.`, + invalidUsage3: + `The '@Monitor' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, + invalidUsage4: + `@Monitor can only decorate method`, + }, + setup(context) { + return { + parsed: (node: arkts.AstNode): void => { + if (!arkts.isClassDeclaration(node) && !arkts.isStructDeclaration(node)) { + return; + } + let monitorUsed = false; + + const isObservedV2 = arkts.isClassDeclaration(node) && checkIfClassIsObservedV2(node); + const isComponentV2 = arkts.isStructDeclaration(node) && checkIfStructIsComponentV2(node); + + monitorUsed = checkMultipleDecorators(node, context); + + // Check for errors related to @Monitor usage + if (monitorUsed && !isObservedV2 && arkts.isClassDeclaration(node)) { + reportInvalidUsage(context, node, rule.messages.invalidUsage2, `@${PresetDecorators.OBSERVED_V2}\n`); + } + if (monitorUsed && !isComponentV2 && arkts.isStructDeclaration(node)) { + reportInvalidUsage(context, node, rule.messages.invalidUsage3, `@${PresetDecorators.COMPONENT_V2}\n`); + } + + checkDecorateMethod(node, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts new file mode 100644 index 000000000..fd18100e9 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getIdentifierName } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function checkInvalidChildInText(node: arkts.AstNode, context: UISyntaxRuleContext, textChild: string[]): void { + // Check if the current node is an identifier, and name is 'Text' + if (!arkts.isIdentifier(node)) { + return; + } + if (getIdentifierName(node) !== 'Text') { + return; + } + if (!node.parent) { + return; + } + const parentNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + } + // If the BlockStatement contains a child component that should not exist under the text, an error will be reported + parentNode.getChildren().forEach(member => { + if (!arkts.isBlockStatement(member)) { + return; + } + member.getChildren().forEach(sibling => { + if (!arkts.isExpressionStatement(sibling) || !arkts.isCallExpression(sibling.expression)) { + return; + } + const childComponentName = sibling.expression.expression.dumpSrc(); + if (!textChild.includes(childComponentName)) { + context.report({ + node: node, + message: rule.messages.invalidChildInText + }); + return; + } + }); + }); +} +function checkOneChildInButton(node: arkts.AstNode, context: UISyntaxRuleContext): void { + // Check if the current node is an identifier, and name is 'Button' + if (!arkts.isIdentifier(node)) { + return; + } + if (getIdentifierName(node) !== 'Button') { + return; + } + if (!node.parent) { + return; + } + const parentNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + } + // If there is more than one subcomponent in the BlockStatement, an error is reported + parentNode.getChildren().forEach(member => { + if (!arkts.isBlockStatement(member)) { + return; + } + if (member.statements.length > 1) { + context.report({ + node: node, + message: rule.messages.oneChildInButton + }); + } + }); +} + +function checkListItem(node: arkts.AstNode, context: UISyntaxRuleContext): void { + // Check if the current node is an identifier, and name is 'ListItem' + if (!arkts.isIdentifier(node)) { + return; + } + if (getIdentifierName(node) !== 'ListItem') { + return; + } + if (!node.parent || !node.parent.parent) { + return; + } + let curNode: arkts.AstNode = node.parent.parent; + do { + while (!arkts.isCallExpression(curNode)) { + if (!curNode.parent) { + return; + } + curNode = curNode.parent; + } + const parentName: string = curNode.expression.dumpSrc(); + if (parentName === 'List') { // If the parent component's name is 'List', exit directly + break; + } else if (parentName !== 'ForEach') { // If the parent component's name is not 'List' or 'ForEach', throw an error + context.report({ + node: node, + message: rule.messages.listItemCannotInOther, + data: { parentName: parentName } + }); + context.report({ + node: node, + message: rule.messages.listItemMustInList + }); + break; + } + // In the remaining case, the parent component is 'ForEach', continue traversing upwards for further checks + if (!curNode.parent) { + return; + } + curNode = curNode.parent; + } while (true); +} + +function checkSpan(node: arkts.AstNode, context: UISyntaxRuleContext): void { + // Check if the current node is an identifier, and name is 'Span' + if (!arkts.isIdentifier(node)) { + return; + } + if (getIdentifierName(node) !== 'Span') { + return; + } + let parentNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + } + // If there are subcomponents in the BlockStatement, an error is reported + parentNode.getChildren().forEach(sibling => { + if (!arkts.isBlockStatement(sibling)) { + return; + } + if (sibling.statements.length > 0) { + context.report({ + node: node, + message: rule.messages.noChildInSpan + }); + } + }); + if (!node.parent || !node.parent.parent) { + return; + } + parentNode = parentNode.parent; + while (!arkts.isCallExpression(parentNode)) { + parentNode = parentNode.parent; + } + const parentName: string = parentNode.expression.dumpSrc(); + // If the name of the parent component is not 'Text', an error is reported + if (parentName !== 'Text' && parentName !== 'RichEditor' && parentName !== 'ContainerSpan') { + context.report({ + node: node, + message: rule.messages.spanMustInText + }); + } +} +// The 'Text' component can have only the Span, ImageSpan, ContainerSpan and SymbolSpan child component. + +const rule: UISyntaxRule = { + name: 'nested-relationship', + messages: { + invalidChildInText: `The 'Text' component can have only the Span, ImageSpan, ContainerSpan and SymbolSpan child component.`, + oneChildInButton: `The 'Button' component can have only one child component.`, + listItemMustInList: `The 'ListItem' component can only be nested in the List and ListItemGroup parent component.`, + listItemCannotInOther: `The 'ListItem' component cannot be a child component of the '{{parentName}}' component.`, + noChildInSpan: `No child component is allowed in the 'Span' component. `, + spanMustInText: `The 'Span' component can only be nested in the Text, RichEditor and ContainerSpan parent component. `, + }, + setup(context) { + const textChild: string[] = ['Span', 'ImageSpan', 'ContainerSpan', 'SymbolSpan']; + return { + parsed: (node): void => { + checkInvalidChildInText(node, context, textChild); + checkOneChildInButton(node, context); + checkListItem(node, context); + checkSpan(node, context); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts b/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts new file mode 100644 index 000000000..6cf999a27 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +import { getIdentifierName } from '../utils'; + +function isInsideStructAndBuild(node: arkts.AstNode): boolean { + let parentNode = node.parent; + let isInStruct = false; + let isInBuild = false; + while (arkts.nodeType(parentNode) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + if (arkts.isStructDeclaration(parentNode)) { + isInStruct = true; + } + if (arkts.isScriptFunction(parentNode) && parentNode.id?.name === 'build') { + isInBuild = true; + } + parentNode = parentNode.parent; + } + return isInStruct && isInBuild; +} + +function reportNoChildInButtonError(parentNode: arkts.AstNode, context: UISyntaxRuleContext): void { + const siblings = parentNode.getChildren(); + if (!Array.isArray(siblings) || siblings.length < 3) { + return; + } + if (arkts.isStringLiteral(siblings[1]) && arkts.isBlockStatement(siblings[2])) { + context.report({ + node: parentNode, + message: rule.messages.noChildInButton, + fix: (parentNode) => { + const startPosition = arkts.getStartPosition(siblings[2]); + const endPosition = arkts.getEndPosition(siblings[2]); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); + } +} + +const rule: UISyntaxRule = { + name: 'no-child-in-button', + messages: { + noChildInButton: `The Button component with a label parameter can not have any child.`, + }, + setup(context: UISyntaxRuleContext) { + return { + parsed: (node): void => { + // Check if the current node is an identifier + if (!arkts.isIdentifier(node)) { + return; + } + const componentName = getIdentifierName(node); + // If the current node is 'Button' + if (componentName !== 'Button') { + return; + } + if (!isInsideStructAndBuild(node)) { + return; + } + // Obtain the information of the parent node of the current node + let parentNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + }; + // Gets and traverses all the children of the parent node + reportNoChildInButtonError(parentNode, context); + } + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts new file mode 100644 index 000000000..60c810180 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const MAX_ENTRY_DECORATOR_COUNT = 1; +function checkDuplicateEntry(node: arkts.AstNode, context: UISyntaxRuleContext): void { + if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + return; + } + let entryDecoratorUsages: arkts.AnnotationUsage[] = []; + node.getChildren().forEach((child) => { + if (!arkts.isStructDeclaration(child)) { + return; + } + const entryDecoratorUsage = getAnnotationUsage( + child, + PresetDecorators.ENTRY, + ); + if (entryDecoratorUsage) { + entryDecoratorUsages.push(entryDecoratorUsage); + } + }); + // If more than one entry decorator is recorded, an error is reported + if (entryDecoratorUsages.length <= MAX_ENTRY_DECORATOR_COUNT) { + return; + } + entryDecoratorUsages.forEach((entryDocoratorUsage) => { + context.report({ + node: entryDocoratorUsage, + message: rule.messages.duplicateEntry, + fix: (entryDocoratorUsage) => { + const startPosition = arkts.getStartPosition(entryDocoratorUsage); + const endPosition = arkts.getEndPosition(entryDocoratorUsage); + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); + }); +} + +const rule: UISyntaxRule = { + name: 'no-duplicate-entry', + messages: { + duplicateEntry: `An ArkTS file can contain only one '@Entry' decorator.`, + }, + setup(context) { + return { + parsed: (node): void => { + checkDuplicateEntry(node, context); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts new file mode 100644 index 000000000..fe57d8f11 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const MAX_PREVIEW_DECORATOR_COUNT = 10; + +function checkDuplicatePreview(node: arkts.AstNode, context: UISyntaxRuleContext): void { + if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + return; + } + let previewDecoratorUsages: arkts.AnnotationUsage[] = []; + node.getChildren().forEach((child) => { + if (!arkts.isStructDeclaration(child)) { + return; + } + const previewDecoratorUsage = getAnnotationUsage( + child, + PresetDecorators.PREVIEW, + ); + if (previewDecoratorUsage) { + previewDecoratorUsages.push(previewDecoratorUsage); + } + }); + // If the number of preview decorators is greater than 10, an error is reported + if (previewDecoratorUsages.length <= MAX_PREVIEW_DECORATOR_COUNT) { + return; + } + previewDecoratorUsages.forEach((previewDecoratorUsage) => { + context.report({ + node: previewDecoratorUsage, + message: rule.messages.duplicateEntry, + fix: (previewDecoratorUsage) => { + const startPosition = arkts.getStartPosition(previewDecoratorUsage); + const endPosition = arkts.getEndPosition(previewDecoratorUsage); + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); + }); +} + +const rule: UISyntaxRule = { + name: 'no-duplicate-preview', + messages: { + duplicateEntry: `An ArkTS file con contain at most 10 '@Preview' decorators.`, + }, + setup(context) { + return { + parsed: (node): void => { + checkDuplicatePreview(node, context); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts b/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts new file mode 100644 index 000000000..95b605f2c --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +import { PresetDecorators } from '../utils/index'; + +function getObservedDecorator(node: arkts.AstNode, observedClasses: string[], observedV2Classes: string[]): void { + for (const child of node.getChildren()) { + // Check if it is of the ClassDeclaration type + if (arkts.isClassDeclaration(child)) { + // Get a list of annotations + const annotations = child.definition?.annotations ?? []; + // Check for @Observed decorators + const hasObservedDecorator = annotations.find((annotation: any) => + annotation.expr.name === PresetDecorators.OBSERVED_V1); + // Check if there is a @ObservedV2 decorator + const hasObservedV2Decorator = annotations.find((annotation: any) => + annotation.expr.name === PresetDecorators.OBSERVED_V2); + // If there is a @Observed decorator, record the class name + if (hasObservedDecorator) { + const className = child.definition?.ident?.name ?? ''; + observedClasses.push(className); + } + // If there is a @ObservedV2 decorator, record the class name + if (hasObservedV2Decorator) { + const className = child.definition?.ident?.name ?? ''; + observedV2Classes.push(className); + } + } + } +} + +function checkInheritanceCompatibility(context: UISyntaxRuleContext, node: arkts.ClassDeclaration, + observedClasses: string[], observedV2Classes: string[]): void { + const observedV1Decorator = node.definition?.annotations?.find(annotations => + annotations.expr && + arkts.isIdentifier(annotations.expr) && + annotations.expr.name === PresetDecorators.OBSERVED_V1 + ); + const observedV2Decorator = node.definition?.annotations?.find(annotations => + annotations.expr && + arkts.isIdentifier(annotations.expr) && + annotations.expr.name === PresetDecorators.OBSERVED_V2 + ); + + //Get the name of the superClass + const superClassName = node.definition?.super?.dumpSrc(); + if (!superClassName) { + return; + } + // Verify that the inheritance relationship is compatible + if (observedV1Decorator && observedV2Classes.includes(superClassName)) { + context.report({ + node: observedV1Decorator, + message: rule.messages.incompatibleHeritageObservedToObservedV2, + }); + } + if (observedV2Decorator && observedClasses.includes(superClassName)) { + context.report({ + node: observedV2Decorator, + message: rule.messages.incompatibleHeritageObservedV2ToObserved, + }); + } +} + +const rule: UISyntaxRule = { + name: 'observed-heritage-compatible-check', + messages: { + incompatibleHeritageObservedToObservedV2: `The current class is decorated by '@Observed', it cannot inherit a class decorated by '@ObservedV2'.`, + incompatibleHeritageObservedV2ToObserved: `The current class is decorated by '@ObservedV2', it cannot inherit a class decorated by '@Observed'.`, + }, + setup(context) { + // Record the class name decorated with @Observed and @ObservedV2 + const observedClasses: string[] = []; + const observedV2Classes: string[] = []; + return { + parsed: (node): void => { + // Check if it's of type "Program". + if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + getObservedDecorator(node, observedClasses, observedV2Classes); + } + + // Check if the current node is a class declaration + if (!arkts.isClassDeclaration(node)) { + return; + } + checkInheritanceCompatibility(context, node, observedClasses, observedV2Classes); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts b/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts new file mode 100644 index 000000000..e02304b3c --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PresetDecorators } from '../utils'; +import { UISyntaxRule } from './ui-syntax-rule'; + +const rule: UISyntaxRule = { + name: 'observed-observedV2-check', + messages: { + conflictingDecorators: `A class cannot be decorated by both '@Observed' and '@ObservedV2' at the same time.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isClassDeclaration(node)) { + return; + } + const hasObservedDecorator = node.definition?.annotations?.find(annotations => annotations.expr && + annotations.expr.dumpSrc() === PresetDecorators.OBSERVED_V1); + const hasObservedV2Decorator = node.definition?.annotations?.find(annotations => annotations.expr && + annotations.expr.dumpSrc() === PresetDecorators.OBSERVED_V2); + // If the current class is decorated by @Observed and @ObservedV2, an error is reported + if (hasObservedDecorator && hasObservedV2Decorator) { + context.report({ + node: hasObservedDecorator, + message: rule.messages.conflictingDecorators, + }); + } + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts b/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts new file mode 100644 index 000000000..d6285abd1 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PresetDecorators, getAnnotationUsage } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const rule: UISyntaxRule = { + name: 'observedV2-trace-usage-validation', + messages: { + observedV2DecoratorError: `The '@ObservedV2' decorator can only be used in 'class'.`, + traceDecoratorError: `The '@Trace' decorator can only be used in 'class'.`, + traceInObservedV2Error: `The '@Trace' decorator can only be used in a 'class' decorated with '@ObservedV2'.`, + traceMemberVariableError: `The '@Trace' decorator can only decorate member variables within a 'class' decorated with '@ObservedV2'.`, + }, + setup(context) { + return { + parsed: (node): void => { + validateTraceDecoratorUsage(node, context); + }, + }; + }, +}; + +function reportObservedV2DecoratorError(context: UISyntaxRuleContext, hasObservedV2Decorator: arkts.AnnotationUsage) + : void { + context.report({ + node: hasObservedV2Decorator, + message: rule.messages.observedV2DecoratorError, + fix: (hasObservedV2Decorator) => { + const startPosition = arkts.getStartPosition(hasObservedV2Decorator); + const endPosition = arkts.getEndPosition(hasObservedV2Decorator); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +function reportTraceMemberVariableError(context: UISyntaxRuleContext, hasTraceDecorator: arkts.AnnotationUsage) + : void { + context.report({ + node: hasTraceDecorator, + message: rule.messages.traceMemberVariableError, + fix: (hasTraceDecorator) => { + const startPosition = arkts.getStartPosition(hasTraceDecorator); + const endPosition = arkts.getEndPosition(hasTraceDecorator); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +function tracePerportyRule( + context: UISyntaxRuleContext, + currentNode: arkts.AstNode, + hasTraceDecorator: arkts.AnnotationUsage): void { + if (arkts.isStructDeclaration(currentNode)) { + reportTraceDecoratorError(context, hasTraceDecorator); + } else if (arkts.isClassDeclaration(currentNode)) { + // The '@Trace' decorator can only be used in a 'class' decorated with '@ObservedV2' + if (!currentNode.definition?.annotations?.some((annotation: any) => annotation.expr.name === + PresetDecorators.OBSERVED_V2)) { + reportTraceInObservedV2Error(context, hasTraceDecorator, currentNode); + } + } +} + +function reportTraceDecoratorError(context: UISyntaxRuleContext, hasTraceDecorator: arkts.AnnotationUsage) + : void { + context.report({ + node: hasTraceDecorator, + message: rule.messages.traceDecoratorError, + fix: (hasTraceDecorator) => { + const startPosition = arkts.getStartPosition(hasTraceDecorator); + const endPosition = arkts.getEndPosition(hasTraceDecorator); + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +function reportTraceInObservedV2Error(context: UISyntaxRuleContext, hasTraceDecorator: arkts.AnnotationUsage, + currentNode: arkts.ClassDeclaration): void { + context.report({ + node: hasTraceDecorator, + message: rule.messages.traceInObservedV2Error, + fix: () => { + const startPosition = arkts.getStartPosition(currentNode); + return { + range: [startPosition, startPosition], + code: `@${PresetDecorators.OBSERVED_V2}\n`, + }; + }, + }); +} + +function validateTraceDecoratorUsage(node: arkts.AstNode, context: UISyntaxRuleContext): void { + let currentNode = node; + if (arkts.isStructDeclaration(node)) { + // Check whether the current custom component is decorated by the @ObservedV2 decorator + const hasObservedV2Decorator = getAnnotationUsage(node, PresetDecorators.OBSERVED_V2); + if (hasObservedV2Decorator) { + reportObservedV2DecoratorError(context, hasObservedV2Decorator); + } + } + if (arkts.isClassProperty(node)) { + const hasTraceDecorator = node.annotations?.find(annotation => + annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.TRACE); + if (hasTraceDecorator) { + // Iterate up the parent node to check whether it is a class or a custom component + while (!arkts.isStructDeclaration(currentNode) && !arkts.isClassDeclaration(currentNode)) { + currentNode = currentNode.parent; + } + // The '@Trace' decorator can only be used in 'class' + tracePerportyRule(context, currentNode, hasTraceDecorator); + } + } + if (arkts.isMethodDefinition(node)) { + // Check that @Trace is in the correct location + const hasTraceDecorator = node.scriptFunction.annotations?.find(annotation => + annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.TRACE); + if (hasTraceDecorator) { + reportTraceMemberVariableError(context, hasTraceDecorator); + } + } +} + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/old-new-decorator-mix-use-check.ts b/arkui-plugins/ui-syntax-plugins/rules/old-new-decorator-mix-use-check.ts new file mode 100644 index 000000000..356a28098 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/old-new-decorator-mix-use-check.ts @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PresetDecorators, getAnnotationUsage } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function findPropertyDecorator( + node: arkts.ClassProperty, + decoratorName: string +): arkts.AnnotationUsage | undefined { + const annotation = node.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() === decoratorName + ); + return annotation; +} + +function paramDecoratorError( + context: UISyntaxRuleContext, + hasParamDecorator: arkts.AnnotationUsage, + hasComponentDecorator: arkts.AnnotationUsage +): void { + context.report({ + node: hasParamDecorator, + message: rule.messages.paramDecoratorError, + fix: () => { + const startPosition = arkts.getStartPosition(hasComponentDecorator); + const endPosition = arkts.getEndPosition(hasComponentDecorator); + return { + range: [startPosition, endPosition], + code: `@${PresetDecorators.COMPONENT_V2}`, + }; + }, + }); +} + +function stateDecoratorError( + context: UISyntaxRuleContext, + hasStateDecorator: arkts.AnnotationUsage, + hasComponentV2Decorator: arkts.AnnotationUsage +): void { + context.report({ + node: hasStateDecorator, + message: rule.messages.stateDecoratorError, + fix: () => { + const startPosition = arkts.getStartPosition(hasComponentV2Decorator); + const endPosition = arkts.getEndPosition(hasComponentV2Decorator); + return { + range: [startPosition, endPosition], + code: `@${PresetDecorators.COMPONENT_V1}`, + }; + }, + }); +} + +function findDecoratorError( + node: arkts.StructDeclaration, + context: UISyntaxRuleContext +): void { + const hasComponentV2Decorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); + const hasComponentDecorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); + // Check where @Param and @State are used + node.definition.body.forEach((property) => { + if (arkts.isClassProperty(property)) { + const hasParamDecorator = findPropertyDecorator(property, PresetDecorators.PARAM); + const hasStateDecorator = findPropertyDecorator(property, PresetDecorators.STATE); + // Check that @Param is in the correct location + if (hasParamDecorator && !hasComponentV2Decorator && hasComponentDecorator) { + paramDecoratorError(context, hasParamDecorator, hasComponentDecorator); + } + // Check that @State is in the correct location + if (hasStateDecorator && !hasComponentDecorator && hasComponentV2Decorator) { + stateDecoratorError(context, hasStateDecorator, hasComponentV2Decorator); + } + } + }); +} + + +const rule: UISyntaxRule = { + name: 'old-new-decorator-mix-use-check', + messages: { + paramDecoratorError: `The '@Param' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, + stateDecoratorError: `The '@State' decorator can only be used in a 'struct' decorated with '@Component'.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + findDecoratorError(node, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts new file mode 100644 index 000000000..fabe04af0 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function findDecorator(member: arkts.ClassProperty, decorator: string): arkts.AnnotationUsage | undefined { + return member.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() === decorator + ); +} + +// Check that the property decorator complies with the rules +function validatePropertyAnnotations( + body: arkts.ClassProperty, + context: UISyntaxRuleContext, + hasOnceDecorator: arkts.AnnotationUsage | undefined +): void { + const propertyAnnotations = getClassPropertyAnnotationNames(body); + hasOnceDecorator = findDecorator(body, PresetDecorators.ONCE); + if (hasOnceDecorator) { + const isParamUsed = propertyAnnotations.includes(PresetDecorators.PARAM); + // If @Once is found, check if @Param is also used + if (!isParamUsed) { + reportMissingParamWithOnce(hasOnceDecorator, context); + } else { + // If both @Once and @Param are used, check for other + // incompatible decorators + const otherDecorators = body.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() !== PresetDecorators.ONCE && + annotation.expr.dumpSrc() !== PresetDecorators.PARAM + ); + reportInvalidDecoratorsWithOnceAndParam(otherDecorators, context); + } + } +} + +function reportMissingParamWithOnce( + hasOnceDecorator: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + if (!hasOnceDecorator) { + return; + } + context.report({ + node: hasOnceDecorator, + message: rule.messages.invalidDecorator, + fix: (hasOnceDecorator) => { + const startPosition = arkts.getEndPosition(hasOnceDecorator); + const endPosition = arkts.getEndPosition(hasOnceDecorator); + return { + range: [startPosition, endPosition], + code: `@${PresetDecorators.PARAM}` + }; + } + }); +} + +function reportInvalidDecoratorsWithOnceAndParam( + otherDecorators: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + if (!otherDecorators) { + return; + } + context.report({ + node: otherDecorators, + message: rule.messages.invalidDecorator, + fix: (otherDecorators) => { + const startPosition = arkts.getStartPosition(otherDecorators); + const endPosition = arkts.getEndPosition(otherDecorators); + return { + range: [startPosition, endPosition], + code: '' + }; + } + }); +} + +// Check if the method is @Once decorated (not allowed) +function validateMethodAnnotations(body: arkts.MethodDefinition, context: UISyntaxRuleContext): void { + const methodAnnotations = body.scriptFunction.annotations?.find(annotation => + annotation.expr && + annotation.expr.dumpSrc() === PresetDecorators.ONCE + ); + if (methodAnnotations) { + context.report({ + node: methodAnnotations, + message: rule.messages.invalidMemberDecorate, + fix: (methodAnnotations) => { + const startPosition = arkts.getStartPosition(methodAnnotations); + const endPosition = arkts.getEndPosition(methodAnnotations); + return { + range: [startPosition, endPosition], + code: '' + }; + } + }); + } +} + +function invalidComponentUsage( + body: arkts.ClassProperty, + hasOnceDecorator: arkts.AnnotationUsage | undefined, + componentV2DocoratorUsage: arkts.AnnotationUsage | undefined, + componentDocoratorUsage: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + hasOnceDecorator = findDecorator(body, PresetDecorators.ONCE); + if (hasOnceDecorator && !componentV2DocoratorUsage && componentDocoratorUsage) { + context.report({ + node: hasOnceDecorator, + message: rule.messages.invalidUsage, + fix: (hasOnceDecorator) => { + const startPosition = arkts.getStartPosition(componentDocoratorUsage); + const endPosition = arkts.getEndPosition(componentDocoratorUsage); + return { + range: [startPosition, endPosition], + code: `@${PresetDecorators.COMPONENT_V2}` + }; + } + }); + } +} + +function validateDecorater( + node: arkts.StructDeclaration, + hasOnceDecorator: arkts.AnnotationUsage | undefined, + componentV2DocoratorUsage: arkts.AnnotationUsage | undefined, + componentDocoratorUsage: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext, +): void { + node.definition?.body.forEach(body => { + // Check if @Once is used on a property and if @Param is used with + if (arkts.isClassProperty(body)) { + validatePropertyAnnotations(body, context, hasOnceDecorator); + // If @Once is used but not in a @ComponentV2 struct, report an error + invalidComponentUsage(body, hasOnceDecorator, componentV2DocoratorUsage, componentDocoratorUsage, context); + } + if (!arkts.isMethodDefinition(body)) { + return; + } + // Check if @Once is used on a method (which is not allowed) + validateMethodAnnotations(body, context); + }); +} + +const rule: UISyntaxRule = { + name: 'once-decorator-check', + messages: { + invalidUsage: `@Once can only decorate member properties in a @ComponentV2 struct.`, + invalidMemberDecorate: `@Once can only decorate member properties.`, + invalidDecorator: `@Once must be only used with @Param. ` + }, + setup(context) { + return { + parsed: (node): void => { + // Check if the node is a struct declaration + if (!arkts.isStructDeclaration(node)) { + return; + } + let hasOnceDecorator: arkts.AnnotationUsage | undefined; + // Check if the struct is decorated with @ComponentV2 + const componentV2DocoratorUsage = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); + const componentDocoratorUsage = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); + validateDecorater(node, hasOnceDecorator, componentV2DocoratorUsage, componentDocoratorUsage, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts new file mode 100644 index 000000000..66dd9cdbd --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationName } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const allowedDecorators = new Set(['Extend', 'Builder', 'Styles']); + +function validateFunctionDecorator(node: arkts.EtsScript, context: UISyntaxRuleContext): void { + node.statements.forEach((statement) => { + // If the node is not a function declaration, it is returned + if (!arkts.isFunctionDeclaration(statement)) { + return; + } + const annotations = statement.annotations; + // If there is no annotation, go straight back + if (!annotations) { + return; + } + // Check that each annotation is in the list of allowed decorators + annotations.forEach((annotation) => { + const decoratorName = getAnnotationName(annotation); + // rule1: misuse of decorator, only '@Extend', '@Builder' , '@Styles' decorators allowed on global functions + if (!allowedDecorators.has(decoratorName)) { + context.report({ + node: annotation, + message: rule.messages.invalidDecorator, + data: { + decoratorName, + }, + }); + } + }); + }); +} + +const rule: UISyntaxRule = { + name: 'one-decorator-on-function-method', + messages: { + invalidDecorator: `misuse of '@{{decoratorName}}' decorator, only '@Extend', '@Builder' and '@Styles' decorators allowed on global functions.`, + }, + setup(context) { + return { + parsed: (node: arkts.AstNode): void => { + // If the node is not an ETS script, it is returned directly + if (!arkts.isEtsScript(node)) { + return; + } + validateFunctionDecorator(node, context); + }, + }; + }, +}; + +export default rule; -- Gitee From 11835e39cb3d1030939e7ba19bdc717c7138a135 Mon Sep 17 00:00:00 2001 From: wangcaoyu Date: Thu, 24 Apr 2025 16:27:09 +0800 Subject: [PATCH 088/123] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20tags=20undefined?= =?UTF-8?q?=20=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangcaoyu --- compiler/src/fast_build/system_api/api_check_utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/src/fast_build/system_api/api_check_utils.ts b/compiler/src/fast_build/system_api/api_check_utils.ts index 7a1fd71e8..da30bfff2 100644 --- a/compiler/src/fast_build/system_api/api_check_utils.ts +++ b/compiler/src/fast_build/system_api/api_check_utils.ts @@ -543,7 +543,7 @@ function checkSinceValue(jsDocTags: readonly ts.JSDocTag[], config: ts.JsDocNode } let minSince: string = ''; const hasSince: boolean = currentNode.jsDoc.some((doc: ts.JSDoc) => { - return doc.tags.some((tag: ts.JSDocTag) => { + return doc.tags?.some((tag: ts.JSDocTag) => { if (tag.tagName.escapedText.toString() === SINCE_TAG_NAME) { minSince = tag.comment.toString(); return true; -- Gitee From ca6d9e74dcbd88e5be6df3a2b8bc53ac952311fe Mon Sep 17 00:00:00 2001 From: Cuecuexiaoyu Date: Mon, 12 May 2025 16:18:46 +0800 Subject: [PATCH 089/123] add ArrayExpression visit Signed-off-by: Cuecuexiaoyu Change-Id: I7ef39384820c2b2dce0e64ac904cc8524e2373f0 --- .../decorators/resource/resource-in-build.ets | 10 ++- .../argument-call.test.ts | 6 +- .../lambda-literals/trailing-lambdas.test.ts | 12 +-- .../lambda-literals/with-receiver.test.ts | 6 +- .../method-declarations/callable.test.ts | 4 +- .../internal-calls.test.ts | 4 +- .../resource/resource-in-build.test.ts | 11 ++- koala-wrapper/native/src/bridges.cc | 7 ++ koala-wrapper/src/Es2pandaNativeModule.ts | 4 + .../src/arkts-api/factory/nodeFactory.ts | 10 ++- koala-wrapper/src/arkts-api/index.ts | 1 + .../node-utilities/ArrayExpression.ts | 38 ++++++++++ koala-wrapper/src/arkts-api/types.ts | 2 + koala-wrapper/src/arkts-api/visitor.ts | 8 ++ .../src/generated/peers/ArrayExpression.ts | 76 +++++++++++++------ 15 files changed, 155 insertions(+), 44 deletions(-) create mode 100644 koala-wrapper/src/arkts-api/node-utilities/ArrayExpression.ts diff --git a/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets b/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets index f778c7f4e..49331e647 100644 --- a/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets +++ b/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { Component, $r, $rawfile, Column, Text, Image, TextInput, Select, SelectOption, Margin } from "@ohos.arkui.component" +import { Component, $r, $rawfile, Column, Text, Image, TextInput, Select, SelectOption, Margin, ImageAnimator } from "@ohos.arkui.component" @Component struct ResourceComponent { @@ -37,6 +37,14 @@ struct ResourceComponent { top: $r('app.float.elements_margin_horizontal_m'), bottom: $r('app.float.elements_margin_horizontal_l') } as Margin) + ImageAnimator().images([ + { + src: $r('app.media.aaa') + }, + { + src: $r('app.media.bbb') + }, + ]) } } } \ No newline at end of file diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts index 4665140d4..a3d7d2909 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts @@ -30,7 +30,7 @@ const pluginTester = new PluginTester('test memo function', buildConfig); const expectedScript: string = ` import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; function main() {} -function memo_arg_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg2: ((x: number)=> number), @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number), arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { +@functions.OptionalParametersAnnotation({minArgCount:3}) function memo_arg_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg2: ((x: number)=> number), @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number), arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 5); const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_arg3 = __memo_scope.param(2, arg3), __memo_parameter_arg4 = __memo_scope.param(3, arg4), __memo_parameter_arg5 = __memo_scope.param(4, arg5); if (__memo_scope.unchanged) { @@ -48,7 +48,7 @@ function memo_arg_call(__memo_context: __memo_context_type, __memo_id: __memo_id return; } } -function memo_arg_call_with_lowering(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { +@functions.OptionalParametersAnnotation({minArgCount:1}) function memo_arg_call_with_lowering(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 3); const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg4 = __memo_scope.param(1, arg4), __memo_parameter_arg5 = __memo_scope.param(2, arg5); if (__memo_scope.unchanged) { @@ -68,7 +68,7 @@ function memo_arg_call_with_lowering(__memo_context: __memo_context_type, __memo return; } } -function args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: int, @memo() gensym%%_?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int), gensym%%_?: int, arg4?: int): void { +@functions.OptionalParametersAnnotation({minArgCount:0}) function args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: int, @memo() gensym%%_?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int), gensym%%_?: int, arg4?: int): void { let arg1: int = (((gensym%%_) !== (undefined)) ? gensym%%_ : (10 as int)); let arg2: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int) = (((gensym%%_) !== (undefined)) ? gensym%%_ : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): int => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts index 7f326a4c0..f023fef13 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts @@ -98,7 +98,7 @@ function main() {} return; } }); -function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, f?: (()=> void)): void { +@functions.OptionalParametersAnnotation({minArgCount:0}) function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, f?: (()=> void)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); const __memo_parameter_f = __memo_scope.param(0, f); if (__memo_scope.unchanged) { @@ -110,8 +110,8 @@ function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, f?: return; } } -function par(f?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} -function kar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() f?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { +@functions.OptionalParametersAnnotation({minArgCount:0}) function par(f?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +@functions.OptionalParametersAnnotation({minArgCount:0}) function kar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() f?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); const __memo_parameter_f = __memo_scope.param(0, f); if (__memo_scope.unchanged) { @@ -124,7 +124,7 @@ function kar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @me } } class A { - public foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, p?: (()=> void)): void { + @functions.OptionalParametersAnnotation({minArgCount:0}) public foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, p?: (()=> void)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); const __memo_parameter_p = __memo_scope.param(0, p); if (__memo_scope.unchanged) { @@ -136,8 +136,8 @@ class A { return; } } - public goo(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} - public koo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { + @functions.OptionalParametersAnnotation({minArgCount:0}) public goo(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} + @functions.OptionalParametersAnnotation({minArgCount:0}) public koo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); const __memo_parameter_p = __memo_scope.param(0, p); if (__memo_scope.unchanged) { diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts index b6ac3bd35..4f6e3fa92 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts @@ -94,11 +94,11 @@ function main() {} return; } }); -function fullName(this: Person, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { +@functions.OptionalParametersAnnotation({minArgCount:1}) function fullName(this: Person, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { return; } -function foo(this: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} -function goo(a: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +@functions.OptionalParametersAnnotation({minArgCount:1}) function foo(this: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +@functions.OptionalParametersAnnotation({minArgCount:1}) function goo(a: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} class Person { public constructor() {} } diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts index c0f81bd4c..7657e1dd0 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts @@ -74,7 +74,7 @@ class A { public constructor() {} } class B { - public static $_invoke(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} + @functions.OptionalParametersAnnotation({minArgCount:0}) public static $_invoke(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} public constructor() {} } class C { @@ -89,7 +89,7 @@ class C { public constructor() {} } class D { - public static $_instantiate(factory: (()=> D), @memo() content?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): D { + @functions.OptionalParametersAnnotation({minArgCount:1}) public static $_instantiate(factory: (()=> D), @memo() content?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): D { return factory(); } public constructor() {} diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts index e85c7ccc7..1076e94fc 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts @@ -118,7 +118,7 @@ class Test { return; } } - public args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_1?: int, gensym%%_2?: (()=> int), gensym%%_3?: int, arg4?: int): void { + @functions.OptionalParametersAnnotation({minArgCount:0}) public args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_1?: int, gensym%%_2?: (()=> int), gensym%%_3?: int, arg4?: int): void { let arg1: int = (((gensym%%_1) !== (undefined)) ? gensym%%_1 : (10 as int)); let arg2: (()=> int) = (((gensym%%_2) !== (undefined)) ? gensym%%_2 : ((() => { return 20; @@ -137,7 +137,7 @@ class Test { return; } } - public optional_args(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1?: int, arg2?: (()=> int)): void { + @functions.OptionalParametersAnnotation({minArgCount:0}) public optional_args(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1?: int, arg2?: (()=> int)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 2); const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2); if (__memo_scope.unchanged) { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts index e8aa44ac8..1925eef83 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts @@ -40,6 +40,7 @@ const expectedScript: string = ` import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; import { memo as memo } from "@ohos.arkui.stateManagement"; +import { UIImageAnimatorAttribute as UIImageAnimatorAttribute } from "@ohos.arkui.component"; import { UISelectAttribute as UISelectAttribute } from "@ohos.arkui.component"; import { UITextInputAttribute as UITextInputAttribute } from "@ohos.arkui.component"; import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; @@ -48,7 +49,7 @@ import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { _rawfile as _rawfile } from "@ohos.arkui.component"; import { _r as _r } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; -import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, TextInput as TextInput, Select as Select, SelectOption as SelectOption, Margin as Margin } from "@ohos.arkui.component"; +import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, TextInput as TextInput, Select as Select, SelectOption as SelectOption, Margin as Margin, ImageAnimator as ImageAnimator } from "@ohos.arkui.component"; function main() {} @@ -104,6 +105,14 @@ function main() {} } as Margin)); return; }), _r("", "", "app.media.app_icon"), undefined, undefined); + ImageAnimator(@memo() ((instance: UIImageAnimatorAttribute): void => { + instance.images([{ + src: _r("", "", "app.media.aaa"), + }, { + src: _r("", "", "app.media.bbb"), + }]); + return; + }), undefined); })); } public constructor() {} diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index ce062418c..31984c2dd 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -481,3 +481,10 @@ KNativePointer impl_AstNodeEndConst(KNativePointer context, KNativePointer recei return const_cast(GetImpl()->AstNodeEndConst(_context, _receiver)); } KOALA_INTEROP_2(AstNodeEndConst, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_IsArrayExpression(KNativePointer nodePtr) +{ + auto node = reinterpret_cast(nodePtr); + return GetImpl()->IsArrayExpression(node); +} +KOALA_INTEROP_1(IsArrayExpression, KBoolean, KNativePointer) diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 551481a4f..78314c0cc 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -840,6 +840,10 @@ export class Es2pandaNativeModule { _CreateSourceRange(context: KNativePointer, start: KNativePointer, end: KNativePointer): KNativePointer { throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); } + + _IsArrayExpression(node: KPtr): KBoolean { + throw new Error('Not implemented'); + } } export function initEs2panda(): Es2pandaNativeModule { diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index a9bd53d70..536c1ef3f 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -73,7 +73,8 @@ import { BooleanLiteral, ObjectExpression, Property, - TemplateLiteral + TemplateLiteral, + ArrayExpression } from "../../generated" import { Es2pandaModifierFlags @@ -133,6 +134,7 @@ import { updateETSNewClassInstanceExpression } from "../node-utilities/ETSNewCla import { updateObjectExpression } from "../node-utilities/ObjectExpression" import { updateProperty } from "../node-utilities/Property" import { updateTemplateLiteral } from "../node-utilities/TemplateLiteral" +import { updateArrayExpression } from "../node-utilities/ArrayExpression"; export const factory = { get createIdentifier() { @@ -468,6 +470,12 @@ export const factory = { get updateTemplateLiteral(): (...args: Parameters) => TemplateLiteral { return updateTemplateLiteral; }, + get createArrayExpression(): (...args: Parameters) => ArrayExpression { + return ArrayExpression.createArrayExpression; + }, + get updateArrayExpression(): (...args: Parameters) => ArrayExpression { + return updateArrayExpression; + }, /** @deprecated */ createTypeParameter1_(name: Identifier, constraint?: TypeNode, defaultType?: TypeNode) { return TSTypeParameter.createTSTypeParameter(Identifier.create1Identifier(name.name), constraint, defaultType) diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index c8b9fcb70..a77ec8acd 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -59,6 +59,7 @@ export * from "../generated/peers/BlockExpression" export * from "../generated/peers/TSClassImplements" export * from "../generated/peers/BooleanLiteral" export * from "../generated/peers/TSArrayType" +export * from "../generated/peers/ArrayExpression"; export * from "./types" export * from "./utilities/private" diff --git a/koala-wrapper/src/arkts-api/node-utilities/ArrayExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ArrayExpression.ts new file mode 100644 index 000000000..320b0d678 --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/ArrayExpression.ts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArrayExpression, Expression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateArrayExpression(original: ArrayExpression, elements: readonly Expression[]): ArrayExpression { + if (isSameNativeObject(elements, original.elements)) { + return original; + } + const update = updateThenAttach( + ArrayExpression.updateArrayExpression, + attachModifiers, + attachOptionalAndDeclaration + ); + return update(original, elements); +} + +function attachOptionalAndDeclaration(node: ArrayExpression, original: ArrayExpression): ArrayExpression { + if (node.isDeclaration) { + node.setDeclaration(); + } + node.setOptional(original.isOptional); + return node; +} diff --git a/koala-wrapper/src/arkts-api/types.ts b/koala-wrapper/src/arkts-api/types.ts index ca450782c..7e97b8a7c 100644 --- a/koala-wrapper/src/arkts-api/types.ts +++ b/koala-wrapper/src/arkts-api/types.ts @@ -48,6 +48,7 @@ import { nodeByType } from './class-by-peer'; import { MemberExpression } from './to-be-generated/MemberExpression'; import { AnnotationUsage, + ArrayExpression, BlockStatement, ClassDefinition, ETSTypeReference, @@ -915,5 +916,6 @@ const pairs: [Es2pandaAstNodeType, { new (peer: KNativePointer): AstNode }][] = [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, ETSTypeReference], [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, ETSTypeReferencePart], [Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, ObjectExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ARRAY_EXPRESSION, ArrayExpression], ]; pairs.forEach(([nodeType, astNode]) => nodeByType.set(nodeType, astNode)); diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index 3125fb088..becf519db 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -45,6 +45,7 @@ import { isTemplateLiteral, isBlockExpression, isReturnStatement, + isArrayExpression, } from '../generated'; import { isEtsScript, @@ -202,6 +203,13 @@ function visitOuterExpression(node: AstNode, visitor: Visitor): AstNode { nodesVisitor(node.getArguments, visitor) ); } + if (isArrayExpression(node)) { + updated = true; + return factory.updateArrayExpression( + node, + nodesVisitor(node.elements, visitor) + ); + } return node; } diff --git a/koala-wrapper/src/generated/peers/ArrayExpression.ts b/koala-wrapper/src/generated/peers/ArrayExpression.ts index 200648cdb..717ce5f45 100644 --- a/koala-wrapper/src/generated/peers/ArrayExpression.ts +++ b/koala-wrapper/src/generated/peers/ArrayExpression.ts @@ -26,55 +26,81 @@ import { KNativePointer, nodeByType, ArktsObject, - unpackString -} from "../../reexport-for-generated" + unpackString, +} from '../../reexport-for-generated'; -import { AnnotatedExpression } from "./AnnotatedExpression" -import { Expression } from "./Expression" -import { Decorator } from "./Decorator" -import { ValidationInfo } from "./ValidationInfo" -import { TypeNode } from "./TypeNode" +import { AnnotatedExpression } from './AnnotatedExpression'; +import { Expression } from './Expression'; +import { Decorator } from './Decorator'; +import { ValidationInfo } from './ValidationInfo'; +import { TypeNode } from './TypeNode'; export class ArrayExpression extends AnnotatedExpression { - constructor(pointer: KNativePointer) { - super(pointer) - + constructor(pointer: KNativePointer) { + super(pointer); + } + static createArrayExpression(elements: readonly Expression[]): ArrayExpression { + return new ArrayExpression( + global.generatedEs2panda._CreateArrayExpression(global.context, passNodeArray(elements), elements.length) + ); + } + static updateArrayExpression( + original: ArrayExpression | undefined, + elements: readonly Expression[] + ): ArrayExpression { + return new ArrayExpression( + global.generatedEs2panda._UpdateArrayExpression( + global.context, + passNode(original), + passNodeArray(elements), + elements.length + ) + ); } get elements(): readonly Expression[] { - return unpackNodeArray(global.generatedEs2panda._ArrayExpressionElementsConst(global.context, this.peer)) + return unpackNodeArray(global.generatedEs2panda._ArrayExpressionElementsConst(global.context, this.peer)); } /** @deprecated */ setElements(elements: readonly Expression[]): this { - global.generatedEs2panda._ArrayExpressionSetElements(global.context, this.peer, passNodeArray(elements), elements.length) - return this + global.generatedEs2panda._ArrayExpressionSetElements( + global.context, + this.peer, + passNodeArray(elements), + elements.length + ); + return this; } get isDeclaration(): boolean { - return global.generatedEs2panda._ArrayExpressionIsDeclarationConst(global.context, this.peer) + return global.generatedEs2panda._ArrayExpressionIsDeclarationConst(global.context, this.peer); } get isOptional(): boolean { - return global.generatedEs2panda._ArrayExpressionIsOptionalConst(global.context, this.peer) + return global.generatedEs2panda._ArrayExpressionIsOptionalConst(global.context, this.peer); } /** @deprecated */ setDeclaration(): this { - global.generatedEs2panda._ArrayExpressionSetDeclaration(global.context, this.peer) - return this + global.generatedEs2panda._ArrayExpressionSetDeclaration(global.context, this.peer); + return this; } /** @deprecated */ setOptional(optional_arg: boolean): this { - global.generatedEs2panda._ArrayExpressionSetOptional(global.context, this.peer, optional_arg) - return this + global.generatedEs2panda._ArrayExpressionSetOptional(global.context, this.peer, optional_arg); + return this; } get decorators(): readonly Decorator[] { - return unpackNodeArray(global.generatedEs2panda._ArrayExpressionDecoratorsConst(global.context, this.peer)) + return unpackNodeArray(global.generatedEs2panda._ArrayExpressionDecoratorsConst(global.context, this.peer)); } get typeAnnotation(): TypeNode | undefined { - return unpackNode(global.generatedEs2panda._ArrayExpressionTypeAnnotationConst(global.context, this.peer)) + return unpackNode(global.generatedEs2panda._ArrayExpressionTypeAnnotationConst(global.context, this.peer)); } /** @deprecated */ setTsTypeAnnotation(typeAnnotation: TypeNode): this { - global.generatedEs2panda._ArrayExpressionSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) - return this + global.generatedEs2panda._ArrayExpressionSetTsTypeAnnotation( + global.context, + this.peer, + passNode(typeAnnotation) + ); + return this; } } export function isArrayExpression(node: AstNode): node is ArrayExpression { - return node instanceof ArrayExpression -} \ No newline at end of file + return global.es2panda._IsArrayExpression(node.peer); +} -- Gitee From 02f66861cbb793dbf0006f9e423c7a604b436ca9 Mon Sep 17 00:00:00 2001 From: wuhailong Date: Tue, 13 May 2025 20:48:55 +0800 Subject: [PATCH 090/123] Fix TSC_SYSTEM_CODE not imported Issue: #IC7K6B Signed-off-by: wuhailong Change-Id: I07092b70d16f2d3543e7021b5ba88e02fa6f9009 --- compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts index 46aecc9e8..4cf4bc9c5 100644 --- a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts @@ -29,7 +29,8 @@ import { emitBuildInfo, runArkTSLinter, targetESVersionChanged, - collectFileToIgnoreDiagnostics + collectFileToIgnoreDiagnostics, + TSC_SYSTEM_CODE } from '../../ets_checker'; import { TS_WATCH_END_MSG } from '../../pre_define'; import { -- Gitee From b9e92779280530027c1dcc5206eb66d2912ac91c Mon Sep 17 00:00:00 2001 From: l00913061 Date: Thu, 8 May 2025 11:00:06 +0800 Subject: [PATCH 091/123] update arkuicompatible Signed-off-by: l00913061 Change-Id: If5fe8dd64f0d55381f0ee39bf51f50b2c8c4a064 --- arkui-plugins/common/predefines.ts | 5 +- .../ui-plugins/checked-transformer.ts | 3 + .../ui-plugins/component-transformer.ts | 39 +- arkui-plugins/ui-plugins/interop.ts | 430 ++++++++++++++---- .../ui-plugins/legacy-transformer.ts | 16 +- 5 files changed, 381 insertions(+), 112 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 510f03fc5..d2be47af4 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -106,7 +106,7 @@ export enum InteroperAbilityNames { ARKTS_1_1 = '1.1', ARKTS_1_2 = '1.2', ARKUICOMPATIBLE = 'ArkUICompatible', - ESOBJECT = 'ESObject', + ESVALUE = 'ESValue', ELMTID = 'elmtId', INITEMPTYOBJECT = 'instantiateEmptyObject', SETPROPERTY = 'setProperty', @@ -114,7 +114,7 @@ export enum InteroperAbilityNames { PARENT = 'parent', INSTANCE = 'instance', PARAM = 'param', - EXTRAINFO = 'extrainfo', + EXTRAINFO = 'extraInfo', COMPONENT = 'component', GETPROPERTY = 'getProperty', CONSTRUCTOR = 'constructor', @@ -127,4 +127,5 @@ export enum InteroperAbilityNames { WRAPSTRING = 'wrapString', PARAMSLAMBDA = 'paramsLambda', INTEROPCOMPONENT = 'interopComponent', + OHMURL = '@normalized:N&entry&com.example.Interop2use1&har1/src/main/ets/components/MainPage&1.0.0', } diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 08c246d38..16e565d63 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -46,6 +46,7 @@ import { isEntryWrapperClass } from './entry-translators/utils'; import { classifyObservedTrack, classifyProperty, PropertyTranslator } from './property-translators'; import { ObservedTrackTranslator } from './property-translators/observedTrack'; import { nodeByType } from '@koalaui/libarkts/build/src/reexport-for-generated'; +import { updateStateVar } from './interop'; export class CheckedTransformer extends AbstractVisitor { private scopeInfoCollection: ScopeInfoCollection; @@ -117,6 +118,8 @@ export class CheckedTransformer extends AbstractVisitor { } else if (arkts.isClassDeclaration(node)) { return transformObservedTracked(node); + } else if (arkts.isCallExpression(node)) { + return updateStateVar(node); } return node; } diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 75429bc42..5fce81159 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -38,6 +38,7 @@ import { } from './ui-factory'; import { StructMap } from '../common/program-visitor'; import { processStructCall } from './interop'; +import { stringify } from 'querystring'; export interface ComponentTransformerOptions extends VisitorOptions { arkui?: string; @@ -54,6 +55,13 @@ interface ComponentContext { structMembers: Map; } +export interface InteropContext { + className: string; + path: string; + stateVarMap: Map; + arguments?: arkts.ObjectExpression; +} + export class ComponentTransformer extends AbstractVisitor { private scopeInfos: ScopeInfo[] = []; private componentInterfaceCollection: arkts.TSInterfaceDeclaration[] = []; @@ -66,6 +74,7 @@ export class ComponentTransformer extends AbstractVisitor { private hasLegacy = false; private legacyStructMap: Map = new Map(); private legacyCallMap: Map = new Map(); + private stateVarMap: Map = new Map(); constructor(options?: ComponentTransformerOptions) { const _options: ComponentTransformerOptions = options ?? {}; @@ -85,6 +94,7 @@ export class ComponentTransformer extends AbstractVisitor { this.hasLegacy = false; this.legacyStructMap = new Map(); this.legacyCallMap = new Map(); + this.stateVarMap = new Map(); } enter(node: arkts.AstNode) { @@ -341,10 +351,12 @@ export class ComponentTransformer extends AbstractVisitor { arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); if (member.annotations.length > 0 && !hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { + const type = getStateManagementType(member); + this.stateVarMap.set(originalName, type); const newMember: arkts.ClassProperty = createOptionalClassProperty( newName, member, - getStateManagementType(member), + type, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); return [originMember, newMember]; @@ -375,6 +387,7 @@ export class ComponentTransformer extends AbstractVisitor { } } } + this.legacyCallMap.set('Child1', 'har1/src/main/ets/components/MainPage'); } visitor(node: arkts.AstNode): arkts.AstNode { @@ -395,14 +408,24 @@ export class ComponentTransformer extends AbstractVisitor { this.processImport(newNode); } if (arkts.isCallExpression(newNode)) { - if (this.legacyCallMap.has(newNode.expression?.name)) { - const pathName = this.legacyCallMap.get(newNode.expression?.name)!; + const ident = newNode.expression; + if (!(ident instanceof arkts.Identifier)) { + return newNode; + } + const className = ident.name; + if (this.legacyCallMap.has(className)) { + const path = this.legacyCallMap.get(className)!; + // const pathName = 'path/har1'; const args = newNode.arguments; - if (args === undefined || args.length > 1 || !(args[0] instanceof arkts.ObjectExpression)) { - return processStructCall(newNode, pathName); - } - const arg = args[0]; - return processStructCall(newNode, pathName, arg); + const context: InteropContext = { + className: className, + path: path, + stateVarMap: this.stateVarMap, + arguments: args && args.length === 1 && args[0] instanceof arkts.ObjectExpression + ? args[0] + : undefined + }; + return processStructCall(context); } } return newNode; diff --git a/arkui-plugins/ui-plugins/interop.ts b/arkui-plugins/ui-plugins/interop.ts index 5b75b3df2..c8293d7dd 100644 --- a/arkui-plugins/ui-plugins/interop.ts +++ b/arkui-plugins/ui-plugins/interop.ts @@ -18,8 +18,9 @@ import * as arkts from '@koalaui/libarkts'; import { InteroperAbilityNames } from '../common/predefines'; import { getCustomComponentOptionsName } from './utils'; +import { InteropContext } from './component-transformer'; -export function createEmptyESObject(name: string): arkts.VariableDeclaration { +export function createEmptyESValue(name: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, @@ -29,7 +30,7 @@ export function createEmptyESObject(name: string): arkts.VariableDeclaration { arkts.factory.createIdentifier(name), arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT), + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), arkts.factory.createIdentifier(InteroperAbilityNames.INITEMPTYOBJECT), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, @@ -43,17 +44,17 @@ export function createEmptyESObject(name: string): arkts.VariableDeclaration { ); } -export function getWrapValue(value: arkts.AstNode): arkts.AstNode { +export function getWrapValue(value: arkts.AstNode, type?: string): arkts.AstNode { let wrapMethod = InteroperAbilityNames.WRAP; - if (value instanceof arkts.StringLiteral) { + if (!!type && value instanceof arkts.StringLiteral) { wrapMethod = InteroperAbilityNames.WRAPSTRING; - } else if (value instanceof arkts.NumberLiteral) { + } else if (!!type && value instanceof arkts.NumberLiteral) { wrapMethod = InteroperAbilityNames.WRAPINT; } return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT), + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), arkts.factory.createIdentifier(wrapMethod), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, @@ -64,7 +65,7 @@ export function getWrapValue(value: arkts.AstNode): arkts.AstNode { ); } -export function setPropertyESObject(name: string, key: arkts.StringLiteral, value: arkts.AstNode): arkts.ExpressionStatement { +export function setPropertyESValue(name: string, key: arkts.StringLiteral, wrapValue: arkts.AstNode): arkts.ExpressionStatement { return arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -77,13 +78,13 @@ export function setPropertyESObject(name: string, key: arkts.StringLiteral, valu undefined, [ key, - getWrapValue(value) + wrapValue ] ) ); } -export function getPropertyESObject(result: string, object: string, key: string): arkts.VariableDeclaration { +export function getPropertyESValue(result: string, object: string, key: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, @@ -107,7 +108,9 @@ export function getPropertyESObject(result: string, object: string, key: string) ); } -function initialArgs(name: string, args?: arkts.ObjectExpression): arkts.Statement[] { +function initialArgs(name: string, context: InteropContext): arkts.Statement[] { + const args = context.arguments; + const stateVarMap = context.stateVarMap; if (!args) { return []; } @@ -118,39 +121,20 @@ function initialArgs(name: string, args?: arkts.ObjectExpression): arkts.Stateme continue; } const key = property.key; - const value = property.value; + if (!(key instanceof arkts.Identifier)){ + throw Error('Error arguments in Legacy Component'); + } + const value = property.value!; + const type = stateVarMap.get(key.name); const key_string = arkts.factory.createStringLiteral(key.name); - const setProperty = setPropertyESObject(name, key_string, value); + const wrapValue = getWrapValue(value, type); + const setProperty = setPropertyESValue(name, key_string, wrapValue); result.push(setProperty); } return result; } -function getModule(moduleName: string): arkts.VariableDeclaration { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(InteroperAbilityNames.MODULE), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT), - arkts.factory.createIdentifier(InteroperAbilityNames.LOAD), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [arkts.factory.create1StringLiteral(moduleName)] - ) - ) - ] - ); -} - -function instantiateComonent(params: arkts.AstNode[]): arkts.VariableDeclaration { +function instantiateComponent(params: arkts.AstNode[]): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, @@ -234,70 +218,259 @@ function createInitReturn(componentName: string): arkts.ReturnStatement { ); } -function createWrapperBlock(name: string, path: string, args?: arkts.ObjectExpression): arkts.BlockStatement { - const index = path.indexOf('/'); - if (index === -1) { - throw new Error('Error path of Legacy Component.'); - } - const moduleName = path.substring(0, index); - const blankLambda = arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - arkts.factory.createBlock([]), - arkts.factory.createFunctionSignature( +function createExtraInfo(properties: string[], value: string[]): arkts.Statement[] { + const body: arkts.AstNode[] = []; + body.push(createEmptyESValue(InteroperAbilityNames.EXTRAINFO)); + properties.forEach((prop, index) => { + const val = value[index]; + body.push(setPropertyESValue( + InteroperAbilityNames.EXTRAINFO, + arkts.factory.createStringLiteral(prop), + arkts.factory.createStringLiteral(val)) + ); + }) + return body; +} + +function createESParent(): arkts.Statement { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier('esparent'), + getWrapValue(arkts.factory.createIdentifier(InteroperAbilityNames.PARENT)) + ) + ] + ); +} + +function createESUndefined(): arkts.Statement { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier('esundefined'), + getWrapValue(arkts.factory.createUndefinedLiteral()) + ) + ] + ); +} + +function createESBlank(): arkts.Statement[] { + const body: arkts.Statement[] = []; + const blank = arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier('blank'), + arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + arkts.factory.createBlock([]), + arkts.factory.createFunctionSignature( + undefined, + [], + undefined, + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ) + ) + ] + ) + body.push(blank); + const asExpression = arkts.factory.createTSAsExpression( + arkts.factory.createIdentifier('blank'), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('object') + ) + ), + false + ); + const esblank = arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier('esblank'), + getWrapValue(asExpression) + ) + ] + ) + body.push(esblank); + return body; +} + +function createELMTID(): arkts.Statement[] { + const body: arkts.Statement[] = []; + const global = arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier('global'), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), + arkts.factory.createIdentifier('getGlobal'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), undefined, - [], + undefined + ) + )] + ); + body.push(global); + const viewStackProcessor = getPropertyESValue('viewStackProcessor', 'global', 'ViewStackProcessor'); + body.push(viewStackProcessor); + const createId = getPropertyESValue('createId', 'viewStackProcessor', 'AllocateNewElmetIdForNextComponent'); + body.push(createId); + const elmtId = arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('createId'), + arkts.factory.createIdentifier('invoke'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), undefined, + undefined + ) + )] + ); + body.push(elmtId); + return body; +} + +function createComponent(moduleName: string, className: string): arkts.Statement[] { + const body: arkts.Statement[] = []; + const module = arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier(moduleName), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), + arkts.factory.createIdentifier(InteroperAbilityNames.LOAD), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [arkts.factory.create1StringLiteral(InteroperAbilityNames.OHMURL)] + ) + ) + ] + ); + body.push(module); + const structObject = getPropertyESValue('structObject', moduleName, className); + body.push(structObject); + const component = instantiateComponent( + [ + arkts.factory.createIdentifier('esundefined'), + arkts.factory.createIdentifier(InteroperAbilityNames.PARAM), + arkts.factory.createIdentifier('esundefined'), + arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID), + arkts.factory.createIdentifier('esblank'), + arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO) + ] + ) + body.push(component); + return body; +} + +function invokeViewPUCreate(): arkts.Statement[] { + const body: arkts.Statement[] = []; + const createMethod = getPropertyESValue('create', 'structObject', 'create'); + body.push(createMethod); + const viewPUCreate = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('create'), + arkts.factory.createIdentifier('invoke'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, false ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, + [ + arkts.factory.createIdentifier('component') + ] ) - ); - const initialArgsStatement = initialArgs(InteroperAbilityNames.PARAM, args); + ) + body.push(viewPUCreate); + return body; +} + +function createWrapperBlock(context: InteropContext): arkts.BlockStatement { + const className = context.className; + const path = context.path; + const args = context.arguments; + const index = path.indexOf('/'); + if (index === -1) { + throw new Error('Error path of Legacy Component.'); + } + const moduleName = path.substring(0, index); + const initialArgsStatement = initialArgs(InteroperAbilityNames.PARAM, context); return arkts.factory.createBlock( [ - createEmptyESObject(InteroperAbilityNames.PARAM), + createEmptyESValue(InteroperAbilityNames.PARAM), ...initialArgsStatement, - createEmptyESObject(InteroperAbilityNames.EXTRAINFO), - setPropertyESObject(InteroperAbilityNames.EXTRAINFO, arkts.factory.create1StringLiteral('page'), arkts.factory.createStringLiteral(path)), - getModule(moduleName), - getPropertyESObject(InteroperAbilityNames.STRUCTOBJECT, InteroperAbilityNames.MODULE, name), - instantiateComonent([ - arkts.factory.createIdentifier(InteroperAbilityNames.PARENT), - arkts.factory.createIdentifier(InteroperAbilityNames.PARAM), - arkts.factory.createUndefinedLiteral(), - arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID), - blankLambda, - arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO) - ]), - ...paramsLambdaDeclaration(name, args), - setPropertyESObject( - InteroperAbilityNames.COMPONENT, - arkts.factory.create1StringLiteral('paramsGenerator_'), - arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA) - ), - createInitReturn(name) + ...createExtraInfo(['page'], [path]), + // createESParent(), + createESUndefined(), + ...createESBlank(), + ...createELMTID(), + ...createComponent(moduleName, className), + ...invokeViewPUCreate(), + // ...paramsLambdaDeclaration(className, args), + // setPropertyESValue( + // 'component', + // arkts.factory.create1StringLiteral('paramsGenerator_'), + // arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA) + // ), + createInitReturn(className) ] ); } -function createInitializer(name: string, number: arkts.ETSTypeReference, esobject: arkts.ETSTypeReference, - path: string, args?: arkts.ObjectExpression): arkts.ArrowFunctionExpression { - const block = createWrapperBlock(name, path, args); +function createInitializer(context: InteropContext): arkts.ArrowFunctionExpression { + const block = createWrapperBlock(context); + const builderNode = arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('BuilderNode') + ) + ) return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( block, arkts.factory.createFunctionSignature( undefined, [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, number), - undefined, - ), - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, esobject), - undefined, - ), + // arkts.factory.createParameterDeclaration( + // arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, builderNode), + // undefined, + // ), ], undefined, false, @@ -308,7 +481,7 @@ function createInitializer(name: string, number: arkts.ETSTypeReference, esobjec ); } -function createUpdater(number: arkts.ETSTypeReference, esobject: arkts.ETSTypeReference): arkts.ArrowFunctionExpression { +function createUpdater(number: arkts.ETSTypeReference, esvalue: arkts.ETSTypeReference): arkts.ArrowFunctionExpression { return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( arkts.factory.createBlock( @@ -324,7 +497,7 @@ function createUpdater(number: arkts.ETSTypeReference, esobject: arkts.ETSTypeRe undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, esvalue), undefined, ), ], @@ -337,23 +510,20 @@ function createUpdater(number: arkts.ETSTypeReference, esobject: arkts.ETSTypeRe ); } -export function processStructCall(node: arkts.CallExpression, path: string, args?: arkts.ObjectExpression): arkts.CallExpression { +export function processStructCall(context: InteropContext): arkts.CallExpression { const number = arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier(InteroperAbilityNames.NUMBER) ) ); - const esobject = arkts.factory.createTypeReference( + const esvalue = arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT) + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) ) ); - const ident = node.expression; - if (!(ident instanceof arkts.Identifier)) { - throw new Error('Unexpected name of legacy component.'); - } - const initializer = createInitializer(ident.name, number, esobject, path, args); - const updater = createUpdater(number, esobject); + const initializer = createInitializer(context); + // console.log('print intt:'+ initializer.dumpSrc()); + const updater = createUpdater(number, esvalue); return arkts.factory.createCallExpression( arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), undefined, @@ -362,4 +532,76 @@ export function processStructCall(node: arkts.CallExpression, path: string, args updater, ] ); +} + +export function updateStateVar(node: arkts.CallExpression): arkts.CallExpression { + const ident = node.expression; + if (!(ident instanceof arkts.Identifier)) { + return node; + } + const name = ident.name; + if (name !== 'ArkUICompatible') { + return node; + } + const init = node.arguments[0] as arkts.ArrowFunctionExpression; + const script = init.scriptFunction; + const body = script.body as arkts.BlockStatement; + const statements = body.statements; + const varStatement = statements[1].expression as arkts.CallExpression; + const params = varStatement.arguments; + const wrapVar = params[1] as arkts.CallExpression; + const stateVar = wrapVar.arguments[0] as arkts.MemberExpression; + const newStateVar = arkts.factory.updateMemberExpression( + stateVar, + stateVar.object, + arkts.factory.createIdentifier('__backing_' + stateVar.property.name), + stateVar.kind, + stateVar.computed, + stateVar.optional + ); + const newWrapVar = arkts.factory.updateCallExpression( + wrapVar, + wrapVar.expression, + wrapVar.typeArguments, + [newStateVar], + ); + const newVarStatement = arkts.factory.updateCallExpression( + varStatement, + varStatement.expression, + varStatement.typeArguments, + [params[0], newWrapVar] + ); + const newBody = arkts.factory.updateBlock( + body, + [ + statements[0], + newVarStatement, + ...statements.slice(2) + ] + ); + const newInit = arkts.factory.updateArrowFunction( + init, + arkts.factory.updateScriptFunction( + script, + newBody, + arkts.factory.createFunctionSignature( + script.typeParams, + script.params, + script.returnTypeAnnotation, + script.hasReceiver, + ), + script.flags, + script.modifiers + ) + ); + const newNode = arkts.factory.updateCallExpression( + node, + node.expression, + node.typeArguments, + [ + newInit, + node.arguments[1] + ], + ); + return newNode; } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/legacy-transformer.ts b/arkui-plugins/ui-plugins/legacy-transformer.ts index 0bccdd7f8..c23c888b2 100644 --- a/arkui-plugins/ui-plugins/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/legacy-transformer.ts @@ -67,9 +67,9 @@ export class LegacyTransformer extends AbstractVisitor { } processConstructor(node: arkts.MethodDefinition): arkts.MethodDefinition { - const esobject = arkts.factory.createTypeReference( + const esvalue = arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(InteroperAbilityNames.ESOBJECT) + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) ) ); const script = arkts.factory.createScriptFunction( @@ -78,27 +78,27 @@ export class LegacyTransformer extends AbstractVisitor { undefined, [ arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, esvalue), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.PARAM, esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.PARAM, esvalue), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('localStorage', esobject), + arkts.factory.createIdentifier('localStorage', esvalue), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, esvalue), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA, esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA, esvalue), undefined, ), arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO, esobject), + arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO, esvalue), undefined, ) ], undefined, false), -- Gitee From 2cba6f79f3d33a9b39cc5bd498a7daa9b27a2604 Mon Sep 17 00:00:00 2001 From: Cuecuexiaoyu Date: Wed, 14 May 2025 15:07:52 +0800 Subject: [PATCH 092/123] fix incremental compilation bug Signed-off-by: Cuecuexiaoyu Change-Id: Idd6fd86a625a45f9de1b005812ddf90cb66409bc --- koala-wrapper/src/arkts-api/utilities/public.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index 2b21e625b..1ebdd1b26 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -45,13 +45,20 @@ import { MemberExpression } from '../to-be-generated/MemberExpression'; export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { console.log('[TS WRAPPER] PROCEED TO STATE: ', getEnumName(Es2pandaContextState, state)); + if (global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR) { + processErrorState(state, forceDtsEmit); + } if (state <= global.es2panda._ContextState(global.context)) { console.log('[TS WRAPPER] PROCEED TO STATE: SKIPPING'); return; } clearNodeCache(); + global.es2panda._ProceedToState(global.context, state); + processErrorState(state, forceDtsEmit); +} + +function processErrorState(state: Es2pandaContextState, forceDtsEmit = false): void { try { - global.es2panda._ProceedToState(global.context, state); if ( global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && !forceDtsEmit -- Gitee From d05761cd5d2df858e02362aa9be54513a4820de2 Mon Sep 17 00:00:00 2001 From: zenghang Date: Wed, 14 May 2025 10:27:18 +0800 Subject: [PATCH 093/123] fix compile oh_modules mixed Issue: IC7PSG Signed-off-by: zenghang Change-Id: I81bca159044a0999aeffde139f30e8c341377a01 --- compiler/main.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/compiler/main.js b/compiler/main.js index 95d20e602..c9d6a4e88 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -1167,6 +1167,10 @@ function initMain() { abilityConfig.abilityType = process.env.abilityType || 'page'; } +/** + * due to some oh_modules is different with the original arkTs module. + * Some branches were not reached, causing some information to be uninitialized. + */ function initMixCompileHar(projectConfig) { projectConfig.isRemoteModule = process.env.isRemoteModule === 'true'; projectConfig.mixCompile = process.env.mixCompile === 'true'; @@ -1174,6 +1178,13 @@ function initMixCompileHar(projectConfig) { projectConfig.compileHar = true; process.env.compileMode = 'moduleJson'; getPackageJsonEntryPath(); + /** + * ets-loader will generate decl file from projectConfig.intentEntry which init in setIntentEntryPages. + * aceModuleJsonPath->ark_modules.json + * when compile oh_module with ets-loader, aceModuleJsonPath will be undefined. + * so projectConfig.intentEntry is empty. + */ + setIntentEntryPages(projectConfig); } } -- Gitee From bce89088c8bf443b624f2a65aa28d754b55c4af8 Mon Sep 17 00:00:00 2001 From: Yuxin Feng Date: Fri, 16 May 2025 15:09:28 +0800 Subject: [PATCH 094/123] XComponent transform Signed-off-by: Yuxin Feng Change-Id: I7c0d40e205f8d7e08e3b60992a9fea31704739c9 --- .../demo/mock/xcomponent/xcomponent-basic.ets | 19 +++ .../animation/animation-basic.test.ts | 2 +- .../xcomponent/xcomponent-basic.test.ts | 132 ++++++++++++++++++ .../builder-lambda-translators/factory.ts | 60 ++++---- .../ui-plugins/checked-transformer.ts | 11 +- .../ui-plugins/struct-translators/factory.ts | 51 +++++++ 6 files changed, 239 insertions(+), 36 deletions(-) create mode 100644 arkui-plugins/test/demo/mock/xcomponent/xcomponent-basic.ets create mode 100644 arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts diff --git a/arkui-plugins/test/demo/mock/xcomponent/xcomponent-basic.ets b/arkui-plugins/test/demo/mock/xcomponent/xcomponent-basic.ets new file mode 100644 index 000000000..aa644d5ed --- /dev/null +++ b/arkui-plugins/test/demo/mock/xcomponent/xcomponent-basic.ets @@ -0,0 +1,19 @@ +import {Component, Flex, XComponent, FlexDirection, XComponentType, Entry, XComponentController, ItemAlign, FlexAlign, XComponentParameter} from '@ohos.arkui.component' + +@Entry +@Component +struct Index { + myXComponentController: XComponentController = new XComponentController(); + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) { + XComponent({ + id: 'xComponentId', + type: XComponentType.TEXTURE, + libraryname: 'nativerender', + controller: this.myXComponentController + } as XComponentParameter) + } + .width('100%') + .height('100%') + } +} \ No newline at end of file diff --git a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts index 732dd8d69..cae171a65 100644 --- a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts @@ -110,7 +110,7 @@ function testAnimationTransformer(this: PluginTestContext): void { } pluginTester.run( - 'test observed only transform', + 'test basic animation transform', [animationTransform, uiNoRecheck], { checked: [testAnimationTransformer], diff --git a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts new file mode 100644 index 000000000..46686c1e6 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { uiNoRecheck } from '../../../utils/plugins'; +import { uiTransform } from '../../../../ui-plugins'; +import { Plugins } from '../../../../common/plugin-context'; + +const XCOMPONENT_DIR_PATH: string = 'xcomponent'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, XCOMPONENT_DIR_PATH, 'xcomponent-basic.ets'), +]; + +const xcomponentTransform: Plugins = { + name: 'xcomponent', + parsed: uiTransform().parsed, +} + +const pluginTester = new PluginTester('test basic XComponent transform', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; + +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; + +import { memo as memo } from "@ohos.arkui.stateManagement"; + +import { UIXComponentAttribute as UIXComponentAttribute } from "@ohos.arkui.component"; + +import { UIFlexAttribute as UIFlexAttribute } from "@ohos.arkui.component"; + +import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; + +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; + +import { Component as Component, Flex as Flex, XComponent as XComponent, FlexDirection as FlexDirection, XComponentType as XComponentType, Entry as Entry, XComponentController as XComponentController, ItemAlign as ItemAlign, FlexAlign as FlexAlign, XComponentParameter as XComponentParameter } from "@ohos.arkui.component"; + +function main() {} + + + +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { + public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { + (this).__backing_myXComponentController = ((({let gensym___221905990 = initializers; + (((gensym___221905990) == (null)) ? undefined : gensym___221905990.myXComponentController)})) ?? (new XComponentController())); + } + + public __updateStruct(initializers: __Options_Index | undefined): void {} + + private __backing_myXComponentController?: XComponentController; + + public get myXComponentController(): XComponentController { + return ((this).__backing_myXComponentController as XComponentController); + } + + public set myXComponentController(value: XComponentController) { + (this).__backing_myXComponentController = value; + } + + @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { + Flex(@memo() ((instance: UIFlexAttribute): void => { + instance.width("100%").height("100%"); + return; + }), { + direction: FlexDirection.Column, + alignItems: ItemAlign.Center, + justifyContent: FlexAlign.Start, + }, (() => { + XComponent(undefined, ({ + id: "xComponentId", + type: XComponentType.TEXTURE, + libraryname: "nativerender", + controller: (this).myXComponentController, + } as XComponentParameter), "", undefined); + })); + } + + public constructor() {} + +} + +interface __Options_Index { + set myXComponentController(myXComponentController: XComponentController | undefined) + + get myXComponentController(): XComponentController | undefined + +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + Index._instantiateImpl(undefined, (() => { + return new Index(); + }), undefined, undefined, undefined); + } + + public constructor() {} + +} +`; + +function testXComponentTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test basic XComponent transform', + [xcomponentTransform, uiNoRecheck], + { + checked: [testXComponentTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index b3d415a74..e4572d2f4 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -35,6 +35,7 @@ import { } from './utils'; import { DecoratorNames } from '../property-translators/utils'; import { factory as PropertyFactory } from '../property-translators/factory'; +import { ProjectConfig } from '../../common/plugin-context'; export class factory { /* @@ -115,7 +116,7 @@ export class factory { /* * create style instance call, e.g. `instance.margin(10)`. */ - static createStyleLambdaBody(lambdaBody: arkts.AstNode, call: arkts.CallExpression): arkts.CallExpression { + static createStyleLambdaBody(lambdaBody: arkts.AstNode, call: arkts.CallExpression, projectConfig: ProjectConfig | undefined): arkts.CallExpression { const newArgs: arkts.Expression[] = factory.getTransformedStyle(call); return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -128,7 +129,7 @@ export class factory { undefined, newArgs.map((arg) => { if (arkts.isArrowFunctionExpression(arg)) { - return this.processArgArrowFunction(arg); + return this.processArgArrowFunction(arg, projectConfig); } return arg; }) @@ -229,14 +230,14 @@ export class factory { * If a builder lambda's argument is an arrow function, * then transform any builder lambda in the function body. */ - static processArgArrowFunction(arg: arkts.ArrowFunctionExpression): arkts.ArrowFunctionExpression { + static processArgArrowFunction(arg: arkts.ArrowFunctionExpression, projectConfig: ProjectConfig | undefined): arkts.ArrowFunctionExpression { const func: arkts.ScriptFunction = arg.scriptFunction; const updateFunc = arkts.factory.updateScriptFunction( func, !!func.body && arkts.isBlockStatement(func.body) ? arkts.factory.updateBlock( func.body, - func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st)) + func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st, projectConfig)) ) : undefined, arkts.FunctionSignature.createFunctionSignature( @@ -334,14 +335,14 @@ export class factory { */ static createOrUpdateArgInBuilderLambda( arg: arkts.Expression | undefined, + projectConfig: ProjectConfig | undefined, typeName?: string, - fallback?: arkts.AstNode ): arkts.AstNode { if (!arg) { - return fallback ?? arkts.factory.createUndefinedLiteral(); + return arkts.factory.createUndefinedLiteral(); } if (arkts.isArrowFunctionExpression(arg)) { - return this.processArgArrowFunction(arg); + return this.processArgArrowFunction(arg, projectConfig); } // this is too optimistic to check if this is an options argument... if (arkts.isTSAsExpression(arg) || arkts.isObjectExpression(arg)) { @@ -356,42 +357,47 @@ export class factory { static generateArgsInBuilderLambda( leaf: arkts.CallExpression, lambdaBody: arkts.Identifier | arkts.CallExpression, - declInfo: BuilderLambdaDeclInfo + declInfo: BuilderLambdaDeclInfo, + projectConfig: ProjectConfig | undefined ): (arkts.AstNode | undefined)[] { const { params, returnType } = declInfo; const typeName: string | undefined = builderLambdaTypeName(leaf); const args: (arkts.AstNode | undefined)[] = [this.createStyleArgInBuilderLambda(lambdaBody, returnType)]; let index = 0; while (index < params.length) { - const isReusable: boolean = typeName - ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable - : false; - if (isReusable && index === params.length - 1) { - const reuseId = arkts.factory.createStringLiteral(typeName!); - args.push(this.createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), typeName, reuseId)); - } else { - args.push(this.createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), typeName)); - } + args.push(this.createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), projectConfig, typeName)); index++; } + const isReusable: boolean = typeName + ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable : false; + if (isReusable) { + args.splice(-1, 1, arkts.factory.createStringLiteral(typeName!)); + } + else if (typeName === 'XComponent') { + let packageInfo: string = ''; + if (projectConfig?.bundleName && projectConfig?.moduleName) { + packageInfo = projectConfig?.bundleName + '/' + projectConfig?.moduleName; + } + args.splice(args.length - 1, 0, arkts.factory.createStringLiteral(packageInfo)); + } return args; } /** * update if-else in trailing lambda contents in a builder lambda call. */ - static updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode): arkts.AstNode { + static updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, projectConfig: ProjectConfig | undefined): arkts.AstNode { if (arkts.isIfStatement(statement)) { const alternate = !!statement.alternate - ? this.updateIfElseContentBodyInBuilderLambda(statement.alternate) + ? this.updateIfElseContentBodyInBuilderLambda(statement.alternate, projectConfig) : statement.alternate; - const consequence = this.updateIfElseContentBodyInBuilderLambda(statement.consequent); + const consequence = this.updateIfElseContentBodyInBuilderLambda(statement.consequent, projectConfig); return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); } if (arkts.isBlockStatement(statement)) { return arkts.factory.updateBlock( statement, - statement.statements.map((st) => this.updateContentBodyInBuilderLambda(st)) + statement.statements.map((st) => this.updateContentBodyInBuilderLambda(st, projectConfig)) ); } return statement; @@ -400,7 +406,7 @@ export class factory { /** * update trailing lambda contents in a builder lambda call. */ - static updateContentBodyInBuilderLambda(statement: arkts.Statement): arkts.Statement { + static updateContentBodyInBuilderLambda(statement: arkts.Statement, projectConfig: ProjectConfig | undefined): arkts.Statement { if ( arkts.isExpressionStatement(statement) && arkts.isCallExpression(statement.expression) && @@ -408,11 +414,11 @@ export class factory { ) { return arkts.factory.updateExpressionStatement( statement, - this.transformBuilderLambda(statement.expression) + this.transformBuilderLambda(statement.expression, projectConfig) ); } if (arkts.isIfStatement(statement)) { - return this.updateIfElseContentBodyInBuilderLambda(statement); + return this.updateIfElseContentBodyInBuilderLambda(statement, projectConfig); } return statement; @@ -498,7 +504,7 @@ export class factory { /** * transform `@ComponentBuilder` in non-declared calls. */ - static transformBuilderLambda(node: arkts.CallExpression): arkts.AstNode { + static transformBuilderLambda(node: arkts.CallExpression, projectConfig: ProjectConfig | undefined): arkts.AstNode { let instanceCalls: arkts.CallExpression[] = []; let leaf: arkts.CallExpression = node; @@ -528,11 +534,11 @@ export class factory { this.updateAnimation(instanceCalls); lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); instanceCalls.forEach((call) => { - lambdaBody = this.createStyleLambdaBody(lambdaBody!, call); + lambdaBody = this.createStyleLambdaBody(lambdaBody!, call, projectConfig); }); } - const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo); + const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, projectConfig); return arkts.factory.updateCallExpression(node, replace, leaf.typeArguments, filterDefined(args)); } diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index ff99c5843..9ab64ff2b 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -84,7 +84,7 @@ export class CheckedTransformer extends AbstractVisitor { visitor(beforeChildren: arkts.AstNode): arkts.AstNode { this.enter(beforeChildren); if (arkts.isCallExpression(beforeChildren) && isBuilderLambda(beforeChildren)) { - const lambda = builderLambdaFactory.transformBuilderLambda(beforeChildren); + const lambda = builderLambdaFactory.transformBuilderLambda(beforeChildren, this.projectConfig); return this.visitEachChild(lambda); } else if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren)) { const lambda = builderLambdaFactory.transformBuilderLambdaMethodDecl(beforeChildren); @@ -115,13 +115,8 @@ export class CheckedTransformer extends AbstractVisitor { return addMemoAnnotation(node); } else if (arkts.isClassDeclaration(node)) { return transformObservedTracked(node); - } else if ( - this.externalSourceName === 'arkui.component.common' && - arkts.isTSInterfaceDeclaration(node) && - !!node.id && - node.id.name === 'UICommonMethod' - ) { - return structFactory.modifyExternalComponentCommon(node); + } else if (this.externalSourceName) { + return structFactory.transformExternalSource(this.externalSourceName, node); } return node; } diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index ac0144dcc..918d2ebac 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -333,4 +333,55 @@ export class factory { false ); } + + /* + * generate XComponent(..., packageInfo: string, ...) + */ + static modifyXcomponent(node: arkts.ScriptFunction): arkts.ScriptFunction { + const info = arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + 'packageInfo', + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('string') + ) + ) + ), + undefined + ); + return arkts.factory.updateScriptFunction( + node, + node.body, + arkts.factory.createFunctionSignature( + node.typeParams, + [...node.params.slice(0, 2), info, ...node.params.slice(2)], + node.returnTypeAnnotation, + false + ), + node.flags, + node.modifiers + ); + } + + /* + * transform ExternalSource headers + */ + static transformExternalSource(externalSourceName: string, node: arkts.AstNode): arkts.AstNode { + if ( + externalSourceName === 'arkui.component.common' && + arkts.isTSInterfaceDeclaration(node) && + !!node.id && + node.id.name === 'UICommonMethod' + ) { + return factory.modifyExternalComponentCommon(node); + } else if ( + externalSourceName === 'arkui.component.xcomponent' && + arkts.isScriptFunction(node) && + !!node.id && + node.id.name === 'XComponent' + ) { + return factory.modifyXcomponent(node); + } + return node; + } } -- Gitee From 02f8f83eeb94ccc7fdd97e81beb10db2e7ebfd04 Mon Sep 17 00:00:00 2001 From: Cuecuexiaoyu Date: Wed, 21 May 2025 16:56:30 +0800 Subject: [PATCH 095/123] add function with receiver capability memo transformation Signed-off-by: Cuecuexiaoyu Change-Id: If3952b9b76ab436e3455c775f0d2ddb178e6a208 --- arkui-plugins/common/arkts-utils.ts | 7 ++ .../memo-plugins/function-transformer.ts | 9 ++ arkui-plugins/memo-plugins/memo-factory.ts | 24 ++++- .../memo-plugins/signature-transformer.ts | 6 +- arkui-plugins/memo-plugins/utils.ts | 19 ++++ .../builder-lambda/style-with-receiver.ets | 47 ++++++++ .../memo/lambdas/function-with-receiver.ets | 32 ++++++ .../function-with-receiver.test.ts | 97 +++++++++++++++++ .../style-with-receiver.test.ts | 102 ++++++++++++++++++ .../builder-lambda-translators/factory.ts | 101 ++++++++++------- .../builder-lambda-translators/utils.ts | 67 ++++++++++++ .../ui-plugins/checked-transformer.ts | 7 +- 12 files changed, 469 insertions(+), 49 deletions(-) create mode 100644 arkui-plugins/test/demo/mock/builder-lambda/style-with-receiver.ets create mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets create mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts create mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index 771442543..4e797d755 100644 --- a/arkui-plugins/common/arkts-utils.ts +++ b/arkui-plugins/common/arkts-utils.ts @@ -97,3 +97,10 @@ export function updateStructMetadata( structInfo.metadata = metadata; return structInfo; } + +export function moveToFront(arr: T[], idx: number): T[] { + if (idx >= arr.length) { + throw new Error(`Invalid argument, size of array: ${arr.length}, index: ${idx}`); + } + return [arr[idx], ...arr.slice(0, idx), ...arr.slice(idx + 1)]; +} \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index fa4a06bc4..6259f6b27 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -48,10 +48,12 @@ import { isStandaloneArrowFunction, isThisAttributeAssignment, removeMemoAnnotation, + parametrizedNodeHasReceiver } from './utils'; import { ParameterTransformer } from './parameter-transformer'; import { ReturnTransformer } from './return-transformer'; import { SignatureTransformer } from './signature-transformer'; +import { moveToFront } from '../common/arkts-utils'; interface ScopeInfo extends MemoInfo { regardAsSameScope?: boolean; @@ -318,6 +320,13 @@ export class FunctionTransformer extends AbstractVisitor { ...updatedArguments, ]; } + const isMemo = + hasMemoAnnotation(decl.scriptFunction) || + hasMemoIntrinsicAnnotation(decl.scriptFunction) || + hasMemoEntryAnnotation(decl.scriptFunction); + if (parametrizedNodeHasReceiver(decl.scriptFunction) && isMemo) { + updatedArguments = moveToFront(updatedArguments, 2); + } return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, updatedArguments); } diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index c1288e7eb..3104fe592 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -22,7 +22,9 @@ import { ParamInfo, ReturnTypeInfo, RuntimeNames, + parametrizedNodeHasReceiver } from './utils'; +import { moveToFront } from '../common/arkts-utils'; export class factory { // Importing @@ -82,12 +84,19 @@ export class factory { static createHiddenParameters(): arkts.ETSParameterExpression[] { return [factory.createContextParameter(), factory.createIdParameter()]; } - static createHiddenParameterIfNotAdded(params?: readonly arkts.Expression[]): readonly arkts.Expression[] { + static createHiddenParameterIfNotAdded( + params: readonly arkts.Expression[], + hasReceiver: boolean = false + ): readonly arkts.Expression[] { const _params = params ?? []; if (isUnmemoizedInFunction(_params)) { return _params; } - return [...factory.createHiddenParameters(), ..._params]; + let newParams: arkts.Expression[] = [...factory.createHiddenParameters(), ..._params]; + if (hasReceiver) { + newParams = moveToFront(newParams, 2); + } + return newParams; } static updateFunctionTypeWithMemoParameters(type: arkts.ETSFunctionType): arkts.ETSFunctionType { return arkts.factory.updateFunctionType( @@ -111,7 +120,7 @@ export class factory { newBody ?? func.body, arkts.factory.createFunctionSignature( func.typeParams, - factory.createHiddenParameterIfNotAdded(func.params), + factory.createHiddenParameterIfNotAdded(func.params, parametrizedNodeHasReceiver(func)), returnType ?? func.returnTypeAnnotation, func.hasReceiver ), @@ -137,9 +146,16 @@ export class factory { // Memo parameters static createMemoParameterIdentifier(name: string): arkts.Identifier { + if (name === RuntimeNames.EQUAL_T) { + return arkts.factory.createIdentifier(`${RuntimeNames.PARAMETER}_${RuntimeNames.THIS}`, undefined); + } return arkts.factory.createIdentifier(`${RuntimeNames.PARAMETER}_${name}`); } static createMemoParameterDeclarator(id: number, name: string): arkts.VariableDeclarator { + const originalIdent = + name === RuntimeNames.THIS || name === RuntimeNames.EQUAL_T + ? arkts.factory.createThisExpression() + : arkts.factory.createIdentifier(name, undefined); return arkts.factory.createVariableDeclarator( arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_CONST, factory.createMemoParameterIdentifier(name), @@ -152,7 +168,7 @@ export class factory { false ), undefined, - [arkts.factory.createNumericLiteral(id), arkts.factory.createIdentifier(name)] + [arkts.factory.createNumericLiteral(id), originalIdent] ) ); } diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index 610114613..801d41fcc 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -15,7 +15,7 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; -import { hasMemoAnnotation, hasMemoIntrinsicAnnotation } from './utils'; +import { hasMemoAnnotation, hasMemoIntrinsicAnnotation, parametrizedNodeHasReceiver } from './utils'; import { AbstractVisitor } from '../common/abstract-visitor'; function isScriptFunctionFromGetter(node: arkts.ScriptFunction): boolean { @@ -59,7 +59,9 @@ export class SignatureTransformer extends AbstractVisitor { node.body, arkts.factory.createFunctionSignature( node.typeParams, - shouldAddMemoParam ? factory.createHiddenParameterIfNotAdded(newParams) : newParams, + shouldAddMemoParam + ? factory.createHiddenParameterIfNotAdded(newParams, parametrizedNodeHasReceiver(node)) + : newParams, node.returnTypeAnnotation ? this.visitor(node.returnTypeAnnotation, shouldApplyMemoToReturnType) : memo diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index e013100ac..3e90dcfa8 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -40,6 +40,7 @@ export enum RuntimeNames { SCOPE = '__memo_scope', THIS = 'this', VALUE = 'value', + EQUAL_T = '=t' } export interface ReturnTypeInfo { @@ -557,3 +558,21 @@ export function buildeParamInfos(parameters: readonly arkts.ETSParameterExpressi }), ]; } + +export function parametersBlockHasReceiver(params: readonly arkts.Expression[]): boolean { + return params.length > 0 && arkts.isEtsParameterExpression(params[0]) && isThisParam(params[0]); +} + +export function parametrizedNodeHasReceiver(node: arkts.ScriptFunction | arkts.ETSFunctionType | undefined): boolean { + if (node === undefined) { + return false; + } + return parametersBlockHasReceiver(node.params); +} + +function isThisParam(node: arkts.Expression | undefined): boolean { + if (node === undefined || !arkts.isEtsParameterExpression(node)) { + return false; + } + return node.identifier?.isReceiver ?? false; +} diff --git a/arkui-plugins/test/demo/mock/builder-lambda/style-with-receiver.ets b/arkui-plugins/test/demo/mock/builder-lambda/style-with-receiver.ets new file mode 100644 index 000000000..92d842ff5 --- /dev/null +++ b/arkui-plugins/test/demo/mock/builder-lambda/style-with-receiver.ets @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { Text, UITextAttribute, Column, Component} from "@ohos.arkui.component" +import hilog from '@ohos.hilog' + +@memo function cardStyle(this: UITextAttribute, num: number, str: string): this { + this.fontSize(num); + this.backgroundColor(num); + return this; +} + +@memo function style22(this: UITextAttribute): this { + this.fontWeight(700); + return this; +} + +@Component +struct MM { + build() { + Column() { + Text('hello world') + .height(200) + .fontColor('#000000') + .cardStyle(600, '#eeeeee') + .fontSize(60) + .fontWeight(400) + .style22() + .width(900) + Text('hello world') + .cardStyle(600, '#eeeeee') + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets b/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets new file mode 100644 index 000000000..36bc7d82f --- /dev/null +++ b/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { memo } from "@ohos.arkui.stateManagement" + +class B { + @memo internal_call(): B { + this.foo1('morning'); + return this.foo2('afternoon') + } +} + +@memo function foo1(this: B, str: string): void { + console.log('Good', str); +} + +@memo function foo2(this: B, str: string): this { + console.log('Good', str); + return this; +} diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts new file mode 100644 index 000000000..8cfc8fc1d --- /dev/null +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { memoNoRecheck } from '../../../utils/plugins'; +import { Plugins } from '../../../../common/plugin-context'; +import { uiTransform } from '../../../../ui-plugins'; + +const LAMBDA_DIR_PATH: string = 'memo/lambdas'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'function-with-receiver.ets'), +]; + +const parsedTransform: Plugins = { + name: 'state-complex-type', + parsed: uiTransform().parsed +}; + +const pluginTester = new PluginTester('test memo lambda', buildConfig); + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "@ohos.arkui.stateManagement"; + +function main() {} + +function foo1(this: B, __memo_context: __memo_context_type, __memo_id: __memo_id_type, str: string): void { + const __memo_scope = __memo_context.scope(((__memo_id) + (38567515)), 2); + const __memo_parameter_this = __memo_scope.param(0, (this)), __memo_parameter_str = __memo_scope.param(1, str); + if (__memo_scope.unchanged) { + __memo_scope.cached; + return; + } + console.log("Good", __memo_parameter_str.value); + { + __memo_scope.recache(); + return; + } +} + +function foo2(this: B, __memo_context: __memo_context_type, __memo_id: __memo_id_type, str: string): B { + const __memo_scope = __memo_context.scope(((__memo_id) + (167482260)), 2); + const __memo_parameter_this = __memo_scope.param(0, (this)), __memo_parameter_str = __memo_scope.param(1, str); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + console.log("Good", __memo_parameter_str.value); + return __memo_scope.recache(this); +} + +class B { + public internal_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type): B { + const __memo_scope = __memo_context.scope(((__memo_id) + (146437675)), 0); + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + foo1((this), __memo_context, ((__memo_id) + (119664703)), "morning"); + return __memo_scope.recache(foo2((this), __memo_context, ((__memo_id) + (181969214)), "afternoon")); + } + + public constructor() {} +} +`; + +function testMemoTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'transform lambdas about function with receiver feature', + [parsedTransform, memoNoRecheck], + { + 'checked:memo-no-recheck': [testMemoTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts new file mode 100644 index 000000000..d84397d42 --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; +import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { builderLambdaNoRecheck, structNoRecheck, uiNoRecheck } from '../../../utils/plugins'; +import { uiTransform } from '../../../../ui-plugins'; +import { Plugins } from '../../../../common/plugin-context'; + +const BUILDER_LAMBDA_DIR_PATH: string = 'builder-lambda'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'style-with-receiver.ets'), +]; + +const pluginTester = new PluginTester('test function with receiver style transformstion', buildConfig); + +const parsedTransform: Plugins = { + name: 'style-with-receiver', + parsed: uiTransform().parsed +}; + +const expectedScript: string = ` +import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { memo as memo } from "@ohos.arkui.stateManagement"; +import { Text as Text, UITextAttribute as UITextAttribute, Column as Column, Component as Component } from "@ohos.arkui.component"; +import hilog from "@ohos.hilog"; + +function main() {} + +@memo() function cardStyle(this: UITextAttribute, num: number, str: string): UITextAttribute { + this.fontSize(num); + this.backgroundColor(num); + return this; +} + +@memo() function style22(this: UITextAttribute): UITextAttribute { + this.fontWeight(700); + return this; +} + +@Component({freezeWhenInactive:false}) final class MM extends CustomComponent { + public __initializeStruct(initializers: __Options_MM | undefined, @memo() content: (()=> void) | undefined): void {} + + public __updateStruct(initializers: __Options_MM | undefined): void {} + + @memo() public _build(@memo() style: ((instance: MM)=> MM) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MM | undefined): void { + Column(undefined, undefined, (() => { + Text(@memo() ((instance: UITextAttribute): void => { + style22(cardStyle(instance.height(200).fontColor("#000000"), 600, "#eeeeee").fontSize(60).fontWeight(400)).width(900); + return; + }), "hello world", undefined, undefined); + Text(@memo() ((instance: UITextAttribute): void => { + cardStyle(instance, 600, "#eeeeee"); + return; + }), "hello world", undefined, undefined); + })); + } + + public constructor() {} + +} + +interface __Options_MM { + +} +`; + +function testParsedAndCheckedTransformer(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); +} + +pluginTester.run( + 'test function with receiver style transformstion', + [parsedTransform, uiNoRecheck], + { + checked: [testParsedAndCheckedTransformer], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index e4572d2f4..245659d46 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -31,7 +31,10 @@ import { BindableDecl, getDecalTypeFromValue, hasBindableProperty, - isDoubleDollarCall + isDoubleDollarCall, + InstanceCallInfo, + isStyleChainedCall, + isStyleWithReceiverCall, } from './utils'; import { DecoratorNames } from '../property-translators/utils'; import { factory as PropertyFactory } from '../property-translators/factory'; @@ -106,34 +109,37 @@ export class factory { [factory.generateValueProperty(bindableArg), factory.generateOnChangeArrowFunc(bindableArg, valueType)], false ); - return arkts.factory.createTSAsExpression( - objExp, - factory.createBindableType(valueType), - false - ); + return arkts.factory.createTSAsExpression(objExp, factory.createBindableType(valueType), false); } /* * create style instance call, e.g. `instance.margin(10)`. */ - static createStyleLambdaBody(lambdaBody: arkts.AstNode, call: arkts.CallExpression, projectConfig: ProjectConfig | undefined): arkts.CallExpression { - const newArgs: arkts.Expression[] = factory.getTransformedStyle(call); - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( + static createStyleLambdaBody(lambdaBody: arkts.AstNode, callInfo: InstanceCallInfo, projectConfig: ProjectConfig | undefined): arkts.CallExpression { + if (!callInfo.isReceiver) { + const newArgs: arkts.Expression[] = factory.getTransformedStyle(callInfo.call); + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + lambdaBody, + callInfo.call.expression, + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + newArgs.map((arg) => { + if (arkts.isArrowFunctionExpression(arg)) { + return this.processArgArrowFunction(arg, projectConfig); + } + return arg; + }) + ); + } else { + return arkts.factory.createCallExpression(callInfo.call.expression, callInfo.call.typeArguments, [ lambdaBody, - call.expression, - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - newArgs.map((arg) => { - if (arkts.isArrowFunctionExpression(arg)) { - return this.processArgArrowFunction(arg, projectConfig); - } - return arg; - }) - ); + ...callInfo.call.arguments.slice(1), + ]); + } } /* @@ -474,25 +480,29 @@ export class factory { /** * transform `.animation(...)` to `.animationStart(...) and .animationStop(...)` */ - static updateAnimation(instanceCalls: arkts.CallExpression[]): void { + static updateAnimation(instanceCalls: InstanceCallInfo[]): void { let lastAniIdx = 0; let curIdx = 0; while (curIdx < instanceCalls.length) { - const property: arkts.Identifier = instanceCalls[curIdx].expression as arkts.Identifier; + if (instanceCalls[curIdx].isReceiver) { + curIdx++; + continue; + } + const property: arkts.Identifier = instanceCalls[curIdx].call.expression as arkts.Identifier; if (property.name === BuilderLambdaNames.ANIMATION_NAME) { const aniStart: arkts.CallExpression = arkts.factory.createCallExpression( arkts.factory.createIdentifier(BuilderLambdaNames.ANIMATION_START), undefined, - instanceCalls[curIdx].arguments + instanceCalls[curIdx].call.arguments ); const aniStop: arkts.CallExpression = arkts.factory.createCallExpression( arkts.factory.createIdentifier(BuilderLambdaNames.ANIMATION_STOP), undefined, - instanceCalls[curIdx].arguments.map((arg)=>arg.clone()) + instanceCalls[curIdx].call.arguments.map((arg) => arg.clone()) ); - instanceCalls.splice(lastAniIdx, 0, aniStart); - instanceCalls[curIdx + 1] = aniStop; + instanceCalls.splice(lastAniIdx, 0, { isReceiver: false, call: aniStart }); + instanceCalls[curIdx + 1] = { isReceiver: false, call: aniStop }; curIdx += 2; lastAniIdx = curIdx; } else { @@ -505,16 +515,29 @@ export class factory { * transform `@ComponentBuilder` in non-declared calls. */ static transformBuilderLambda(node: arkts.CallExpression, projectConfig: ProjectConfig | undefined): arkts.AstNode { - let instanceCalls: arkts.CallExpression[] = []; + let instanceCalls: InstanceCallInfo[] = []; let leaf: arkts.CallExpression = node; - while ( - arkts.isMemberExpression(leaf.expression) && - arkts.isIdentifier(leaf.expression.property) && - arkts.isCallExpression(leaf.expression.object) - ) { - instanceCalls.push(arkts.factory.createCallExpression(leaf.expression.property, undefined, leaf.arguments)); - leaf = leaf.expression.object; + while (isStyleChainedCall(leaf) || isStyleWithReceiverCall(leaf)) { + if (isStyleChainedCall(leaf)) { + instanceCalls.push({ + isReceiver: false, + call: arkts.factory.createCallExpression( + (leaf.expression as arkts.MemberExpression).property, + leaf.typeArguments, + leaf.arguments + ), + }); + leaf = (leaf.expression as arkts.MemberExpression).object as arkts.CallExpression; + } + + if (isStyleWithReceiverCall(leaf)) { + instanceCalls.push({ + isReceiver: true, + call: arkts.factory.createCallExpression(leaf.expression, leaf.typeArguments, leaf.arguments), + }); + leaf = leaf.arguments[0] as arkts.CallExpression; + } } const decl: arkts.AstNode | undefined = findBuilderLambdaDecl(leaf); @@ -533,8 +556,8 @@ export class factory { instanceCalls = instanceCalls.reverse(); this.updateAnimation(instanceCalls); lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); - instanceCalls.forEach((call) => { - lambdaBody = this.createStyleLambdaBody(lambdaBody!, call, projectConfig); + instanceCalls.forEach((callInfo) => { + lambdaBody = this.createStyleLambdaBody(lambdaBody!, callInfo, projectConfig); }); } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index c220640f5..f7cd7c6de 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -29,6 +29,11 @@ export enum BindableDecl { export type BuilderLambdaAstNode = arkts.ScriptFunction | arkts.ETSParameterExpression | arkts.FunctionDeclaration; +export type InstanceCallInfo = { + isReceiver: boolean; + call: arkts.CallExpression; +}; + /** * Used in finding "XXX" in BuilderLambda("XXX") * @deprecated @@ -56,9 +61,64 @@ export function builderLambdaArgumentName(annotation: arkts.AnnotationUsage): st */ export function isBuilderLambda(node: arkts.AstNode, isExternal?: boolean): boolean { const builderLambdaCall: arkts.AstNode | undefined = getDeclForBuilderLambda(node); + if (!builderLambdaCall) { + return arkts.isCallExpression(node) && node.arguments.length > 0 && isBuilderLambda(node.arguments[0]); + } return !!builderLambdaCall; } +/** + * Determine whether it is a function with receiver method definition. + * + * @param node method definition node + */ +export function isFunctionWithReceiver(node: arkts.MethodDefinition): boolean { + if (node.scriptFunction && arkts.isScriptFunction(node.scriptFunction)) { + return node.scriptFunction.hasReceiver; + } + return false; +} + +/** + * Determine whether it is a function with receiver call. + * + * @param node identifier node + */ +export function isFunctionWithReceiverCall(node: arkts.Identifier): boolean { + const decl: arkts.AstNode | undefined = arkts.getDecl(node); + if (decl && arkts.isMethodDefinition(decl)) { + return isFunctionWithReceiver(decl); + } + return false; +} + +/** + * Determine whether it is a style chained call. + * + * @param node call expression node + */ +export function isStyleChainedCall(node: arkts.CallExpression): boolean { + return ( + arkts.isMemberExpression(node.expression) && + arkts.isIdentifier(node.expression.property) && + arkts.isCallExpression(node.expression.object) + ); +} + +/** + * Determine whether it is a style function with receiver call. + * + * @param node call expression node + */ +export function isStyleWithReceiverCall(node: arkts.CallExpression): boolean { + return ( + arkts.isIdentifier(node.expression) && + isFunctionWithReceiverCall(node.expression) && + !!node.arguments.length && + arkts.isCallExpression(node.arguments[0]) + ); +} + /** * replace $_instantiate with _instantiateImpl. * @@ -134,6 +194,13 @@ export function isBuilderLambdaCall(node: arkts.CallExpression | arkts.Identifie } if (arkts.isMethodDefinition(decl)) { + if (isFunctionWithReceiver(decl)) { + return ( + arkts.isCallExpression(node) && + node.arguments.length > 0 && + !!getDeclForBuilderLambda(node.arguments[0]) + ); + } return isBuilderLambdaMethod(decl); } if (arkts.isFunctionExpression(decl)) { diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 9ab64ff2b..4d665193e 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -125,7 +125,7 @@ export class CheckedTransformer extends AbstractVisitor { export type ClassScopeInfo = { isObserved: boolean; classHasTrack: boolean; - getters: arkts.MethodDefinition[] + getters: arkts.MethodDefinition[]; }; function transformObservedTracked(node: arkts.ClassDeclaration): arkts.ClassDeclaration { @@ -139,7 +139,7 @@ function transformObservedTracked(node: arkts.ClassDeclaration): arkts.ClassDecl if (!isObserved && !classHasTrack) { return node; } - + const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( node.definition, node.definition.ident, @@ -160,7 +160,7 @@ function transformObservedTracked(node: arkts.ClassDeclaration): arkts.ClassDecl arkts.classDefinitionFlags(node.definition) ); return arkts.factory.updateClassDeclaration(node, updateClassDef); -} +} function observedTrackPropertyMembers( classHasTrack: boolean, @@ -469,4 +469,3 @@ function transformResource( ]; return structFactory.generateTransformedResource(resourceNode, newArgs); } - -- Gitee From e6971103d3097afce06f56acef6a3463bed508f4 Mon Sep 17 00:00:00 2001 From: Yuxin Feng Date: Mon, 26 May 2025 21:28:24 +0800 Subject: [PATCH 096/123] fix @Observed transform Signed-off-by: Yuxin Feng Change-Id: I1a3fba93d831d3026bdb2a81741bb62177c6e663 --- .../observed-track/observed-only.test.ts | 4 +- .../observed-track-class-property.test.ts | 6 +- .../observed-track-complex-type.test.ts | 66 +++++++++---------- .../observed-track-extends.test.ts | 6 +- .../observed-track-implements.test.ts | 20 +----- .../observed-track/observed-track.test.ts | 2 +- .../observed-track/track-only.test.ts | 2 +- .../decorators/watch/watch-basic.test.ts | 2 +- .../property-translators/observedTrack.ts | 22 ++++--- 9 files changed, 58 insertions(+), 72 deletions(-) diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts index 55af0dd86..2c8cc5c75 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts @@ -96,7 +96,7 @@ function main() {} if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_propA!; + return (this).__backing_propA; } public set propA(newValue: number) { @@ -111,7 +111,7 @@ function main() {} if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_trackA!; + return (this).__backing_trackA; } public set trackA(newValue: number) { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts index becd4ced5..116fc4442 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts @@ -102,7 +102,7 @@ class E implements IObservedObject { (this).__meta_trackE.addRef(); } setObservationDepth((this).__backing_trackE.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_trackE.value!; + return (this).__backing_trackE.value; } public set trackE(newValue: Info) { @@ -145,7 +145,7 @@ class E implements IObservedObject { (this).__meta.addRef(); } setObservationDepth((this).__backing_propE1.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_propE1.value!; + return (this).__backing_propE1.value; } public set propE1(newValue: Info) { @@ -161,7 +161,7 @@ class E implements IObservedObject { (this).__meta.addRef(); } setObservationDepth((this).__backing_trackE1.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_trackE1.value!; + return (this).__backing_trackE1.value; } public set trackE1(newValue: Info) { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts index b0635b8a9..cca4ab40b 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts @@ -231,7 +231,7 @@ final class Status extends BaseEnum { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_numA.addRef(); } - return (this).__backing_numA!; + return (this).__backing_numA; } public set numA(newValue: number) { @@ -246,7 +246,7 @@ final class Status extends BaseEnum { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_stringA.addRef(); } - return (this).__backing_stringA!; + return (this).__backing_stringA; } public set stringA(newValue: string) { @@ -261,7 +261,7 @@ final class Status extends BaseEnum { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_booleanA.addRef(); } - return (this).__backing_booleanA!; + return (this).__backing_booleanA; } public set booleanA(newValue: boolean) { @@ -277,7 +277,7 @@ final class Status extends BaseEnum { (this).__meta_arrayA.addRef(); } setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_arrayA.value!; + return (this).__backing_arrayA.value; } public set arrayA(newValue: Array) { @@ -293,7 +293,7 @@ final class Status extends BaseEnum { (this).__meta_objectA.addRef(); } setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_objectA.value!; + return (this).__backing_objectA.value; } public set objectA(newValue: Object) { @@ -309,7 +309,7 @@ final class Status extends BaseEnum { (this).__meta_dateA.addRef(); } setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_dateA.value!; + return (this).__backing_dateA.value; } public set dateA(newValue: Date) { @@ -325,7 +325,7 @@ final class Status extends BaseEnum { (this).__meta_setA.addRef(); } setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_setA.value!; + return (this).__backing_setA.value; } public set setA(newValue: Set) { @@ -341,7 +341,7 @@ final class Status extends BaseEnum { (this).__meta_mapA.addRef(); } setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_mapA.value!; + return (this).__backing_mapA.value; } public set mapA(newValue: Map) { @@ -356,7 +356,7 @@ final class Status extends BaseEnum { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_unionA.addRef(); } - return (this).__backing_unionA!; + return (this).__backing_unionA; } public set unionA(newValue: string | undefined) { @@ -372,7 +372,7 @@ final class Status extends BaseEnum { (this).__meta_classA.addRef(); } setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_classA.value!; + return (this).__backing_classA.value; } public set classA(newValue: Person) { @@ -388,7 +388,7 @@ final class Status extends BaseEnum { (this).__meta_enumA.addRef(); } setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_enumA.value!; + return (this).__backing_enumA.value; } public set enumA(newValue: Status) { @@ -448,7 +448,7 @@ final class Status extends BaseEnum { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_numA!; + return (this).__backing_numA; } public set numA(newValue: number) { @@ -463,7 +463,7 @@ final class Status extends BaseEnum { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_stringA!; + return (this).__backing_stringA; } public set stringA(newValue: string) { @@ -478,7 +478,7 @@ final class Status extends BaseEnum { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_booleanA!; + return (this).__backing_booleanA; } public set booleanA(newValue: boolean) { @@ -494,7 +494,7 @@ final class Status extends BaseEnum { (this).__meta.addRef(); } setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_arrayA.value!; + return (this).__backing_arrayA.value; } public set arrayA(newValue: Array) { @@ -510,7 +510,7 @@ final class Status extends BaseEnum { (this).__meta.addRef(); } setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_objectA.value!; + return (this).__backing_objectA.value; } public set objectA(newValue: Object) { @@ -526,7 +526,7 @@ final class Status extends BaseEnum { (this).__meta.addRef(); } setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_dateA.value!; + return (this).__backing_dateA.value; } public set dateA(newValue: Date) { @@ -542,7 +542,7 @@ final class Status extends BaseEnum { (this).__meta.addRef(); } setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_setA.value!; + return (this).__backing_setA.value; } public set setA(newValue: Set) { @@ -558,7 +558,7 @@ final class Status extends BaseEnum { (this).__meta.addRef(); } setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_mapA.value!; + return (this).__backing_mapA.value; } public set mapA(newValue: Map) { @@ -573,7 +573,7 @@ final class Status extends BaseEnum { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_unionA!; + return (this).__backing_unionA; } public set unionA(newValue: string | undefined) { @@ -589,7 +589,7 @@ final class Status extends BaseEnum { (this).__meta.addRef(); } setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_classA.value!; + return (this).__backing_classA.value; } public set classA(newValue: Person) { @@ -605,7 +605,7 @@ final class Status extends BaseEnum { (this).__meta.addRef(); } setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_enumA.value!; + return (this).__backing_enumA.value; } public set enumA(newValue: Status) { @@ -685,7 +685,7 @@ class mixed3 implements IObservedObject { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_numA.addRef(); } - return (this).__backing_numA!; + return (this).__backing_numA; } public set numA(newValue: number) { @@ -700,7 +700,7 @@ class mixed3 implements IObservedObject { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_stringA.addRef(); } - return (this).__backing_stringA!; + return (this).__backing_stringA; } public set stringA(newValue: string) { @@ -715,7 +715,7 @@ class mixed3 implements IObservedObject { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_booleanA.addRef(); } - return (this).__backing_booleanA!; + return (this).__backing_booleanA; } public set booleanA(newValue: boolean) { @@ -731,7 +731,7 @@ class mixed3 implements IObservedObject { (this).__meta_arrayA.addRef(); } setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_arrayA.value!; + return (this).__backing_arrayA.value; } public set arrayA(newValue: Array) { @@ -747,7 +747,7 @@ class mixed3 implements IObservedObject { (this).__meta_objectA.addRef(); } setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_objectA.value!; + return (this).__backing_objectA.value; } public set objectA(newValue: Object) { @@ -763,7 +763,7 @@ class mixed3 implements IObservedObject { (this).__meta_dateA.addRef(); } setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_dateA.value!; + return (this).__backing_dateA.value; } public set dateA(newValue: Date) { @@ -779,7 +779,7 @@ class mixed3 implements IObservedObject { (this).__meta_setA.addRef(); } setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_setA.value!; + return (this).__backing_setA.value; } public set setA(newValue: Set) { @@ -795,7 +795,7 @@ class mixed3 implements IObservedObject { (this).__meta_mapA.addRef(); } setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_mapA.value!; + return (this).__backing_mapA.value; } public set mapA(newValue: Map) { @@ -810,7 +810,7 @@ class mixed3 implements IObservedObject { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_unionA.addRef(); } - return (this).__backing_unionA!; + return (this).__backing_unionA; } public set unionA(newValue: string | undefined) { @@ -826,7 +826,7 @@ class mixed3 implements IObservedObject { (this).__meta_classA.addRef(); } setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_classA.value!; + return (this).__backing_classA.value; } public set classA(newValue: Person) { @@ -842,7 +842,7 @@ class mixed3 implements IObservedObject { (this).__meta_enumA.addRef(); } setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_enumA.value!; + return (this).__backing_enumA.value; } public set enumA(newValue: Status) { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts index 47237cf0c..3d9274904 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts @@ -96,7 +96,7 @@ function main() {} if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_propA!; + return (this).__backing_propA; } public set propA(newValue: number) { @@ -111,7 +111,7 @@ function main() {} if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_trackA!; + return (this).__backing_trackA; } public set trackA(newValue: number) { @@ -158,7 +158,7 @@ class G extends A { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_propG.addRef(); } - return (this).__backing_propG!; + return (this).__backing_propG; } public set propG(newValue: number) { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts index c4239714b..e7562feef 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts @@ -118,7 +118,7 @@ interface trackInterface { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_propF!; + return (this).__backing_propF; } public set trackF(newValue: number) { @@ -133,23 +133,7 @@ interface trackInterface { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta.addRef(); } - return (this).__backing_trackF!; - } - - public set propF(newValue: number) { - if ((((this).__backing_propF) !== (newValue))) { - (this).__backing_propF = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("propF"); - } - } - - public set trackF(newValue: number) { - if ((((this).__backing_trackF) !== (newValue))) { - (this).__backing_trackF = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("trackF"); - } + return (this).__backing_trackF; } } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts index 95a77ed88..11b85da04 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts @@ -96,7 +96,7 @@ function main() {} if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_trackB.addRef(); } - return (this).__backing_trackB!; + return (this).__backing_trackB; } public set trackB(newValue: number) { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts index c21fe95f3..17a8f9572 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts @@ -96,7 +96,7 @@ class C implements IObservedObject { if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_trackC.addRef(); } - return (this).__backing_trackC!; + return (this).__backing_trackC; } public set trackC(newValue: number) { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts index 692bf1f24..ef7678fad 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts @@ -116,7 +116,7 @@ function main() {} if ((((this)._permissibleAddRefDepth) > (0))) { (this).__meta_trackA.addRef(); } - return (this).__backing_trackA!; + return (this).__backing_trackA; } public set trackA(newValue: string) { diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts index 62bcad2d6..c83004733 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -158,23 +158,27 @@ export class ObservedTrackTranslator { const originSetter: arkts.MethodDefinition = originGetter.overloads[0]; const updateGetter: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( originGetter, - newGetter.kind, + originGetter.kind, newGetter.name, - arkts.factory.createFunctionExpression(newGetter.scriptFunction), + arkts.factory.createFunctionExpression( + newGetter.scriptFunction.addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) + ), originGetter.modifiers, false ); - const updateSetter: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( + arkts.factory.updateMethodDefinition( originSetter, - newSetter.kind, + originSetter.kind, newSetter.name, - arkts.factory.createFunctionExpression(newSetter.scriptFunction), + arkts.factory.createFunctionExpression( + newSetter.scriptFunction + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_OVERLOAD) + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) + ), originSetter.modifiers, false ); - // updateGetter.setOverloads([updateSetter]) this.classScopeInfo.getters[idx] = updateGetter; - this.classScopeInfo.getters.push(updateSetter); } } else { this.classScopeInfo.getters.push(...[newGetter, newSetter]); @@ -287,9 +291,7 @@ export class ObservedTrackTranslator { getterReturnMember(properyIsClass: boolean, newName: string): arkts.ReturnStatement { return arkts.factory.createReturnStatement( - arkts.factory.createTSNonNullExpression( - properyIsClass ? this.genThisBackingValue(newName) : this.genThisBacking(newName) - ) + properyIsClass ? this.genThisBackingValue(newName) : this.genThisBacking(newName) ); } -- Gitee From 240882a5c382b7485c4dd14066f180516eebaae8 Mon Sep 17 00:00:00 2001 From: wuhailong Date: Tue, 20 May 2025 09:46:27 +0800 Subject: [PATCH 097/123] Add interop Transform in mixed compilation Issue: #ICAOTO Signed-off-by: wuhailong Change-Id: I98657ddb8f552a7dc3896db13441d8a7e9f901f6 --- .../src/fast_build/ark_compiler/error_code.ts | 3 + .../ark_compiler/module/module_mode.ts | 3 + .../ets_ui/rollup-plugin-ets-typescript.ts | 16 +- compiler/src/process_arkts_evolution.ts | 414 ++++++++++- .../common/process_arkts_evolution.test.ts | 702 +++++++++++++++++- 5 files changed, 1134 insertions(+), 4 deletions(-) diff --git a/compiler/src/fast_build/ark_compiler/error_code.ts b/compiler/src/fast_build/ark_compiler/error_code.ts index b74ab275e..80352dbed 100644 --- a/compiler/src/fast_build/ark_compiler/error_code.ts +++ b/compiler/src/fast_build/ark_compiler/error_code.ts @@ -58,6 +58,9 @@ export enum ErrorCode { ETS2BUNDLE_EXTERNAL_ES2ABC_EXECUTION_FAILED = '10311009', ETS2BUNDLE_EXTERNAL_LAZY_IMPORT_RE_EXPORT_ERROR = '10311010', ETS2BUNDLE_EXTERNAL_DUPLICATE_FILE_NAMES_ERROR = '10311011', + // INTEROPTRANSFORMER ERROR CODE + ETS2BUNDLE_EXTERNAL_CLASS_HAS_NO_CONSTRUCTOR_WITHOUT_ARGS = '10311012', + ETS2BUNDLE_EXTERNAL_UNION_TYPE_AMBIGUITY = '10311013', // CONSTANTS FOR ES2ABC ERROR CODE ES2ABC_SYNTAX_ERROR_ERROR_CODE = '10705000', diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts index 01b5c1635..e058778ec 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_mode.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -600,6 +600,9 @@ export class ModuleMode extends CommonMode { if (this.projectConfig.allowEtsAnnotations) { this.cmdArgs.push('--enable-annotations'); } + if (this.projectConfig.mixCompile) { + this.cmdArgs.push('--enable-ets-implements'); + } } addCacheFileArgs() { diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts index e1c3280f9..16c5d5531 100644 --- a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts @@ -109,6 +109,10 @@ import { MemoryDefine } from '../meomry_monitor/memory_define'; import { ModuleSourceFile } from '../ark_compiler/module/module_source_file'; import { ARKUI_SUBSYSTEM_CODE } from '../../../lib/hvigor_error_code/hvigor_error_info'; import { ProjectCollections } from 'arkguard'; +import { + interopTransformLog, + interopTransform +} from '../../process_arkts_evolution'; const filter: any = createFilter(/(? = new Map(); @@ -70,6 +84,14 @@ export let arkTSEvolutionModuleMap: Map = new Map( export let arkTSHybridModuleMap: Map = new Map(); +let arkTSEvoFileOHMUrlMap: Map = new Map(); + +let globalDeclarations: Map = new Map(); + +let declaredClassVars: Set = new Set(); + +let fullNameToTmpVar: Map = new Map(); + export function addDeclFilesConfig(filePath: string, projectConfig: Object, logger: Object, pkgPath: string, pkgName: string): void { const { projectFilePath, pkgInfo } = getPkgInfo(filePath, projectConfig, logger, pkgPath, pkgName); @@ -157,6 +179,11 @@ export function cleanUpProcessArkTSEvolutionObj(): void { arkTSEvolutionModuleMap = new Map(); arkTSHybridModuleMap = new Map(); pkgDeclFilesConfig = {}; + arkTSEvoFileOHMUrlMap = new Map(); + interopTransformLog.cleanUp(); + globalDeclarations = new Map(); + declaredClassVars = new Set(); + fullNameToTmpVar = new Map(); } export async function writeBridgeCodeFileSyncByNode(node: ts.SourceFile, moduleId: string): Promise { @@ -185,3 +212,386 @@ function getDeclgenV2OutPath(pkgName: string): string { return ''; } +export function interopTransform(program: ts.Program, id: string, mixCompile: boolean): ts.TransformerFactory { + if (!mixCompile || /\.ts$/.test(id)) { + return () => sourceFile => sourceFile; + } + // For specific scenarios, please refer to the test file process_arkts_evolution.test.ts + const typeChecker: ts.TypeChecker = program.getTypeChecker(); + return (context: ts.TransformationContext): ts.Transformer => { + const scopeUsedNames: WeakMap> = new WeakMap>(); + return (rootNode: ts.SourceFile) => { + interopTransformLog.sourceFile = rootNode; + const classToInterfacesMap: Map> = collectInterfacesMap(rootNode, typeChecker); + // Support for creating 1.2 type object literals in 1.1 modules + const visitor: ts.Visitor = createObjectLiteralVisitor(context, typeChecker, scopeUsedNames); + const processNode: ts.SourceFile = ts.visitEachChild(rootNode, visitor, context); + // Support 1.1 classes to implement 1.2 interfaces + const withHeritage: ts.SourceFile = classToInterfacesMap.size > 0 ? + ts.visitEachChild(processNode, transformHeritage(context, classToInterfacesMap), context) : processNode; + + const importStmts: ts.ImportDeclaration[] = withHeritage.statements.filter(stmt => ts.isImportDeclaration(stmt)); + const otherStmts: ts.Statement[] = withHeritage.statements.filter(stmt => !ts.isImportDeclaration(stmt)); + const globalStmts: ts.Statement[] = Array.from(globalDeclarations.values()); + + return ts.factory.updateSourceFile( + withHeritage, + [...importStmts, ...globalStmts, ...otherStmts], + withHeritage.isDeclarationFile, + withHeritage.referencedFiles, + withHeritage.typeReferenceDirectives, + withHeritage.hasNoDefaultLib, + withHeritage.libReferenceDirectives + ); + }; + }; +} + +function isFromArkTSEvolutionModule(node: ts.Node): boolean { + const sourceFile: ts.SourceFile = node.getSourceFile(); + const filePath: string = toUnixPath(sourceFile.fileName); + for (const arkTSEvolutionModuleInfo of arkTSEvolutionModuleMap.values()) { + const declgenV1OutPath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenV1OutPath); + if (filePath.startsWith(declgenV1OutPath + '/')) { + const relative: string = filePath.replace(declgenV1OutPath + '/', '').replace(/\.d\.ets$/, ''); + if (!arkTSEvoFileOHMUrlMap.has(filePath)) { + arkTSEvoFileOHMUrlMap.set(filePath, relative); + } + return true; + } + } + return false; +} + +function createObjectLiteralVisitor(context: ts.TransformationContext, typeChecker: ts.TypeChecker, + scopeUsedNames: WeakMap>): ts.Visitor { + return function visitor(node: ts.SourceFile): ts.SourceFile { + if (!ts.isObjectLiteralExpression(node)) { + return ts.visitEachChild(node, visitor, context); + } + + const contextualType: ts.Type | undefined = typeChecker.getContextualType(node); + if (!contextualType) { + return ts.visitEachChild(node, visitor, context); + } + const isRecordType: boolean = contextualType.aliasSymbol?.escapedName === 'Record' && + (typeof ts.isStaticRecord === 'function' && ts.isStaticRecord(contextualType)); + const finalType: ts.Type = unwrapType(node, contextualType); + const decl : ts.Declaration = (finalType.symbol?.declarations || finalType.aliasSymbol?.declarations)?.[0]; + let className: string; + if (!isRecordType) { + if (!decl || !isFromArkTSEvolutionModule(decl)) { + return ts.visitEachChild(node, visitor, context); + } + className = finalType.symbol?.name || finalType.aliasSymbol?.name; + if (!className) { + return ts.visitEachChild(node, visitor, context); + } + + if (ts.isClassDeclaration(decl) && !hasZeroArgConstructor(decl, className)) { + return ts.visitEachChild(node, visitor, context); + } + } + + const scope: ts.Node = getScope(node); + const tmpObjName: string = getUniqueName(scope, 'tmpObj', scopeUsedNames); + const fullName: string = buildFullClassName(decl, finalType, className, isRecordType); + const getCtorExpr: ts.Expression = buildGetConstructorCall(fullName, isRecordType); + let tmpClassName: string; + if (fullNameToTmpVar.has(fullName)) { + tmpClassName = fullNameToTmpVar.get(fullName)!; + } else { + tmpClassName = getUniqueName(scope, isRecordType ? 'tmpRecord' : 'tmpClass', scopeUsedNames); + fullNameToTmpVar.set(fullName, tmpClassName); + declareGlobalTemp(tmpClassName, getCtorExpr); + } + declareGlobalTemp(tmpObjName); + + const assignments: ts.Expression[] = buildPropertyAssignments(node, tmpObjName, !isRecordType); + return ts.factory.createParenthesizedExpression(ts.factory.createCommaListExpression([ + ts.factory.createAssignment(ts.factory.createIdentifier(tmpObjName), + ts.factory.createNewExpression(ts.factory.createIdentifier(tmpClassName), undefined, [])), + ...assignments, + ts.factory.createIdentifier(tmpObjName) + ])); + }; +} + +function unwrapType(node: ts.SourceFile, type: ts.Type): ts.Type { + // Unwrap parenthesized types recursively + if ((type.flags & ts.TypeFlags.Parenthesized) && 'type' in type) { + return unwrapType(node, (type as ts.ParenthesizedType).type); + } + + // If union, pick the unique viable type + if (type.isUnion()) { + const arkTSEvolutionTypes: ts.Type[] = []; + + for (const tpye of type.types) { + const symbol: ts.Symbol = tpye.aliasSymbol || tpye.getSymbol(); + const decls: ts.Declaration[] = symbol?.declarations; + if (!decls || decls.length === 0) { + continue; + } + + const isArkTSEvolution: boolean = decls.some(decl => isFromArkTSEvolutionModule(decl)); + if (isArkTSEvolution) { + arkTSEvolutionTypes.push(tpye); + } + } + if (arkTSEvolutionTypes.length === 0) { + return type; + } + if (arkTSEvolutionTypes.length !== 1 || type.types.length > 1) { + const candidates: string = arkTSEvolutionTypes.map(tpye => tpye.symbol?.name || '(anonymous)').join(', '); + const errInfo: LogData = LogDataFactory.newInstance( + ErrorCode.ETS2BUNDLE_EXTERNAL_UNION_TYPE_AMBIGUITY, + ArkTSErrorDescription, + `Ambiguous union type: multiple valid ArkTSEvolution types found: [${candidates}].`, + '', + ['Please use type assertion as to disambiguate.'] + ); + interopTransformLog.errors.push({ + type: LogType.ERROR, + message: errInfo.toString(), + pos: node.getStart() + }); + return type; + } + return unwrapType(node, arkTSEvolutionTypes[0]); + } + return type; +} + +function hasZeroArgConstructor(decl: ts.ClassDeclaration, className: string): boolean { + const ctors = decl.members.filter(member => + ts.isConstructorDeclaration(member) || ts.isConstructSignatureDeclaration(member)); + const hasZeroArgCtor: boolean = ctors.length === 0 || ctors.some(ctor => ctor.parameters.length === 0); + if (!hasZeroArgCtor) { + const errInfo: LogData = LogDataFactory.newInstance( + ErrorCode.ETS2BUNDLE_EXTERNAL_CLASS_HAS_NO_CONSTRUCTOR_WITHOUT_ARGS, + ArkTSErrorDescription, + `The class "${className}" does not has no no-argument constructor.`, + '', + [ + 'Please confirm whether there is a no-argument constructor ' + + `in the ArkTS Evolution class "${className}" type in the object literal.` + ] + ); + interopTransformLog.errors.push({ + type: LogType.ERROR, + message: errInfo.toString(), + pos: decl.name?.getStart() ?? decl.getStart() + }); + return false; + } + return hasZeroArgCtor; +} + +function buildFullClassName(decl: ts.Declaration, finalType: ts.Type, className: string, isRecordType: boolean): string { + if (isRecordType) { + return 'Lescompat/Record'; + } + const basePath: string = getArkTSEvoFileOHMUrl(finalType); + return ts.isInterfaceDeclaration(decl) ? + `L${basePath}/${className}$ObjectLiteral` : + `L${basePath}/${className}`; +} + +function buildGetConstructorCall(fullName: string, isRecord: boolean): ts.Expression { + return ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('globalThis'), 'gtest'), + isRecord ? 'etsVM.getInstance' : 'etsVM.getClass'), + undefined, + [ts.factory.createStringLiteral(fullName)] + ); +} + +function buildPropertyAssignments(node: ts.ObjectLiteralExpression, tmpObjName: string, + usePropertyAccess: boolean = true): ts.Expression[] { + return node.properties.map(property => { + if (!ts.isPropertyAssignment(property)) { + return undefined; + } + const key = property.name; + const target = usePropertyAccess && ts.isIdentifier(key) ? + ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(tmpObjName), key) : + ts.factory.createElementAccessExpression(ts.factory.createIdentifier(tmpObjName), + ts.isIdentifier(key) ? ts.factory.createStringLiteral(key.text) : key); + return ts.factory.createAssignment(target, property.initializer); + }).filter(Boolean) as ts.Expression[]; +} + +function getArkTSEvoFileOHMUrl(contextualType: ts.Type): string { + const decl: ts.Declaration = (contextualType.symbol?.declarations || contextualType.aliasSymbol?.declarations)?.[0]; + if (!decl) { + return ''; + } + const sourceFilePath: string = toUnixPath(decl.getSourceFile().fileName); + return arkTSEvoFileOHMUrlMap.get(sourceFilePath); +} + +function getScope(node: ts.Node): ts.Node { + let current: ts.Node | undefined = node; + while (current && !ts.isBlock(current) && !ts.isSourceFile(current)) { + current = current.parent; + } + return current ?? node.getSourceFile(); +} + +function getUniqueName(scope: ts.Node, base: string, usedNames: WeakMap>): string { + if (!usedNames.has(scope)) { + usedNames.set(scope, new Set()); + } + const used: Set = usedNames.get(scope)!; + let name: string = base; + let counter: number = 1; + while (used.has(name)) { + name = `${base}_${counter++}`; + } + used.add(name); + return name; +} + +function declareGlobalTemp(name: string, initializer?: ts.Expression): ts.Statement { + if (initializer && declaredClassVars.has(name)) { + return globalDeclarations.get(name)!; + } + + if (!globalDeclarations.has(name)) { + const decl = ts.factory.createVariableStatement(undefined, + ts.factory.createVariableDeclarationList( + [ts.factory.createVariableDeclaration(name, undefined, undefined, initializer)], ts.NodeFlags.Let)); + globalDeclarations.set(name, decl); + if (initializer) { + declaredClassVars.add(name); + } + } + + return globalDeclarations.get(name)!; +} + +function collectInterfacesMap(rootNode: ts.Node, checker: ts.TypeChecker): Map> { + const classToInterfacesMap = new Map>(); + ts.forEachChild(rootNode, function visit(node) { + if (ts.isClassDeclaration(node)) { + const interfaces = new Set(); + const visited = new Set(); + collectDeepInheritedInterfaces(node, checker, visited, interfaces); + if (interfaces.size > 0) { + classToInterfacesMap.set(node, interfaces); + } + } + ts.forEachChild(node, visit); + }); + return classToInterfacesMap; +} + +function collectDeepInheritedInterfaces(node: ts.ClassDeclaration | ts.InterfaceDeclaration, + checker: ts.TypeChecker, visited: Set, interfaces: Set): void { + const heritageClauses = node.heritageClauses; + if (!heritageClauses) { + return; + } + + for (const clause of heritageClauses) { + for (const exprWithTypeArgs of clause.types) { + const type = checker.getTypeAtLocation(exprWithTypeArgs.expression); + collectDeepInheritedInterfacesFromType(type, checker, visited, interfaces); + } + } +} + +function collectDeepInheritedInterfacesFromType(type: ts.Type, checker: ts.TypeChecker, + visited: Set, interfaces: Set): void { + if (visited.has(type)) { + return; + } + visited.add(type); + const decls: ts.Declaration[] = type.symbol?.declarations; + const isArkTSEvolution: boolean = decls?.some(decl => isFromArkTSEvolutionModule(decl)); + if (isArkTSEvolution) { + const ifacePath: string = getArkTSEvoFileOHMUrl(type); + interfaces.add(`L${ifacePath}/${type.symbol.name};`); + } + const baseTypes: ts.BaseType[] = checker.getBaseTypes(type as ts.InterfaceType) ?? []; + for (const baseType of baseTypes) { + collectDeepInheritedInterfacesFromType(baseType, checker, visited, interfaces); + } + + if (decls) { + for (const decl of decls) { + if (ts.isClassDeclaration(decl) || ts.isInterfaceDeclaration(decl)) { + collectDeepInheritedInterfaces(decl, checker, visited, interfaces); + } + } + } +} + +function transformHeritage(context: ts.TransformationContext, + classToInterfacesMap: Map>): ts.Visitor { + return function visitor(node: ts.SourceFile): ts.SourceFile { + if (ts.isClassDeclaration(node) && classToInterfacesMap.has(node)) { + const interfaceNames = classToInterfacesMap.get(node)!; + const updatedMembers = injectImplementsInConstructor(node, interfaceNames); + return ts.factory.updateClassDeclaration(node, node.modifiers, node.name, node.typeParameters, + node.heritageClauses, updatedMembers); + } + return ts.visitEachChild(node, visitor, context); + }; +} + +function injectImplementsInConstructor(node: ts.ClassDeclaration, interfaceNames: Set): ts.ClassElement[] { + const members: ts.ClassElement[] = [...node.members]; + const params: ts.ParameterDeclaration[] = []; + const needSuper: boolean = + node.heritageClauses?.some(clause => clause.token === ts.SyntaxKind.ExtendsKeyword) || false; + const injectStatement: ts.ExpressionStatement[] = [ + ts.factory.createExpressionStatement( + ts.factory.createStringLiteral(`implements static:${(Array.from(interfaceNames)).join(',')}`) + ) + ]; + const ctorDecl: ts.ConstructorDeclaration | undefined = + members.find(element => ts.isConstructorDeclaration(element)) as ts.ConstructorDeclaration | undefined; + if (ctorDecl) { + const newCtorDecl: ts.ConstructorDeclaration = ts.factory.updateConstructorDeclaration( + ctorDecl, ctorDecl.modifiers, ctorDecl.parameters, + ts.factory.updateBlock( + ctorDecl.body ?? ts.factory.createBlock([], true), + [...injectStatement, ...(ctorDecl.body?.statements ?? [])] + ) + ); + const index: number = members.indexOf(ctorDecl); + members.splice(index, 1, newCtorDecl); + } else { + addSuper(needSuper, injectStatement, params); + const newCtorDecl: ts.ConstructorDeclaration = ts.factory.createConstructorDeclaration( + undefined, params, + ts.factory.createBlock([...injectStatement], true) + ); + members.push(newCtorDecl); + } + return members; +} + +function addSuper(needSuper: boolean, injectStatement: ts.ExpressionStatement[], + params: ts.ParameterDeclaration[]): void { + if (needSuper) { + injectStatement.push( + ts.factory.createExpressionStatement( + ts.factory.createCallExpression( + ts.factory.createSuper(), undefined, [ts.factory.createSpreadElement(ts.factory.createIdentifier(SUPER_ARGS))]) + ) + ); + params.push( + ts.factory.createParameterDeclaration( + undefined, + ts.factory.createToken(ts.SyntaxKind.DotDotDotToken), + ts.factory.createIdentifier(SUPER_ARGS), + undefined, + undefined, + undefined) + ); + } +} diff --git a/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts b/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts index 42a538d80..69cddf379 100644 --- a/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts +++ b/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts @@ -16,18 +16,479 @@ import { expect } from 'chai'; import mocha from 'mocha'; import sinon from 'sinon'; +import ts from 'typescript'; +import path from 'path'; +import proxyquire from 'proxyquire'; import { collectArkTSEvolutionModuleInfo, addDeclFilesConfig, pkgDeclFilesConfig, - arkTSModuleMap + arkTSModuleMap, + arkTSEvolutionModuleMap, + interopTransform, + interopTransformLog, + cleanUpProcessArkTSEvolutionObj } from '../../../lib/process_arkts_evolution'; import RollUpPluginMock from '../mock/rollup_mock/rollup_plugin_mock'; import { BUNDLE_NAME_DEFAULT, HAR_DECLGENV2OUTPATH } from '../mock/rollup_mock/common'; +import { + LogData, + LogDataFactory +} from '../../../lib/fast_build/ark_compiler/logger'; +import { + ArkTSErrorDescription, + ErrorCode +} from '../../../lib/fast_build/ark_compiler/error_code'; + +const testFileName: string = '/TestProject/entry/test.ets'; + +function createDualSourceProgram(testContent: string): { program: ts.Program, testSourceFile: ts.SourceFile } { + const declgenV1OutPath: string = '/TestProject/arkTSEvo/build/default/intermediates/declgen/default/declgenV1'; + arkTSEvolutionModuleMap.set('arkTSEvo', { + language: '1.2', + packageName: 'arkTSEvo', + moduleName: 'arkTSEvo', + modulePath: '/TestProject/arkTSEvo/', + declgenV1OutPath + }); + + const declFileName: string = path.join(declgenV1OutPath, 'arkTSEvo/src/main/ets/decl.d.ets'); + const declSourceFile = ts.createSourceFile(declFileName, DECLFILE_CODE, ts.ScriptTarget.ESNext, true); + const testSourceFile = ts.createSourceFile(testFileName, testContent, ts.ScriptTarget.ESNext, true); + Object.defineProperty(declSourceFile, 'fileName', { value: declFileName }); + Object.defineProperty(testSourceFile, 'fileName', { value: testFileName }); + + const compilerHost = ts.createCompilerHost({ target: ts.ScriptTarget.ESNext }); + const sourceFiles = new Map([ + [declFileName, declSourceFile], + [testFileName, testSourceFile] + ]); + compilerHost.getSourceFile = (fileName, languageVersion) => sourceFiles.get(fileName); + compilerHost.resolveModuleNames = (moduleNames, containingFile) => { + return moduleNames.map(name => { + if (name === 'arkTSEvo') { + return { + resolvedFileName: declFileName, + isExternalLibraryImport: false + }; + } + return undefined; + }); + }; + + return { + program: ts.createProgram({ rootNames: [testFileName, declFileName], options: {}, host: compilerHost }), + testSourceFile: testSourceFile + }; +} + +const DECLFILE_CODE: string = `export declare class ArkTSClass { + public get a(): number; + public set a(value: number); + constructor(); +} +export declare interface ArkTSInterface { + public get a(): number; + public set a(value: number); +} +export declare interface I1{}; +export declare interface I2{}; +export declare class ArkTSClassNoCtor { + public get a(): number; + public set a(value: number); + constructor(x: number); +} +export declare function ArkTSFuncClass(a: ArkTSClass): void; +export declare function ArkTSFuncInterface(a: ArkTSInterface): void; +export declare function ArkTSRecordFunc(rec: Record): void; +`; + +const CLASS_NO_HAS_NO_ARG_CONSTRUCTOR_CODE: string = `import { ArkTSClassNoCtor } from "arkTSEvo"; +let noCtor: ArkTSClassNoCtor = { a: 1 }; +`; + +const IMPORT_ARKTS_EVO_RECORD_CODE: string = `import { ArkTSRecordFunc } from "arkTSEvo"; +ArkTSRecordFunc({a: 1}); +`; + +const IMPORT_ARKTS_EVO_RECORD_CODE_EXPECT: string = `import { ArkTSRecordFunc } from "arkTSEvo"; +let tmpRecord = globalThis.gtest.etsVM.getInstance("Lescompat/Record"); +let tmpObj; +ArkTSRecordFunc((tmpObj = new tmpRecord(), tmpObj["a"] = 1, tmpObj)); +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_1: string = `import { ArkTSClass } from "arkTSEvo"; +let a: ArkTSClass = {a: 1}; +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_1_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +let a: ArkTSClass = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_2: string = `import { ArkTSClass } from "arkTSEvo"; +let an = new ArkTSClass(); +an = {a: 1}; +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_2_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +let an = new ArkTSClass(); +an = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_3: string = `import { ArkTSClass } from "arkTSEvo"; +let aas = {a: 1} as ArkTSClass; +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_3_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +let aas = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj) as ArkTSClass; +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_4: string = `import { ArkTSClass } from "arkTSEvo"; +class A { + a: ArkTSClass = {a: 1} +} +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_4_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +class A { + a: ArkTSClass = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +} +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_5: string = `import { ArkTSClass } from "arkTSEvo"; +class AA { + a: ArkTSClass; + constructor(a: ArkTSClass) { + this.a = a; + } +} +let aa = new AA({a: 1}) +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_5_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +class AA { + a: ArkTSClass; + constructor(a: ArkTSClass) { + this.a = a; + } +} +let aa = new AA((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_6: string = `import { ArkTSClass } from "arkTSEvo"; +class AAA { + a: ArkTSClass = new ArkTSClass(); +} +let aaa: AAA = {a: {a: 1}} +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_6_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +class AAA { + a: ArkTSClass = new ArkTSClass(); +} +let aaa: AAA = { a: (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj) }; +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_7: string = `import { ArkTSClass } from "arkTSEvo"; +function foo(a: ArkTSClass = {a:1}) {} +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_7_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +function foo(a: ArkTSClass = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)) { } +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_8: string = `import { ArkTSClass } from "arkTSEvo"; +function bar(a: ArkTSClass){} +bar({a: 1}) +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_8_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +function bar(a: ArkTSClass) { } +bar((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_9: string = `import { ArkTSClass } from "arkTSEvo"; +let aaa: () => ArkTSClass = () => ({a: 1}) +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_9_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +let aaa: () => ArkTSClass = () => ((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_10: string = `import { ArkTSClass } from "arkTSEvo"; +function fooa(): ArkTSClass { + return {a: 1} +} +`; + +const IMPORT_ARKTS_EVO_CLASS_CODE_10_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +function fooa(): ArkTSClass { + return (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +} +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_1: string = `import { ArkTSInterface } from "arkTSEvo"; +let a: ArkTSInterface = {a: 1}; +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_1_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj; +let a: ArkTSInterface = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_2: string = `import { ArkTSInterface } from "arkTSEvo"; +let aas = {a: 1} as ArkTSInterface; +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_2_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj; +let aas = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj) as ArkTSInterface; +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_3: string = `import { ArkTSInterface } from "arkTSEvo"; +class A { + a: ArkTSInterface = {a: 1} +} +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_3_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj; +class A { + a: ArkTSInterface = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +} +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_4: string = `import { ArkTSInterface } from "arkTSEvo"; +class AA { + a: ArkTSInterface; + constructor(a: ArkTSInterface) { + this.a = a; + } +} +let aa = new AA({a: 1}) +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_4_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj; +class AA { + a: ArkTSInterface; + constructor(a: ArkTSInterface) { + this.a = a; + } +} +let aa = new AA((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_5: string = `import { ArkTSInterface } from "arkTSEvo"; +function foo(a: ArkTSInterface = {a:1}) {} +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_5_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj; +function foo(a: ArkTSInterface = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)) { } +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_6: string = `import { ArkTSInterface } from "arkTSEvo"; +function bar(a: ArkTSInterface){} +bar({a: 1}) +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_6_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj; +function bar(a: ArkTSInterface) { } +bar((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_7: string = `import { ArkTSInterface } from "arkTSEvo"; +let aaa: () => ArkTSInterface = () => ({a: 1}) +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_7_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj; +let aaa: () => ArkTSInterface = () => ((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_8: string = `import { ArkTSInterface } from "arkTSEvo"; +function fooa(): ArkTSInterface { + return {a: 1} +} +`; + +const IMPORT_ARKTS_EVO_INTERFACE_CODE_8_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj; +function fooa(): ArkTSInterface { + return (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +} +`; + +const IMPORT_ARKTS_EVO_FUNCTION_CODE: string = `import { + ArkTSFuncClass, + ArkTSFuncInterface +} from "arkTSEvo"; +ArkTSFuncClass({a: 1}); +ArkTSFuncInterface({a: 1}); +`; + +const IMPORT_ARKTS_EVO_FUNCTION_CODE_EXPECT: string = `import { ArkTSFuncClass, ArkTSFuncInterface } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +let tmpClass_1 = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpObj_1; +ArkTSFuncClass((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); +ArkTSFuncInterface((tmpObj_1 = new tmpClass_1(), tmpObj_1.a = 1, tmpObj_1)); +`; + +const UNION_NO_AMBIGUITY_CODE: string = `import { ArkTSClass } from "arkTSEvo"; +let a: ArkTSClass | undefined = {a: 1}; +`; + +const UNION_NO_AMBIGUITY_CODE_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +let a: ArkTSClass | undefined = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +`; + +const UNION_AMBIGUITY_CODE: string = `import { +ArkTSClass, +ArkTSInterface +} from "arkTSEvo"; +class A { + a: number; +} +class B { + a: number; +} +let a1: A | B = {a: 1}; +let a2: ArkTSClass | ArkTSInterface = {a: 1}; +let a2: A | B | ArkTSClass | ArkTSInterface = {a: 1}; +`; + +const UNION_AMBIGUITY_CODE_EXPECT: string = `import { ArkTSClass, ArkTSInterface } from "arkTSEvo"; +class A { + a: number; +} +class B { + a: number; +} +let a1: A | B = { a: 1 }; +let a2: ArkTSClass | ArkTSInterface = { a: 1 }; +let a2: A | B | ArkTSClass | ArkTSInterface = { a: 1 }; +`; + +const PARENTHESIZED_CODE: string = `import { ArkTSClass } from "arkTSEvo"; +let a: (ArkTSClass) = {a: 1}; +`; + +const PARENTHESIZED_CODE_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; +let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); +let tmpObj; +let a: (ArkTSClass) = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); +`; + +const CLASS_IMPLEMENTS_ARKTS_EVO_CLASS_OR_INTERFACE_CODE: string = `import { I1, I2 } from "arkTSEvo"; +interface I3 {}; +class A implements I1 {} +class B extends A {} +interface I4 extends I2 {} +class C implements I3, I4 {} +class D extends B implements I4 {} +class E implements I2 { + a: number; + constructor(a: number) { + this.a = a; + } +} +class F extends D { + constructor() { + super(); + } +} +interface I5 extends I1, I4 {} +class G extends A implements I5, I3 {} +`; + +const CLASS_IMPLEMENTS_ARKTS_EVO_CLASS_OR_INTERFACE_CODE_EXPECT: string = `import { I1, I2 } from "arkTSEvo"; +interface I3 { +} +; +class A implements I1 { + constructor() { + "implements static:LarkTSEvo/src/main/ets/decl/I1;"; + } +} +class B extends A { + constructor(...args) { + "implements static:LarkTSEvo/src/main/ets/decl/I1;"; + super(...args); + } +} +interface I4 extends I2 { +} +class C implements I3, I4 { + constructor() { + "implements static:LarkTSEvo/src/main/ets/decl/I2;"; + } +} +class D extends B implements I4 { + constructor(...args) { + "implements static:LarkTSEvo/src/main/ets/decl/I1;,LarkTSEvo/src/main/ets/decl/I2;"; + super(...args); + } +} +class E implements I2 { + a: number; + constructor(a: number) { + "implements static:LarkTSEvo/src/main/ets/decl/I2;"; + this.a = a; + } +} +class F extends D { + constructor() { + "implements static:LarkTSEvo/src/main/ets/decl/I1;,LarkTSEvo/src/main/ets/decl/I2;"; + super(); + } +} +interface I5 extends I1, I4 { +} +class G extends A implements I5, I3 { + constructor(...args) { + "implements static:LarkTSEvo/src/main/ets/decl/I1;,LarkTSEvo/src/main/ets/decl/I2;"; + super(...args); + } +} +`; mocha.describe('process arkts evolution tests', function () { mocha.before(function () { @@ -115,4 +576,243 @@ mocha.describe('process arkts evolution tests', function () { expect(pkgDeclFilesConfig['har'].files['Index'].ohmUrl === expectOhmUrl).to.be.true; arkTSModuleMap.clear(); }); + + mocha.describe('3: process arkts evolution tests: interop transform', function () { + mocha.it('3-1-1: test mixCompile is false', function () { + const sourceFile: ts.SourceFile = ts.createSourceFile('a.ts', 'let x = 1;', ts.ScriptTarget.ESNext); + const program: ts.Program = ts.createProgram({ rootNames: ['a.ts'], options: {}, host: ts.createCompilerHost({}) }); + const result: ts.SourceFile = interopTransform(program, testFileName, false, false)()(sourceFile); + expect(result === sourceFile).to.be.true; + }); + + mocha.it('3-1-2: test error message of ArkTS evoluion class does not has a no-argument constructor', function () { + const { program, testSourceFile } = createDualSourceProgram(CLASS_NO_HAS_NO_ARG_CONSTRUCTOR_CODE); + const errInfo: LogData = LogDataFactory.newInstance( + ErrorCode.ETS2BUNDLE_EXTERNAL_CLASS_HAS_NO_CONSTRUCTOR_WITHOUT_ARGS, + ArkTSErrorDescription, + 'The class "ArkTSClassNoCtor" does not has no no-argument constructor.', + '', + [ + 'Please confirm whether there is a no-argument constructor ' + + 'in the ArkTS Evolution class "ArkTSClassNoCtor" type in the object literal.' + ] + ); + ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]); + const hasError = interopTransformLog.errors.some(error => + error.message.includes(errInfo.toString()) + ); + expect(hasError).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-3: test import ArkTS evoluion Record in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_RECORD_CODE); + const isStaticRecord = () => (true); + const mockedTs = { + ...require('typescript'), + isStaticRecord + }; + let interopTransform; + ({ interopTransform } = proxyquire('../../../lib/process_arkts_evolution', { 'typescript': mockedTs })); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_RECORD_CODE_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-1: test import ArkTS evoluion class (variable init) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_1); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_1_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-2: test import ArkTS evoluion class (object assignment) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_2); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_2_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-3: test import ArkTS evoluion class (type assertions) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_3); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_3_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-4: test import ArkTS evoluion class (property init) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_4); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_4_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-5: test import ArkTS evoluion class (contr function call) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_5); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_5_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-6: test import ArkTS evoluion class (multi-layer object assignment) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_6); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_6_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-7: test import ArkTS evoluion class (parameter initp) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_7); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_7_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-8: test import ArkTS evoluion class (function call) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_8); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_8_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-9: test import ArkTS evoluion class (arrow function return value) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_9); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_9_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-4-10: test import ArkTS evoluion class (function return value) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_10); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_10_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-5-1: test import ArkTS evoluion interface (variable init) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_1); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_1_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-5-2: test import ArkTS evoluion interface (type assertions) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_2); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_2_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-5-3: test import ArkTS evoluion interface (property init) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_3); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_3_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-5-4: test import ArkTS evoluion interface (contr function call) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_4); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_4_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-5-5: test import ArkTS evoluion interface (parameter initp) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_5); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_5_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-5-6: test import ArkTS evoluion interface (function call) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_6); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_6_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-5-7: test import ArkTS evoluion interface (arrow function return value) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_7); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_7_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-5-8: test import ArkTS evoluion interface (function return value) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_8); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_8_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-6: test import ArkTS evoluion function in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_FUNCTION_CODE); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === IMPORT_ARKTS_EVO_FUNCTION_CODE_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-7: test union type (no ambiguity) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(UNION_NO_AMBIGUITY_CODE); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === UNION_NO_AMBIGUITY_CODE_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-8: test union type (ambiguity) in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(UNION_AMBIGUITY_CODE); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + const errInfo: LogData = LogDataFactory.newInstance( + ErrorCode.ETS2BUNDLE_EXTERNAL_UNION_TYPE_AMBIGUITY, + ArkTSErrorDescription, + `Ambiguous union type: multiple valid ArkTSEvolution types found: [ArkTSClass, ArkTSInterface].`, + '', + ['Please use type assertion as to disambiguate.'] + ); + const hasError = interopTransformLog.errors.some(error => + error.message.includes(errInfo.toString()) + ); + expect(hasError).to.be.true; + expect(resultCode === UNION_AMBIGUITY_CODE_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-1-9: test parenthesized type in object literal', function () { + const { program, testSourceFile } = createDualSourceProgram(PARENTHESIZED_CODE); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === PARENTHESIZED_CODE_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + + mocha.it('3-2-1: test class extends arkTS evolution class or implement arkTS evolution interface', function () { + const { program, testSourceFile } = createDualSourceProgram(CLASS_IMPLEMENTS_ARKTS_EVO_CLASS_OR_INTERFACE_CODE); + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, true)]).transformed[0]; + const resultCode = ts.createPrinter().printFile(result); + expect(resultCode === CLASS_IMPLEMENTS_ARKTS_EVO_CLASS_OR_INTERFACE_CODE_EXPECT).to.be.true; + cleanUpProcessArkTSEvolutionObj(); + }); + }); }); \ No newline at end of file -- Gitee From 3ba868c5e281a41b7ffbdd3d449d9ad625e6efe5 Mon Sep 17 00:00:00 2001 From: Cuecuexiaoyu Date: Tue, 27 May 2025 16:00:37 +0800 Subject: [PATCH 098/123] add kit dependencies import Signed-off-by: Cuecuexiaoyu Change-Id: Ic0aa369289ab8ac1199a3c2256e32a708f096856 --- arkui-plugins/common/arkts-utils.ts | 9 ++-- arkui-plugins/common/predefines.ts | 47 +------------------ .../function-with-receiver.test.ts | 4 +- .../animation/animation-basic.test.ts | 10 ++-- .../style-with-receiver.test.ts | 6 +-- .../init-with-local-builder.test.ts | 8 ++-- .../decorators/builder/global-builder.test.ts | 8 ++-- .../decorators/builder/local-builder.test.ts | 8 ++-- .../observed-track/observed-only.test.ts | 10 ++-- .../observed-track-class-property.test.ts | 10 ++-- .../observed-track-complex-type.test.ts | 12 ++--- .../observed-track-extends.test.ts | 10 ++-- .../observed-track-implements.test.ts | 10 ++-- .../observed-track/observed-track.test.ts | 10 ++-- .../observed-track/track-only.test.ts | 10 ++-- .../decorators/prop/prop-basic-type.test.ts | 8 ++-- .../decorators/prop/prop-complex-type.test.ts | 8 ++-- .../decorators/prop/state-to-prop.test.ts | 8 ++-- .../provide-annotation-usage.test.ts | 8 ++-- .../provide-basic-type.test.ts | 8 ++-- .../provide-complex-type.test.ts | 8 ++-- .../resource/resource-in-build.test.ts | 8 ++-- .../resource/resource-in-property.test.ts | 8 ++-- .../reusable/reusable-basic.test.ts | 8 ++-- .../reusable/reusable-complex.test.ts | 10 ++-- .../decorators/state/state-basic-type.test.ts | 8 ++-- .../state/state-complex-type.test.ts | 8 ++-- .../decorators/state/state-to-state.test.ts | 8 ++-- .../storagelink-appstorage.test.ts | 10 ++-- .../storagelink-complex-type.test.ts | 10 ++-- .../storagelink-primitive-type.test.ts | 10 ++-- .../storageprop-appstorage.test.ts | 10 ++-- .../storageprop-complex-type.test.ts | 10 ++-- .../storageprop-primitive-type.test.ts | 10 ++-- .../decorators/watch/watch-basic.test.ts | 12 ++--- .../xcomponent/xcomponent-basic.test.ts | 10 ++-- .../ui-plugins/entry-translators/utils.ts | 2 +- .../ui-plugins/preprocessor-transform.ts | 23 ++++++++- arkui-plugins/ui-plugins/utils.ts | 2 +- 39 files changed, 183 insertions(+), 204 deletions(-) diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index 4e797d755..e62d9c991 100644 --- a/arkui-plugins/common/arkts-utils.ts +++ b/arkui-plugins/common/arkts-utils.ts @@ -99,8 +99,11 @@ export function updateStructMetadata( } export function moveToFront(arr: T[], idx: number): T[] { - if (idx >= arr.length) { - throw new Error(`Invalid argument, size of array: ${arr.length}, index: ${idx}`); + if (idx < 0 || idx >= arr.length) { + throw new Error(`Index ${idx} is out of bounds for array of length ${arr.length}`); } - return [arr[idx], ...arr.slice(0, idx), ...arr.slice(idx + 1)]; + + const copy = [...arr]; + const [item] = copy.splice(idx, 1); + return [item, ...copy]; } \ No newline at end of file diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index d4667b424..2029bd8e7 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -29,8 +29,8 @@ export const EXTERNAL_SOURCE_PREFIX_NAMES: (string | RegExp)[] = [ ]; export const ARKUI_COMPONENT_IMPORT_NAME: string = '@ohos.arkui.component'; - export const ARKUI_STATEMANAGEMENT_IMPORT_NAME: string = '@ohos.arkui.stateManagement'; +export const KIT_ARKUI_NAME: string = '@kit.ArkUI'; export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ ARKUI_COMPONENT_IMPORT_NAME, @@ -38,50 +38,7 @@ export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ ]; export const IMPORT_SOURCE_MAP: Map> = new Map>([ - ['@ohos.arkui.component', new Set(['$r', '$rawfile', '_r', '_rawfile', 'Bindable'])], - [ - '@ohos.arkui.stateManagement', - new Set([ - 'State', - 'Prop', - 'Provide', - 'Consume', - 'StorageLink', - 'StorageProp', - 'LocalStorageLink', - 'LocalStorageProp', - 'Watch', - 'ObjectLink', - 'Observed', - 'Track', - 'StateDecoratedVariable', - 'MutableState', - 'contextLocalStateOf', - 'contextLocal', - 'observableProxy', - 'propState', - 'StorageLinkState', - 'SyncedProperty', - 'DecoratedV1VariableBase', - 'LinkDecoratedVariable', - 'PropDecoratedVariable', - 'StorageLinkDecoratedVariable', - 'StoragePropDecoratedVariable', - 'MutableStateMeta', - 'BackingValue', - 'setObservationDepth', - 'IObservedObject', - 'ProvideDecoratedVariable', - 'ConsumeDecoratedVariable', - 'memo', - '__memo_context_type', - '__memo_id_type', - 'ObjectLinkDecoratedVariable', - 'WatchIdType', - 'SubscribedWatches' - ]), - ], - ['@koalaui.runtime.common', new Set(['int32'])] + ['arkui.stateManagement.runtime', new Set(['memo', '__memo_context_type', '__memo_id_type'])] ]); export const OUTPUT_DEPENDENCY_MAP: Map = new Map([ diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts index 8cfc8fc1d..219dec151 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts @@ -37,8 +37,8 @@ const parsedTransform: Plugins = { const pluginTester = new PluginTester('test memo lambda', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "@ohos.arkui.stateManagement"; function main() {} diff --git a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts index cae171a65..dd4678db6 100644 --- a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts @@ -37,19 +37,19 @@ const animationTransform: Plugins = { const pluginTester = new PluginTester('test basic animation transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Text as Text, Column as Column, Component as Component, Color as Color, Curve as Curve } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts index d84397d42..1c64f1cdb 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts @@ -37,11 +37,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { memo as memo } from "@ohos.arkui.stateManagement"; import { Text as Text, UITextAttribute as UITextAttribute, Column as Column, Component as Component } from "@ohos.arkui.component"; import hilog from "@ohos.hilog"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts index 336ee7389..96bf7204b 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts @@ -37,10 +37,10 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; function main() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts index 09ffcfbaa..95740a1d5 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts @@ -37,12 +37,12 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { UIRowAttribute as UIRowAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Row as Row, Builder as Builder, Text as Text } from "@ohos.arkui.component"; function main() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts index 084238f23..e13c9d93a 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts @@ -37,12 +37,12 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, Builder as Builder, Text as Text } from "@ohos.arkui.component"; function main() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts index 55af0dd86..c7cdb537e 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts @@ -37,17 +37,17 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed only transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { int32 as int32 } from "@koalaui.runtime.common"; +import { int32 as int32 } from "@ohos.arkui.stateManagement"; import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; @@ -57,7 +57,7 @@ import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts index becd4ced5..d001176ca 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts @@ -37,17 +37,17 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed track transform with class property', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { int32 as int32 } from "@koalaui.runtime.common"; +import { int32 as int32 } from "@ohos.arkui.stateManagement"; import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; @@ -57,7 +57,7 @@ import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts index b0635b8a9..40648706c 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts @@ -37,17 +37,17 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed track transform with complex type', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { int32 as int32 } from "@koalaui.runtime.common"; +import { int32 as int32 } from "@ohos.arkui.stateManagement"; import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; @@ -57,9 +57,9 @@ import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts index 47237cf0c..5521fe099 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts @@ -37,17 +37,17 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed track transform with extends', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { int32 as int32 } from "@koalaui.runtime.common"; +import { int32 as int32 } from "@ohos.arkui.stateManagement"; import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; @@ -57,7 +57,7 @@ import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts index c4239714b..488899833 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts @@ -37,17 +37,17 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed track transform with implements', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { int32 as int32 } from "@koalaui.runtime.common"; +import { int32 as int32 } from "@ohos.arkui.stateManagement"; import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; @@ -57,7 +57,7 @@ import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts index 95a77ed88..fc8f76115 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts @@ -37,17 +37,17 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed with track transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { int32 as int32 } from "@koalaui.runtime.common"; +import { int32 as int32 } from "@ohos.arkui.stateManagement"; import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; @@ -57,7 +57,7 @@ import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts index c21fe95f3..c481467e0 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts @@ -37,17 +37,17 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test track only transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { int32 as int32 } from "@koalaui.runtime.common"; +import { int32 as int32 } from "@ohos.arkui.stateManagement"; import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; @@ -57,7 +57,7 @@ import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts index b25b5c22d..7284beb5e 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts @@ -37,11 +37,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Prop as Prop } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts index 312db0a77..5c6262494 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts @@ -37,11 +37,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Prop as Prop } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts index 787797bc6..71b40bf8c 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts @@ -37,15 +37,15 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Text as Text, Button as Button, Column as Column, ClickEvent as ClickEvent } from "@ohos.arkui.component"; import { Prop as Prop, State as State } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts index 5239317ac..d696b4a79 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts @@ -37,11 +37,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Provide as Provide } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts index 8ce1a14e5..92e8579d7 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts @@ -37,11 +37,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Provide as Provide } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts index 0a2eb5ae7..51952cc98 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts @@ -37,11 +37,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Provide as Provide } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts index 1925eef83..dc235c38c 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts @@ -37,9 +37,9 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UIImageAnimatorAttribute as UIImageAnimatorAttribute } from "@ohos.arkui.component"; import { UISelectAttribute as UISelectAttribute } from "@ohos.arkui.component"; import { UITextInputAttribute as UITextInputAttribute } from "@ohos.arkui.component"; @@ -48,7 +48,7 @@ import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { _rawfile as _rawfile } from "@ohos.arkui.component"; import { _r as _r } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, TextInput as TextInput, Select as Select, SelectOption as SelectOption, Margin as Margin, ImageAnimator as ImageAnimator } from "@ohos.arkui.component"; function main() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts index 60451251c..e84095778 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts @@ -37,15 +37,15 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { _rawfile as _rawfile } from "@ohos.arkui.component"; import { _r as _r } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, Resource as Resource } from "@ohos.arkui.component"; let i: Resource; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts index f4a20b03e..aead2d3df 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts @@ -37,11 +37,11 @@ const reusableTransform: Plugins = { const pluginTester = new PluginTester('test basic reusable', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; @@ -49,7 +49,7 @@ import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stat import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Reusable as Reusable } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts index dbbd61448..29ab50400 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts @@ -37,11 +37,11 @@ const reusableTransform: Plugins = { const pluginTester = new PluginTester('test complex reusable', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; @@ -51,9 +51,9 @@ import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Reusable as Reusable, Column as Column, Text as Text, Button as Button, ClickEvent as ClickEvent, FontWeight as FontWeight } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts index a3258fa0b..77e81ddc0 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts @@ -37,11 +37,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { State as State } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts index eeec6cdc4..fdb92c74a 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts @@ -37,11 +37,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { State as State } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts index eb7d0a500..406d937b5 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts @@ -37,13 +37,13 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, Text as Text } from "@ohos.arkui.component"; import { State as State } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts index 8e1832428..b41f7e584 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts @@ -37,11 +37,11 @@ const storageLinkTransform: Plugins = { const pluginTester = new PluginTester('test storagelink with appstorage', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; @@ -49,9 +49,9 @@ import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts index c060b7a83..25fba5eb4 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts @@ -37,17 +37,17 @@ const storageLinkTransform: Plugins = { const pluginTester = new PluginTester('test storagelink complex type transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts index e129e2600..da4f0e41b 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts @@ -37,17 +37,17 @@ const storageLinkTransform: Plugins = { const pluginTester = new PluginTester('test storagelink primitive type transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts index a403e00a9..d1074e980 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts @@ -37,11 +37,11 @@ const storagePropTransform: Plugins = { const pluginTester = new PluginTester('test storageprop with appstorage', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; @@ -49,9 +49,9 @@ import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts index aa649440b..8580f8a27 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts @@ -37,17 +37,17 @@ const storagePropTransform: Plugins = { const pluginTester = new PluginTester('test storageprop complex type transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts index c56d42735..988da9f67 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts @@ -37,17 +37,17 @@ const storagePropTransform: Plugins = { const pluginTester = new PluginTester('test storageprop primitive type transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts index 692bf1f24..ca024fc1f 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts @@ -37,11 +37,11 @@ const watchTransform: Plugins = { const pluginTester = new PluginTester('test basic watch transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { ConsumeDecoratedVariable as ConsumeDecoratedVariable } from "@ohos.arkui.stateManagement"; @@ -51,7 +51,7 @@ import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagem import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { int32 as int32 } from "@koalaui.runtime.common"; +import { int32 as int32 } from "@ohos.arkui.stateManagement"; import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; @@ -75,9 +75,9 @@ import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stat import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts index 46686c1e6..54d600a56 100644 --- a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts @@ -37,19 +37,19 @@ const xcomponentTransform: Plugins = { const pluginTester = new PluginTester('test basic XComponent transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UIXComponentAttribute as UIXComponentAttribute } from "@ohos.arkui.component"; import { UIFlexAttribute as UIFlexAttribute } from "@ohos.arkui.component"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Flex as Flex, XComponent as XComponent, FlexDirection as FlexDirection, XComponentType as XComponentType, Entry as Entry, XComponentController as XComponentController, ItemAlign as ItemAlign, FlexAlign as FlexAlign, XComponentParameter as XComponentParameter } from "@ohos.arkui.component"; diff --git a/arkui-plugins/ui-plugins/entry-translators/utils.ts b/arkui-plugins/ui-plugins/entry-translators/utils.ts index c3b1dfbef..61a03783c 100644 --- a/arkui-plugins/ui-plugins/entry-translators/utils.ts +++ b/arkui-plugins/ui-plugins/entry-translators/utils.ts @@ -23,7 +23,7 @@ export enum EntryWrapperNames { WRAPPER_CLASS_NAME = '__EntryWrapper', ENTRY_STORAGE_ANNOTATION_KEY = 'storage', ENTRY_STORAGE_LOCAL_STORAGE_PROPERTY_NAME = '_entry_local_storage_', - ENTRY_DEFAULT_IMPORT = '@ohos.arkui.component', + ENTRY_DEFAULT_IMPORT = 'arkui.UserView', ENTRY_POINT_CLASS_NAME = 'EntryPoint', } diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index d6f90b49c..4f9570ec8 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -17,7 +17,13 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { CustomComponentNames } from './utils'; import { factory } from './ui-factory'; -import { ARKUI_COMPONENT_IMPORT_NAME, IMPORT_SOURCE_MAP, OUTPUT_DEPENDENCY_MAP } from '../common/predefines'; +import { + ARKUI_COMPONENT_IMPORT_NAME, + IMPORT_SOURCE_MAP, + OUTPUT_DEPENDENCY_MAP, + ARKUI_STATEMANAGEMENT_IMPORT_NAME, + KIT_ARKUI_NAME, +} from '../common/predefines'; import { NameCollector } from './name-collector'; interface MemoImportCollection { @@ -49,6 +55,8 @@ export class PreprocessorTransformer extends AbstractVisitor { this.memoImportCollection = {}; this.localComponentNames = []; this.isMemoImportOnce = false; + IMPORT_SOURCE_MAP.clear(); + IMPORT_SOURCE_MAP.set('arkui.stateManagement.runtime', new Set(['memo', '__memo_context_type', '__memo_id_type'])); } isCustomConponentDecl(node: arkts.CallExpression): boolean { @@ -188,10 +196,21 @@ export class PreprocessorTransformer extends AbstractVisitor { // Handling component imports const importName: string = node.imported.name; const sourceName: string = source.str; - if (this.nameCollector.getComponents().includes(importName) && sourceName === ARKUI_COMPONENT_IMPORT_NAME) { + if ( + this.nameCollector.getComponents().includes(importName) && + (sourceName === ARKUI_COMPONENT_IMPORT_NAME || sourceName === KIT_ARKUI_NAME) + ) { const newDependencies = [`UI${importName}Attribute`]; this.updateOutDependencyMap(importName, newDependencies); this.updateSourceDependencyMap(sourceName, newDependencies); + } else if ( + OUTPUT_DEPENDENCY_MAP.get(importName) && + (sourceName === ARKUI_COMPONENT_IMPORT_NAME || + sourceName === ARKUI_STATEMANAGEMENT_IMPORT_NAME || + sourceName === KIT_ARKUI_NAME) + ) { + const newDependencies: string[] = OUTPUT_DEPENDENCY_MAP.get(importName) ?? []; + this.updateSourceDependencyMap(sourceName, newDependencies); } } diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index 73a22180b..d7276ab90 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -23,7 +23,7 @@ export enum CustomComponentNames { RESUABLE_ANNOTATION_NAME = 'Reusable', COMPONENT_BUILD_ORI = 'build', COMPONENT_CONSTRUCTOR_ORI = 'constructor', - COMPONENT_DEFAULT_IMPORT = '@ohos.arkui.component', + COMPONENT_DEFAULT_IMPORT = 'arkui.component.customComponent', COMPONENT_CLASS_NAME = 'CustomComponent', COMPONENT_INTERFACE_PREFIX = '__Options_', COMPONENT_INITIALIZE_STRUCT = '__initializeStruct', -- Gitee From 2c9c56a38f321dac35bca0cad253b9a1b4f5b928 Mon Sep 17 00:00:00 2001 From: l00913061 Date: Tue, 27 May 2025 17:43:19 +0800 Subject: [PATCH 099/123] interopstate Signed-off-by: l00913061 Change-Id: I3364a4f45bdadb47b0ebf0da93d5fadc9de1556f --- .../demo/interop/1.2State-1.1Link-example.ets | 104 +++++++ .../ui-plugins/checked-transformer.ts | 6 +- .../ui-plugins/component-transformer.ts | 15 +- arkui-plugins/ui-plugins/initstatevar.ts | 290 ++++++++++++++++++ arkui-plugins/ui-plugins/interop.ts | 264 ++++++++-------- .../ui-plugins/legacy-transformer.ts | 123 +++++++- 6 files changed, 650 insertions(+), 152 deletions(-) create mode 100644 arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets create mode 100644 arkui-plugins/ui-plugins/initstatevar.ts diff --git a/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets b/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets new file mode 100644 index 000000000..f11af005f --- /dev/null +++ b/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets @@ -0,0 +1,104 @@ +/* + * 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. + */ + + +// ArkTS1.2 +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { ArkUICompatible, InteropComponent, Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickEvent, UserView, } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins +import { State, StateDecoratedVariable, MutableState, stateOf, observableProxy, Observed, Track, Provide, Consume } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { MyText } from 'har2/src/main/ets/components/MainPage' +import { Child1 } from 'har1' + + +@Component +struct MyStateSample { + @State stateVar: new MyText(); + build() { + Column() { + Button(this.stateVar.text) + .onClick((e: ClickEvent) => { + this.stateVar.text += '~'; + }) + Child1({stateVar: this.stateVar, text: this.stateVar}) + } + } +} + +class MyText { + text: string = 'MyText'; +} + + +//ArkT1.1 +import { MyText } from 'har2/src/main/ets/components/MainPage' + +@Component +export struct Child1{ + @Link stateVar: MyText; + @Link text: MyText; + build() { + Column() { + Button(this.stateVar.text) + .onClick(() => { + this.stateVar.text += '~'; + }) + Button(this.text.text) + .onClick(() => { + this.text.text = 'ArkTS1.1'; + }) + } + } +} + + +//transform 1.1struct 'Child1' to ArkUICompatible + +ArkUICompatible(__memo_context, ((__memo_id) + (252133223)), (() => { + let global = ESValue.getGlobal(); + let param = ESValue.instantiateEmptyObject(); + let createState = global.getProperty("createStateVariable"); + let stateVar_SetSource = ((value: B) => { + (this).stateVar = value; + }); + let stateVar_ProxyState = createState.invoke(ESValue.wrap((this).stateVar), ESValue.wrap(stateVar_SetSource)); + (this).__backing_stateVar!.setProxy(stateVar_ProxyState); + let stateVar_SetProxy = ((value: B) => { + stateVar_ProxyState.invokeMethod("set", ESValue.wrap(value)); + }); + (this).__backing_stateVar!.setProxyValue = stateVar_SetProxy; + let stateVar_NotifyCallback = ((propertyName: string) => { + stateVar_ProxyState.invokeMethod("notifyPropertyHasChangedPU"); + }); + (this).__backing_stateVar!.setNotifyCallback(stateVar_NotifyCallback); + param.setProperty("stateVar", stateVar_ProxyState); + param.setProperty("text", stateVar_ProxyState); + let extraInfo = ESValue.instantiateEmptyObject(); + extraInfo.setProperty("page", "har1/src/main/ets/components/MainPage"); + let esundefined = ESValue.wrap(undefined); + let blank = (() => {}); + let esblank = ESValue.wrap((blank as object)); + let viewStackProcessor = global.getProperty("ViewStackProcessor"); + let createId = viewStackProcessor.getProperty("AllocateNewElmetIdForNextComponent"); + let elmtId = createId.invoke(); + let har1 = ESValue.load("@normalized:N&entry&com.example.Interop2use1&har1/src/main/ets/components/MainPage&1.0.0"); + let structObject = har1.getProperty("Child1"); + let component = structObject.instantiate(esundefined, param, esundefined, elmtId, esblank, extraInfo); + let create = structObject.getProperty("create"); + create.invoke(component); + return { + component: component, + name: "Child1", + }; +}), ((instance: ESValue) => {})); \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 16e565d63..0e9df875a 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -46,7 +46,7 @@ import { isEntryWrapperClass } from './entry-translators/utils'; import { classifyObservedTrack, classifyProperty, PropertyTranslator } from './property-translators'; import { ObservedTrackTranslator } from './property-translators/observedTrack'; import { nodeByType } from '@koalaui/libarkts/build/src/reexport-for-generated'; -import { updateStateVar } from './interop'; +import { isArkUICompatible, updateArkUICompatible } from './interop'; export class CheckedTransformer extends AbstractVisitor { private scopeInfoCollection: ScopeInfoCollection; @@ -118,8 +118,8 @@ export class CheckedTransformer extends AbstractVisitor { } else if (arkts.isClassDeclaration(node)) { return transformObservedTracked(node); - } else if (arkts.isCallExpression(node)) { - return updateStateVar(node); + } else if (isArkUICompatible(node)) { + return updateArkUICompatible(node as arkts.CallExpression); } return node; } diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 5fce81159..cc6b9acd4 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -37,7 +37,7 @@ import { factory } from './ui-factory'; import { StructMap } from '../common/program-visitor'; -import { processStructCall } from './interop'; +import { generateTempCallFunction } from './interop'; import { stringify } from 'querystring'; export interface ComponentTransformerOptions extends VisitorOptions { @@ -58,7 +58,8 @@ interface ComponentContext { export interface InteropContext { className: string; path: string; - stateVarMap: Map; + line?: number; + col?: number; arguments?: arkts.ObjectExpression; } @@ -74,7 +75,6 @@ export class ComponentTransformer extends AbstractVisitor { private hasLegacy = false; private legacyStructMap: Map = new Map(); private legacyCallMap: Map = new Map(); - private stateVarMap: Map = new Map(); constructor(options?: ComponentTransformerOptions) { const _options: ComponentTransformerOptions = options ?? {}; @@ -94,7 +94,6 @@ export class ComponentTransformer extends AbstractVisitor { this.hasLegacy = false; this.legacyStructMap = new Map(); this.legacyCallMap = new Map(); - this.stateVarMap = new Map(); } enter(node: arkts.AstNode) { @@ -351,12 +350,10 @@ export class ComponentTransformer extends AbstractVisitor { arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); if (member.annotations.length > 0 && !hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { - const type = getStateManagementType(member); - this.stateVarMap.set(originalName, type); const newMember: arkts.ClassProperty = createOptionalClassProperty( newName, member, - type, + getStateManagementType(member), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); return [originMember, newMember]; @@ -387,7 +384,6 @@ export class ComponentTransformer extends AbstractVisitor { } } } - this.legacyCallMap.set('Child1', 'har1/src/main/ets/components/MainPage'); } visitor(node: arkts.AstNode): arkts.AstNode { @@ -420,12 +416,11 @@ export class ComponentTransformer extends AbstractVisitor { const context: InteropContext = { className: className, path: path, - stateVarMap: this.stateVarMap, arguments: args && args.length === 1 && args[0] instanceof arkts.ObjectExpression ? args[0] : undefined }; - return processStructCall(context); + return generateTempCallFunction(context); } } return newNode; diff --git a/arkui-plugins/ui-plugins/initstatevar.ts b/arkui-plugins/ui-plugins/initstatevar.ts new file mode 100644 index 000000000..3264db1a2 --- /dev/null +++ b/arkui-plugins/ui-plugins/initstatevar.ts @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +import * as arkts from '@koalaui/libarkts'; +import { InteroperAbilityNames } from '../common/predefines'; +import { annotation, backingField, isAnnotation } from '../common/arkts-utils'; +import { getPropertyESValue, getWrapValue, setPropertyESValue } from './interop'; + + +export function processNormal(keyName: string, value: arkts.AstNode): arkts.Statement[] { + const result: arkts.Statement[] = []; + const setProperty = setPropertyESValue( + InteroperAbilityNames.PARAM, + keyName, + getWrapValue(value) + ); + result.push(setProperty); + return result; +} + +export function createVariableLet(varName: string, expression: arkts.AstNode): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier(varName), + expression + )] + ); +} +export function setValueCallback(name: string, type: arkts.TypeNode, block: arkts.BlockStatement): arkts.AstNode { + return createVariableLet(name, + arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + block, + arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('value', type), + undefined, + ), + ], + undefined, + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ) + ); +} + +function createProxyBlock(varName: string): arkts.BlockStatement { + return arkts.factory.createBlock( + [ + arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(varName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + arkts.factory.createIdentifier('value') + ) + ) + ] + ); +} + +export function setCallbackForProxy(varName: string, type: arkts.TypeNode): arkts.Statement[] { + const createCallback = setValueCallback(addStatePrefix(varName, 'SetSource'), type, createProxyBlock(varName)); + const createProxyState = createVariableLet(addStatePrefix(varName, 'ProxyState'), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('createState'), + arkts.factory.createIdentifier('invoke'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + getWrapValue( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(varName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + ), + getWrapValue(arkts.factory.createIdentifier(addStatePrefix(varName, 'SetSource'))) + ] + ) + ); + const setProxy = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(backingField(varName)), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + ), + arkts.factory.createIdentifier('setProxy'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState'))], + ) + ); + return [createCallback, createProxyState, setProxy]; +} + +function createSourceBlock(varName: string): arkts.BlockStatement { + return arkts.factory.createBlock( + [ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')), + arkts.factory.createIdentifier('invokeMethod'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createStringLiteral('set'), + getWrapValue( + arkts.factory.createIdentifier('value') + ) + ] + ) + ) + ] + ); +} + +function createNotifyBlock(varName: string): arkts.BlockStatement { + return arkts.factory.createBlock( + [ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')), + arkts.factory.createIdentifier('invokeMethod'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createStringLiteral('notifyPropertyHasChangedPU') + ] + ) + ) + ] + ); +} + +function setNotifyForSource(varName: string): arkts.Statement[] { + const block = createNotifyBlock(varName); + const createCallback = createVariableLet(addStatePrefix(varName, 'NotifyCallback'), + arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + block, + arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('propertyName', + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('string') + ) + ) + ), + undefined, + ), + ], + undefined, + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ) + ); + const setCallback = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(backingField(varName)), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + ), + arkts.factory.createIdentifier('setNotifyCallback'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [arkts.factory.createIdentifier(addStatePrefix(varName, 'NotifyCallback'))], + ) + ); + return [createCallback, setCallback]; +} + +export function setCallbackForSource(varName: string, type: arkts.TypeNode): arkts.Statement[] { + const createCallback = setValueCallback(addStatePrefix(varName, 'SetProxy'), type, createSourceBlock(varName)); + const setFunc = arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(backingField(varName)), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + ), + arkts.factory.createIdentifier('setProxyValue'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + arkts.factory.createIdentifier(addStatePrefix(varName, 'SetProxy')) + ) + ); + const setNotify = setNotifyForSource(varName); + return [createCallback, setFunc, ...setNotify]; +} + +export function processLink(keyName: string, value: arkts.AstNode, type: arkts.TypeNode, proxySet: Set): arkts.Statement[] { + const varName = ((value as arkts.MemberExpression).property as arkts.Identifier).name; + const result: arkts.Statement[] = []; + if (!proxySet.has(varName)) { + proxySet.add(varName); + const setProxy = setCallbackForProxy(varName, type); + result.push(...setProxy); + const setSource = setCallbackForSource(varName, type); + result.push(...setSource); + } + const setParam = setPropertyESValue( + 'param', + keyName, + arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')) + ); + result.push(setParam); + return result; +} + +export function hasLink(decorators: string[]): boolean { + return decorators.some(decorator => decorator === 'Link'); +} + +function addStatePrefix(stateVarName: string, name: string): string { + return `${stateVarName}_${name}`; +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/interop.ts b/arkui-plugins/ui-plugins/interop.ts index c8293d7dd..d6c43d1c7 100644 --- a/arkui-plugins/ui-plugins/interop.ts +++ b/arkui-plugins/ui-plugins/interop.ts @@ -19,6 +19,13 @@ import * as arkts from '@koalaui/libarkts'; import { InteroperAbilityNames } from '../common/predefines'; import { getCustomComponentOptionsName } from './utils'; import { InteropContext } from './component-transformer'; +import { annotation, backingField, isAnnotation } from '../common/arkts-utils'; +import { hasLink, processLink, processNormal } from './initstatevar'; + +interface propertyInfo { + decorators: string[], + type: arkts.TypeNode, +} export function createEmptyESValue(name: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( @@ -44,18 +51,11 @@ export function createEmptyESValue(name: string): arkts.VariableDeclaration { ); } -export function getWrapValue(value: arkts.AstNode, type?: string): arkts.AstNode { - let wrapMethod = InteroperAbilityNames.WRAP; - if (!!type && value instanceof arkts.StringLiteral) { - wrapMethod = InteroperAbilityNames.WRAPSTRING; - } else if (!!type && value instanceof arkts.NumberLiteral) { - wrapMethod = InteroperAbilityNames.WRAPINT; - } - +export function getWrapValue(value: arkts.AstNode): arkts.AstNode { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(wrapMethod), + arkts.factory.createIdentifier(InteroperAbilityNames.WRAP), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -65,7 +65,7 @@ export function getWrapValue(value: arkts.AstNode, type?: string): arkts.AstNode ); } -export function setPropertyESValue(name: string, key: arkts.StringLiteral, wrapValue: arkts.AstNode): arkts.ExpressionStatement { +export function setPropertyESValue(name: string, key: string, wrapValue: arkts.AstNode): arkts.ExpressionStatement { return arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -77,7 +77,7 @@ export function setPropertyESValue(name: string, key: arkts.StringLiteral, wrapV ), undefined, [ - key, + arkts.factory.createStringLiteral(key), wrapValue ] ) @@ -108,28 +108,33 @@ export function getPropertyESValue(result: string, object: string, key: string): ); } -function initialArgs(name: string, context: InteropContext): arkts.Statement[] { - const args = context.arguments; - const stateVarMap = context.stateVarMap; - if (!args) { - return []; - } - const result: arkts.Statement[] = []; +function initialArgs(args: arkts.ObjectExpression, varMap: Map): arkts.Statement[] { + const result: arkts.Statement[] = [ + createEmptyESValue(InteroperAbilityNames.PARAM), + getPropertyESValue('createState', 'global', 'createStateVariable') + ]; + + const proxySet = new Set(); for (const property of args.properties) { if (!(property instanceof arkts.Property)) { continue; } const key = property.key; - if (!(key instanceof arkts.Identifier)){ + const value = property.value; + if (!(key instanceof arkts.Identifier)) { throw Error('Error arguments in Legacy Component'); } - const value = property.value!; - const type = stateVarMap.get(key.name); - const key_string = arkts.factory.createStringLiteral(key.name); - const wrapValue = getWrapValue(value, type); - const setProperty = setPropertyESValue(name, key_string, wrapValue); - result.push(setProperty); + const name = key.name; + const decorators = varMap.get(name)?.decorators; + const type = varMap.get(name)?.type!; + if (decorators !== undefined && hasLink(decorators)) { + const initParam = processLink(key.name, value!, type, proxySet); + result.push(...initParam); + } else { + const initParam = processNormal(key.name, value!); + result.push(...initParam); + } } return result; } @@ -225,10 +230,10 @@ function createExtraInfo(properties: string[], value: string[]): arkts.Statement const val = value[index]; body.push(setPropertyESValue( InteroperAbilityNames.EXTRAINFO, - arkts.factory.createStringLiteral(prop), + prop, arkts.factory.createStringLiteral(val)) ); - }) + }); return body; } @@ -284,7 +289,7 @@ function createESBlank(): arkts.Statement[] { ) ) ] - ) + ); body.push(blank); const asExpression = arkts.factory.createTSAsExpression( arkts.factory.createIdentifier('blank'), @@ -305,14 +310,13 @@ function createESBlank(): arkts.Statement[] { getWrapValue(asExpression) ) ] - ) + ); body.push(esblank); return body; } -function createELMTID(): arkts.Statement[] { - const body: arkts.Statement[] = []; - const global = arkts.factory.createVariableDeclaration( +function createGlobal(): arkts.Statement { + return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [arkts.factory.createVariableDeclarator( @@ -331,7 +335,10 @@ function createELMTID(): arkts.Statement[] { ) )] ); - body.push(global); +} + +function createELMTID(): arkts.Statement[] { + const body: arkts.Statement[] = []; const viewStackProcessor = getPropertyESValue('viewStackProcessor', 'global', 'ViewStackProcessor'); body.push(viewStackProcessor); const createId = getPropertyESValue('createId', 'viewStackProcessor', 'AllocateNewElmetIdForNextComponent'); @@ -394,12 +401,12 @@ function createComponent(moduleName: string, className: string): arkts.Statement arkts.factory.createIdentifier('esblank'), arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO) ] - ) + ); body.push(component); return body; } -function invokeViewPUCreate(): arkts.Statement[] { +function invokeViewPUCreate(): arkts.Statement[] { const body: arkts.Statement[] = []; const createMethod = getPropertyESValue('create', 'structObject', 'create'); body.push(createMethod); @@ -417,12 +424,12 @@ function invokeViewPUCreate(): arkts.Statement[] { arkts.factory.createIdentifier('component') ] ) - ) + ); body.push(viewPUCreate); return body; } -function createWrapperBlock(context: InteropContext): arkts.BlockStatement { +function createWrapperBlock(context: InteropContext, varMap: Map): arkts.BlockStatement { const className = context.className; const path = context.path; const args = context.arguments; @@ -431,13 +438,12 @@ function createWrapperBlock(context: InteropContext): arkts.BlockStatement { throw new Error('Error path of Legacy Component.'); } const moduleName = path.substring(0, index); - const initialArgsStatement = initialArgs(InteroperAbilityNames.PARAM, context); + const initialArgsStatement = args ? initialArgs(args, varMap) : []; return arkts.factory.createBlock( [ - createEmptyESValue(InteroperAbilityNames.PARAM), + createGlobal(), ...initialArgsStatement, ...createExtraInfo(['page'], [path]), - // createESParent(), createESUndefined(), ...createESBlank(), ...createELMTID(), @@ -446,7 +452,7 @@ function createWrapperBlock(context: InteropContext): arkts.BlockStatement { // ...paramsLambdaDeclaration(className, args), // setPropertyESValue( // 'component', - // arkts.factory.create1StringLiteral('paramsGenerator_'), + // 'paramsGenerator_', // arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA) // ), createInitReturn(className) @@ -454,24 +460,14 @@ function createWrapperBlock(context: InteropContext): arkts.BlockStatement { ); } -function createInitializer(context: InteropContext): arkts.ArrowFunctionExpression { - const block = createWrapperBlock(context); - const builderNode = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('BuilderNode') - ) - ) +function createInitializer(context: InteropContext, varMap: Map): arkts.ArrowFunctionExpression { + const block = createWrapperBlock(context, varMap); return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( block, arkts.factory.createFunctionSignature( undefined, - [ - // arkts.factory.createParameterDeclaration( - // arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, builderNode), - // undefined, - // ), - ], + [], undefined, false, ), @@ -481,7 +477,7 @@ function createInitializer(context: InteropContext): arkts.ArrowFunctionExpressi ); } -function createUpdater(number: arkts.ETSTypeReference, esvalue: arkts.ETSTypeReference): arkts.ArrowFunctionExpression { +function createUpdater(esvalue: arkts.ETSTypeReference, varMap: Map): arkts.ArrowFunctionExpression { return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( arkts.factory.createBlock( @@ -492,10 +488,6 @@ function createUpdater(number: arkts.ETSTypeReference, esvalue: arkts.ETSTypeRef arkts.factory.createFunctionSignature( undefined, [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, number), - undefined, - ), arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, esvalue), undefined, @@ -510,21 +502,54 @@ function createUpdater(number: arkts.ETSTypeReference, esvalue: arkts.ETSTypeRef ); } -export function processStructCall(context: InteropContext): arkts.CallExpression { - const number = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(InteroperAbilityNames.NUMBER) - ) - ); +function generateVarMap(node: arkts.Identifier): Map { + const decl = arkts.getDecl(node); + if (!(decl instanceof arkts.ClassDefinition)) { + throw Error("can't find legacy class declaration"); + } + const result = new Map(); + const definition = decl; + const body = definition.body; + body.forEach(node => { + if (node instanceof arkts.ClassProperty && node.key instanceof arkts.Identifier) { + const key = node.key.name; + const annotations = node.annotations; + const decorators: string[] = annotations.map(annotation => { + return (annotation.expr as arkts.Identifier).name; + }); + const type: arkts.TypeNode = node.typeAnnotation!; + result.set(key, {decorators: decorators, type: type}); + } + }); + return result; +} + +export function updateArkUICompatible(node: arkts.CallExpression): arkts.CallExpression { + const classInterop = (node.expression as arkts.MemberExpression).object as arkts.Identifier; + const className = classInterop.name; + const args = node.arguments; + const path = (args[0] as arkts.StringLiteral).str; + const line = args[1] instanceof arkts.UndefinedLiteral ? undefined : (args[1] as arkts.NumberLiteral).value; + const col = args[2] instanceof arkts.UndefinedLiteral ? undefined : (args[2] as arkts.NumberLiteral).value; + const options = args[3] instanceof arkts.UndefinedLiteral ? undefined : args[3] as arkts.ObjectExpression; + const context: InteropContext = { + className: className, + path: path, + line: line, + col: col, + arguments: options + }; + + const varMap: Map = generateVarMap(classInterop); const esvalue = arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) ) ); - const initializer = createInitializer(context); - // console.log('print intt:'+ initializer.dumpSrc()); - const updater = createUpdater(number, esvalue); - return arkts.factory.createCallExpression( + const initializer = createInitializer(context, varMap); + const updater = createUpdater(esvalue, varMap); + return arkts.factory.updateCallExpression( + node, arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), undefined, [ @@ -534,74 +559,37 @@ export function processStructCall(context: InteropContext): arkts.CallExpression ); } -export function updateStateVar(node: arkts.CallExpression): arkts.CallExpression { - const ident = node.expression; - if (!(ident instanceof arkts.Identifier)) { - return node; - } - const name = ident.name; - if (name !== 'ArkUICompatible') { - return node; - } - const init = node.arguments[0] as arkts.ArrowFunctionExpression; - const script = init.scriptFunction; - const body = script.body as arkts.BlockStatement; - const statements = body.statements; - const varStatement = statements[1].expression as arkts.CallExpression; - const params = varStatement.arguments; - const wrapVar = params[1] as arkts.CallExpression; - const stateVar = wrapVar.arguments[0] as arkts.MemberExpression; - const newStateVar = arkts.factory.updateMemberExpression( - stateVar, - stateVar.object, - arkts.factory.createIdentifier('__backing_' + stateVar.property.name), - stateVar.kind, - stateVar.computed, - stateVar.optional - ); - const newWrapVar = arkts.factory.updateCallExpression( - wrapVar, - wrapVar.expression, - wrapVar.typeArguments, - [newStateVar], - ); - const newVarStatement = arkts.factory.updateCallExpression( - varStatement, - varStatement.expression, - varStatement.typeArguments, - [params[0], newWrapVar] - ); - const newBody = arkts.factory.updateBlock( - body, - [ - statements[0], - newVarStatement, - ...statements.slice(2) - ] - ); - const newInit = arkts.factory.updateArrowFunction( - init, - arkts.factory.updateScriptFunction( - script, - newBody, - arkts.factory.createFunctionSignature( - script.typeParams, - script.params, - script.returnTypeAnnotation, - script.hasReceiver, - ), - script.flags, - script.modifiers - ) - ); - const newNode = arkts.factory.updateCallExpression( - node, - node.expression, - node.typeArguments, - [ - newInit, - node.arguments[1] - ], + +function generateStructInfo(context: InteropContext): arkts.AstNode[] { + const result: arkts.AstNode[] = [ + arkts.factory.createStringLiteral(context.path), + context.line ? arkts.factory.createIdentifier(context.line.toString()) : arkts.factory.createUndefinedLiteral(), + context.col ? arkts.factory.createIdentifier(context.col.toString()) : arkts.factory.createUndefinedLiteral(), + context.arguments ?? arkts.factory.createUndefinedLiteral() + ]; + return result; + +} + +export function generateTempCallFunction(context: InteropContext): arkts.CallExpression { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(context.className), + arkts.factory.createIdentifier('instantiate_Interop'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + generateStructInfo(context) ); - return newNode; +} + +export function isArkUICompatible(node: arkts.AstNode): boolean { + if (node instanceof arkts.CallExpression && node.expression instanceof arkts.MemberExpression && + node.expression.property instanceof arkts.Identifier && + node.expression.property.name === 'instantiate_Interop') { + return true; + } + return false; } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/legacy-transformer.ts b/arkui-plugins/ui-plugins/legacy-transformer.ts index c23c888b2..8196f89a2 100644 --- a/arkui-plugins/ui-plugins/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/legacy-transformer.ts @@ -14,8 +14,12 @@ */ import * as arkts from '@koalaui/libarkts'; +import { getInteropPath } from '../path'; +const interop = require(getInteropPath()); +const nullptr = interop.nullptr; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { InteroperAbilityNames } from '../common/predefines'; +import { getCustomComponentOptionsName } from './utils'; interface LegacyTransformerOptions extends VisitorOptions { structList?: string[] @@ -23,6 +27,7 @@ interface LegacyTransformerOptions extends VisitorOptions { export class LegacyTransformer extends AbstractVisitor { private structList: string[] = []; + private componentInterfaceCollection: arkts.TSInterfaceDeclaration[] = []; constructor(options?: LegacyTransformerOptions) { const _options: LegacyTransformerOptions = options ?? {}; @@ -30,10 +35,91 @@ export class LegacyTransformer extends AbstractVisitor { this.structList = _options.structList ?? []; } + reset(): void { + super.reset(); + this.componentInterfaceCollection = []; + } + getList(): string[] { return this.structList; } + createParam(name: string, type: string): arkts.ETSParameterExpression { + return arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + name, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(type) + ) + ) + ), + undefined + ); + } + + createInteropMethod(name: string): arkts.MethodDefinition { + const path = this.createParam('path', 'string'); + const line = this.createParam('line', 'number'); + line.setOptional(true); + const col = this.createParam('col', 'number'); + col.setOptional(true); + const options = this.createParam('options', getCustomComponentOptionsName(name)); + options.setOptional(true); + + const script = arkts.factory.createScriptFunction( + arkts.factory.createBlock([]), + arkts.FunctionSignature.createFunctionSignature( + undefined, + [path, line, col, options], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC + ); + + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + arkts.factory.createIdentifier('instantiate_Interop'), + arkts.factory.createFunctionExpression(script), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + false + ); + } + + generateMember(map: Map): arkts.ClassProperty[] { + const properties: arkts.ClassProperty[] = []; + + map.forEach((value, key) => { + const property = arkts.factory.createClassProperty( + arkts.factory.createIdentifier(key), + undefined, + value, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL, + false + ); + + properties.push(property); + }); + + return properties; + } + + generateComponentInterface(name: string, modifiers: number, map: Map): arkts.TSInterfaceDeclaration { + const interfaceNode = arkts.factory.createInterfaceDeclaration( + [], + arkts.factory.createIdentifier(getCustomComponentOptionsName(name)), + nullptr, // TODO: wtf + arkts.factory.createInterfaceBody([...(this.generateMember(map) || [])]), + false, + false + ); + interfaceNode.modifiers = modifiers; + return interfaceNode; + } + processComponent(node: arkts.StructDeclaration): arkts.StructDeclaration | arkts.ClassDeclaration { const definition: arkts.ClassDefinition = node.definition!; const ident = definition.ident!; @@ -43,6 +129,9 @@ export class LegacyTransformer extends AbstractVisitor { if (hasExportFlag) { this.structList.push(ident.name); } + + const instantiate_Interop: arkts.MethodDefinition = this.createInteropMethod(ident.name); + const newDefinition = arkts.factory.updateClassDefinition( definition, definition.ident, @@ -51,11 +140,14 @@ export class LegacyTransformer extends AbstractVisitor { definition.implements, undefined, definition.super, - [...definition.body], + [...definition.body, instantiate_Interop], definition.modifiers, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE ); + console.log('print legacyclass definition' + newDefinition.dumpSrc()); + + //TODO: need check if (arkts.isStructDeclaration(node)) { const _node = arkts.factory.createClassDeclaration(newDefinition); @@ -115,9 +207,38 @@ export class LegacyTransformer extends AbstractVisitor { ); } + collectComponentMembers(node: arkts.StructDeclaration, className: string): Map { + const result: Map = new Map(); + node.definition.body.map((it) => { + if (arkts.isClassProperty(it)) { + const name = (it.key as arkts.Identifier).name; + const type = it.typeAnnotation!; + result.set(name, type); + } + }); + return result; + } + + processEtsScript(node: arkts.EtsScript): arkts.EtsScript { + let updateStatements: arkts.AstNode[] = []; + if (this.componentInterfaceCollection.length > 0) { + updateStatements.push(...this.componentInterfaceCollection); + } + if (updateStatements.length > 0) { + return arkts.factory.updateEtsScript(node, [...node.statements, ...updateStatements]); + } + return node; + } + visitor(node: arkts.AstNode): arkts.AstNode { const newNode = this.visitEachChild(node); + if (arkts.isEtsScript(newNode)) { + return this.processEtsScript(newNode); + } if (arkts.isStructDeclaration(newNode)) { + const className = node.definition?.ident?.name; + const memberMap = this.collectComponentMembers(node as arkts.StructDeclaration, className); + this.componentInterfaceCollection.push(this.generateComponentInterface(className, node.modifiers, memberMap)); const updateNode = this.processComponent(newNode); return updateNode; } -- Gitee From abdcc92b217c86331e20555ec59287efb0839b90 Mon Sep 17 00:00:00 2001 From: zenghang Date: Sun, 25 May 2025 19:25:36 +0800 Subject: [PATCH 100/123] provide fileManager for interop Issue: IC99RE Signed-off-by: zenghang Change-Id: Ib3061b73526cca24d5dd00fae4be0974cddd47b0 --- compiler/src/ets_checker.ts | 8 +- .../ark_compiler/interop/interop_manager.ts | 262 ++++++++++++++++++ .../fast_build/ark_compiler/interop/type.ts | 69 +++++ .../ets_ui/rollup-plugin-ets-checker.ts | 8 + .../interop/interop_manager.test.ts | 196 +++++++++++++ 5 files changed, 542 insertions(+), 1 deletion(-) create mode 100644 compiler/src/fast_build/ark_compiler/interop/interop_manager.ts create mode 100644 compiler/src/fast_build/ark_compiler/interop/type.ts create mode 100644 compiler/test/ark_compiler_ut/interop/interop_manager.test.ts diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index e533e46d2..1ec5ea72b 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -113,6 +113,8 @@ import { getArkTSEvoDeclFilePath } from './process_arkts_evolution'; import { processInteropUI } from './process_interop_ui'; +import { FileManager } from './fast_build/ark_compiler/interop/interop_manager'; +import { ARKTS_1_2 } from './pre_define'; export interface LanguageServiceCache { service?: ts.LanguageService; @@ -381,7 +383,11 @@ export function createLanguageService(rootFileNames: string[], resolveModulePath // TSC will re-do resolution if this callback return true. hasInvalidatedResolutions: (filePath: string): boolean => { return reuseLanguageServiceForDepChange && needReCheckForChangedDepUsers; - } + }, + isStaticSourceFile: (fileName: string): boolean => { + const languageVersion = FileManager.getInstance().getLanguageVersionByFilePath(fileName); + return languageVersion?.languageVersion === ARKTS_1_2; + }, }; if (process.env.watchMode === 'true') { diff --git a/compiler/src/fast_build/ark_compiler/interop/interop_manager.ts b/compiler/src/fast_build/ark_compiler/interop/interop_manager.ts new file mode 100644 index 000000000..3ea51946e --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/interop/interop_manager.ts @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import * as ts from 'typescript'; + +import { sdkConfigs } from '../../../../main'; +import { toUnixPath } from '../../../utils'; +import { + ARKTS_1_1, + ArkTSEvolutionModule, + ARKTS_1_2, + HYBRID, + FileInfo +} from './type'; + +export class FileManager { + private static instance: FileManager | undefined = undefined; + + static arkTSModuleMap: Map = new Map(); + static dynamicLibPath: Set = new Set(); + static staticSDKDeclPath: Set = new Set(); + static staticSDKGlueCodePath: Set = new Set(); + static mixCompile: boolean = false; + static glueCodeFileInfos: Map = new Map(); + + private constructor() { } + + public static init( + dependentModuleMap: Map, + dynamicSDKPath?: Set, + staticSDKDeclPath?: Set, + staticSDKGlueCodePath?: Set + ): void { + if (FileManager.instance === undefined) { + FileManager.instance = new FileManager(); + FileManager.initLanguageVersionFromDependentModuleMap(dependentModuleMap); + FileManager.initSDK(dynamicSDKPath, staticSDKDeclPath, staticSDKGlueCodePath); + } + } + + public static getInstance(): FileManager { + if (!FileManager.instance) { + FileManager.instance = new FileManager(); + } + return FileManager.instance; + } + + private static initLanguageVersionFromDependentModuleMap( + dependentModuleMap: Map + ): void { + const convertedMap = new Map(); + + for (const [key, module] of dependentModuleMap) { + const convertedModule: ArkTSEvolutionModule = { + ...module, + modulePath: toUnixPath(module.modulePath), + declgenV1OutPath: module.declgenV1OutPath ? toUnixPath(module.declgenV1OutPath) : undefined, + declgenV2OutPath: module.declgenV2OutPath ? toUnixPath(module.declgenV2OutPath) : undefined, + declgenBridgeCodePath: module.declgenBridgeCodePath ? toUnixPath(module.declgenBridgeCodePath) : undefined, + declFilesPath: module.declFilesPath ? toUnixPath(module.declFilesPath) : undefined, + }; + convertedMap.set(key, convertedModule); + } + + this.arkTSModuleMap = convertedMap; + } + + private static initSDK( + dynamicSDKPath?: Set, + staticSDKBaseUrl?: Set, + staticSDKGlueCodePaths?: Set + ): void { + if (dynamicSDKPath) { + for (const path of dynamicSDKPath) { + FileManager.dynamicLibPath.add(toUnixPath(path)); + } + } + if (staticSDKBaseUrl) { + for (const path of staticSDKBaseUrl) { + FileManager.staticSDKDeclPath.add(toUnixPath(path)); + } + } + if (staticSDKGlueCodePaths) { + for (const path of staticSDKGlueCodePaths) { + FileManager.staticSDKGlueCodePath.add(toUnixPath(path)); + } + } + } + + public static cleanFileManagerObject(): void { + if (this.instance) { + this.instance = undefined; + } + + FileManager.arkTSModuleMap.clear(); + FileManager.dynamicLibPath.clear(); + FileManager.staticSDKDeclPath.clear(); + FileManager.staticSDKGlueCodePath.clear(); + FileManager.glueCodeFileInfos.clear(); + FileManager.mixCompile = false; + } + + getLanguageVersionByFilePath(filePath: string): { + languageVersion: string, + pkgName: string + } | undefined { + const path = toUnixPath(filePath); + + const moduleMatch = FileManager.matchModulePath(path); + if (moduleMatch) { + return moduleMatch; + } + + const sdkMatch = FileManager.matchSDKPath(path); + if (sdkMatch) { + return sdkMatch; + } + + return undefined; + } + + private static matchModulePath(path: string): { + languageVersion: string, + pkgName: string + } | undefined { + for (const [_, moduleInfo] of FileManager.arkTSModuleMap) { + if (!path.startsWith(moduleInfo.modulePath)) { + continue; + } + + const isHybrid = moduleInfo.language === HYBRID; + const pkgName = moduleInfo.packageName; + + if (!isHybrid) { + return { + languageVersion: moduleInfo.language, + pkgName + }; + } + + const isDynamic = + moduleInfo.dynamicFiles.includes(path) || + (moduleInfo.declgenV2OutPath && path.startsWith(moduleInfo.declgenV2OutPath)); + + if (isDynamic) { + return { + languageVersion: ARKTS_1_1, + pkgName + }; + } + + const isStatic = + moduleInfo.staticFiles.includes(path) || + (moduleInfo.declgenV1OutPath && path.startsWith(moduleInfo.declgenV1OutPath)) || + (moduleInfo.declgenBridgeCodePath && path.startsWith(moduleInfo.declgenBridgeCodePath)); + + if (isStatic) { + return { + languageVersion: ARKTS_1_2, + pkgName + }; + } + } + + return undefined; + } + + private static matchSDKPath(path: string): { + languageVersion: string, + pkgName: string + } | undefined { + const sdkMatches: [Set | undefined, string][] = [ + [FileManager.dynamicLibPath, ARKTS_1_1], + [FileManager.staticSDKDeclPath, ARKTS_1_2], + [FileManager.staticSDKGlueCodePath, ARKTS_1_2], + ]; + + for (const [paths, version] of sdkMatches) { + const isMatch = paths && Array.from(paths).some( + p => p && (path.startsWith(p + '/') || path === p) + ); + if (isMatch) { + return { languageVersion: version, pkgName: 'SDK' }; + } + } + return undefined; + } +} + +export function initFileManagerInRollup(share: Object): void { + if (!share.projectConfig.mixCompile) { + return; + } + + FileManager.mixCompile = true; + const sdkInfo = collectSDKInfo(share); + + FileManager.init( + share.projectConfig.dependentModuleMap, + sdkInfo.dynamicSDKPath, + sdkInfo.staticSDKInteropDecl, + sdkInfo.staticSDKGlueCodePath + ); +} + +function collectSDKInfo(share: Object): { + dynamicSDKPath: Set, + staticSDKInteropDecl: Set, + staticSDKGlueCodePath: Set +} { + const dynamicSDKPath: Set = new Set(); + + const staticSDKInteropDecl: Set = new Set([ + path.resolve(share.projectConfig.etsLoaderPath, '../../../ets1.2interop/declarations/kit'), + path.resolve(share.projectConfig.etsLoaderPath, '../../../ets1.2interop/declarations/api'), + path.resolve(share.projectConfig.etsLoaderPath, '../../../ets1.2interop/declarations/arkts'), + ].map(toUnixPath)); + + const staticSDKGlueCodePath: Set = new Set([ + path.resolve(share.projectConfig.etsLoaderPath, '../../../ets1.2interop/bridge/kit'), + path.resolve(share.projectConfig.etsLoaderPath, '../../../ets1.2interop/bridge/api'), + path.resolve(share.projectConfig.etsLoaderPath, '../../../ets1.2interop/bridge/arkts'), + ].map(toUnixPath)); + + const declarationsPath: string = path.resolve(share.projectConfig.etsLoaderPath, './declarations').replace(/\\/g, '/'); + const componentPath: string = path.resolve(share.projectConfig.etsLoaderPath, './components').replace(/\\/g, '/'); + const etsComponentPath: string = path.resolve(share.projectConfig.etsLoaderPath, '../../component').replace(/\\/g, '/'); + + if (process.env.externalApiPaths) { + const externalApiPaths = path.resolve(process.env.externalApiPaths, '../'); + staticSDKGlueCodePath.add(path.resolve(externalApiPaths, 'ets1.2interop/bridge')); + staticSDKInteropDecl.add(path.resolve(externalApiPaths, 'ets1.2interop/declarations')); + } + + dynamicSDKPath.add(declarationsPath); + dynamicSDKPath.add(componentPath); + dynamicSDKPath.add(etsComponentPath); + sdkConfigs.forEach(({ apiPath }) => { + apiPath.forEach(path => { + dynamicSDKPath.add(toUnixPath(path)); + }); + }); + return { + dynamicSDKPath: dynamicSDKPath, + staticSDKInteropDecl: staticSDKInteropDecl, + staticSDKGlueCodePath: staticSDKGlueCodePath + }; +} \ No newline at end of file diff --git a/compiler/src/fast_build/ark_compiler/interop/type.ts b/compiler/src/fast_build/ark_compiler/interop/type.ts new file mode 100644 index 000000000..66deaf308 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/interop/type.ts @@ -0,0 +1,69 @@ +/* + * 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. + */ + +export interface ArkTSEvolutionModule { + language: string; + packageName: string; + moduleName: string; + modulePath: string; + declgenV1OutPath?: string; + declgenV2OutPath?: string; + declgenBridgeCodePath?: string; + declFilesPath?: string; + dynamicFiles: string[]; + staticFiles: string[]; + cachePath: string; + byteCodeHarInfo?: Object; +} + +export const ARKTS_1_2: string = '1.2'; +export const ARKTS_1_1: string = '1.1'; +export const ARKTS_1_0: string = '1.0'; +export const HYBRID: string = 'hybrid'; + +export interface Params { + dependentModuleMap: Map; + projectConfig: ProjectConfig; + tasks: taskInfo[]; +} + +interface ProjectConfig { + cachePath: string; + bundleName: string; + mainModuleName: string; + projectRootPath: string; +}; + +enum BuildType { + DECLGEN = 'declgen', + BYTE_CODE_HAR = 'byteCodeHar', + INTEROP_CONTEXT = 'interopContext' +} + +interface taskInfo { + packageName: string; + buildTask: BuildType; +} + +export interface AliasConfig { + originalAPIName: string; + isStatic: boolean; +} + +export interface FileInfo { + recordName: string; + baseUrl: string; + absolutePath: string; +} \ No newline at end of file diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts index 4cf4bc9c5..89cd4cd54 100644 --- a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts @@ -48,6 +48,10 @@ import { MemoryDefine } from '../meomry_monitor/memory_define'; import { LINTER_SUBSYSTEM_CODE } from '../../hvigor_error_code/hvigor_error_info'; import { ErrorCodeModule } from '../../hvigor_error_code/const/error_code_module'; import { collectArkTSEvolutionModuleInfo } from '../../process_arkts_evolution'; +import { + initFileManagerInRollup, + FileManager +} from '../ark_compiler/interop/interop_manager'; export let tsWatchEmitter: EventEmitter | undefined = undefined; export let tsWatchEndPromise: Promise; @@ -61,6 +65,7 @@ export function etsChecker() { if (this.share.projectConfig.dependentModuleMap) { collectArkTSEvolutionModuleInfo(this.share); } + initFileManagerInRollup(this.share); const compilationTime: CompilationTimeStatistics = new CompilationTimeStatistics(this.share, 'etsChecker', 'buildStart'); if (process.env.watchMode === 'true' && process.env.triggerTsWatch === 'true') { tsWatchEmitter = new EventEmitter(); @@ -145,6 +150,9 @@ export function etsChecker() { // The generated js file might be different in some cases when we change the targetESVersion, // so we need to regenerate them all when targetESVersion is changed. return targetESVersionChanged; + }, + cleanUp(): void { + FileManager.cleanFileManagerObject(); } }; } diff --git a/compiler/test/ark_compiler_ut/interop/interop_manager.test.ts b/compiler/test/ark_compiler_ut/interop/interop_manager.test.ts new file mode 100644 index 000000000..dd961e254 --- /dev/null +++ b/compiler/test/ark_compiler_ut/interop/interop_manager.test.ts @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use rollupObject file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { expect } from 'chai'; +import mocha from 'mocha'; +import { FileManager } from '../../../lib/fast_build/ark_compiler/interop/interop_manager'; +import { ARKTS_1_1, ARKTS_1_2, HYBRID } from '../../../lib/fast_build/ark_compiler/interop/type'; + +export interface ArkTSEvolutionModule { + language: string; + packageName: string; + moduleName: string; + modulePath: string; + declgenV1OutPath?: string; + declgenV2OutPath?: string; + declgenBridgeCodePath?: string; + declFilesPath?: string; + dynamicFiles: string[]; + staticFiles: string[]; + cachePath: string; + byteCodeHarInfo?: Object; +} + +mocha.describe('test interop_manager file api', function () { + mocha.before(function () { + const dependentModuleMap: Map = new Map(); + const dynamicSDKPath: Set = new Set([ + '/sdk/default/openharmony/ets/ets1.1/api', + '/sdk/default/openharmony/ets/ets1.1/arkts', + '/sdk/default/openharmony/ets/ets1.1/kits', + '/sdk/default/openharmony/ets/ets1.1/build-tools/ets-loader/declarations', + '/sdk/default/openharmony/ets/ets1.1/build-tools/ets-loader/component', + '/sdk/default/openharmony/ets/ets1.1/build-tools/components' + ]); + const staticSDKDeclPath: Set = new Set([ + '/sdk/default/openharmony/ets/ets1.2interop/declarations/kit', + '/sdk/default/openharmony/ets/ets1.2interop/declarations/api', + '/sdk/default/openharmony/ets/ets1.2interop/declarations/arkts' + ]); + const staticSDKGlueCodePath: Set = new Set([ + '/sdk/default/openharmony/ets/ets1.2interop/bridge/kit', + '/sdk/default/openharmony/ets/ets1.2interop/bridge/api', + '/sdk/default/openharmony/ets/ets1.2interop/bridge/arkts' + ]); + dependentModuleMap.set('application', { + language: ARKTS_1_1, + packageName: 'application', + moduleName: 'application', + modulePath: '/MyApplication16/application', + declgenV1OutPath: '/MyApplication16/application/build/default/intermediates/declgen/default/declgenV1', + declgenV2OutPath: '/MyApplication16/application/build/default/intermediates/declgen/default/declgenV2', + declgenBridgeCodePath: '/MyApplication16/application/build/default/intermediates/declgen/default/declgenBridgeCode', + declFilesPath: '/MyApplication16/application/build/default/intermediates/declgen/default/decl-fileInfo.json', + dynamicFiles: [], + staticFiles: [], + cachePath: '/MyApplication16/application/build/cache', + byteCodeHarInfo: {} + }); + + dependentModuleMap.set('harv2', { + language: ARKTS_1_2, + packageName: 'harv2', + moduleName: 'harv2', + modulePath: '/MyApplication16/harv2', + declgenV1OutPath: '/MyApplication16/harv2/build/default/intermediates/declgen/default/declgenV1', + declgenV2OutPath: '/MyApplication16/harv2/build/default/intermediates/declgen/default/declgenV2', + declgenBridgeCodePath: '/MyApplication16/harv2/build/default/intermediates/declgen/default/declgenBridgeCode', + declFilesPath: '/MyApplication16/harv2/build/default/intermediates/declgen/default/decl-fileInfo.json', + dynamicFiles: [], + staticFiles: [], + cachePath: '/MyApplication16/harv2/build/cache', + byteCodeHarInfo: {} + }); + + dependentModuleMap.set('dynamic1', { + language: ARKTS_1_1, + packageName: 'dynamic1', + moduleName: 'dynamic1', + modulePath: '/MyApplication16/dynamic1', + declgenV1OutPath: '/MyApplication16/dynamic1/build/default/intermediates/declgen/default/declgenV1', + declgenV2OutPath: '/MyApplication16/dynamic1/build/default/intermediates/declgen/default/declgenV2', + declgenBridgeCodePath: '/MyApplication16/dynamic1/build/default/intermediates/declgen/default/declgenBridgeCode', + declFilesPath: '/MyApplication16/dynamic1/build/default/intermediates/declgen/default/decl-fileInfo.json', + dynamicFiles: [], + staticFiles: [], + cachePath: '/MyApplication16/dynamic1/build/cache', + byteCodeHarInfo: {} + }); + + dependentModuleMap.set('hybrid', { + language: HYBRID, + packageName: 'hybrid', + moduleName: 'hybrid', + modulePath: '/MyApplication16/hybrid', + declgenV1OutPath: '/MyApplication16/hybrid/build/default/intermediates/declgen/default/declgenV1', + declgenV2OutPath: '/MyApplication16/hybrid/build/default/intermediates/declgen/default/declgenV2', + declgenBridgeCodePath: '/MyApplication16/hybrid/build/default/intermediates/declgen/default/declgenBridgeCode', + declFilesPath: '/MyApplication16/hybrid/build/default/intermediates/declgen/default/decl-fileInfo.json', + dynamicFiles: ['/MyApplication16/hybrid/fileV1.ets'], + staticFiles: ['/MyApplication16/hybrid/fileV2.ets'], + cachePath: '/MyApplication16/hybrid/build/cache', + byteCodeHarInfo: {} + }); + FileManager.cleanFileManagerObject(); + FileManager.init( + dependentModuleMap, + dynamicSDKPath, + staticSDKDeclPath, + staticSDKGlueCodePath); + }); + + mocha.after(() => { + }); + + mocha.it('1-1: test SDK path', function() { + const filePath = '/sdk/default/openharmony/ets/ets1.1/api/TestAPI.ets'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_1); + expect(result?.pkgName).to.equal('SDK'); + }); + + mocha.it('1-2: test ets-loader/declarations path', function() { + const filePath = '/sdk/default/openharmony/ets/ets1.1/build-tools/ets-loader/declarations/TestAPI.ets'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_1); + expect(result?.pkgName).to.equal('SDK'); + }); + + mocha.it('1-3: test ets-loader/component path', function() { + const filePath = '/sdk/default/openharmony/ets/ets1.1/build-tools/ets-loader/component/TestAPI.d.ts'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_1); + expect(result?.pkgName).to.equal('SDK'); + }); + + mocha.it('1-4: test SDK glue code path', function() { + const filePath = '/sdk/default/openharmony/ets/ets1.2interop/bridge/arkts/TestAPI.d.ts'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_2); + expect(result?.pkgName).to.equal('SDK'); + }); + + mocha.it('1-5: test SDK interop decl path', function() { + const filePath = '/sdk/default/openharmony/ets/ets1.2interop/declarations/kit/TestAPI.d.ts'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_2); + expect(result?.pkgName).to.equal('SDK'); + }); + + mocha.it('1-6: test source code from 1.1 module', function() { + const filePath = '/MyApplication16/application/sourceCode.ets'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_1); + expect(result?.pkgName).to.equal('application'); + }); + + mocha.it('1-7: test glue code file from 1.2 module', function() { + const filePath = '/MyApplication16/harv2/build/default/intermediates/declgen/default/declgenBridgeCode/sourceCode.ets'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_2); + expect(result?.pkgName).to.equal('harv2'); + }); + + mocha.it('1-8: test decl file from 1.2 module', function() { + const filePath = '/MyApplication16/harv2/build/default/intermediates/declgen/default/declgenV1/sourceCode.ets'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_2); + expect(result?.pkgName).to.equal('harv2'); + }); + + mocha.it('1-8: test source code file from hybrid module', function() { + const filePath = '/MyApplication16/hybrid/fileV1.ets'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_1); + expect(result?.pkgName).to.equal('hybrid'); + }); + + mocha.it('1-8: test source code file from hybrid module', function() { + const filePath = '/MyApplication16/hybrid/build/default/intermediates/declgen/default/declgenV1/file1'; + const result = FileManager.getInstance().getLanguageVersionByFilePath(filePath); + expect(result?.languageVersion).to.equal(ARKTS_1_2); + expect(result?.pkgName).to.equal('hybrid'); + }); +}); \ No newline at end of file -- Gitee From c93cdd89a2f399e0abee005cd6e77832f81b839c Mon Sep 17 00:00:00 2001 From: wangweiyuan Date: Thu, 22 May 2025 20:18:03 +0800 Subject: [PATCH 101/123] add log Signed-off-by: wangweiyuan --- .../ui-syntax-plugins/processor/index.ts | 33 ++++++- .../ui-syntax-plugins/rules/ui-syntax-rule.ts | 4 +- .../ui-syntax-plugins/utils/index.ts | 67 +++++++++++++- koala-wrapper/native/src/bridges.cc | 92 +++++++++++++++++++ koala-wrapper/src/Es2pandaNativeModule.ts | 24 ++++- koala-wrapper/src/arkts-api/index.ts | 4 + .../src/arkts-api/peers/Diagnostic.ts | 39 ++++++++ .../src/arkts-api/peers/DiagnosticInfo.ts | 33 +++++++ .../src/arkts-api/peers/DiagnosticKind.ts | 35 +++++++ .../src/arkts-api/peers/SuggestionInfo.ts | 33 +++++++ 10 files changed, 354 insertions(+), 10 deletions(-) create mode 100644 koala-wrapper/src/arkts-api/peers/Diagnostic.ts create mode 100644 koala-wrapper/src/arkts-api/peers/DiagnosticInfo.ts create mode 100644 koala-wrapper/src/arkts-api/peers/DiagnosticKind.ts create mode 100644 koala-wrapper/src/arkts-api/peers/SuggestionInfo.ts diff --git a/arkui-plugins/ui-syntax-plugins/processor/index.ts b/arkui-plugins/ui-syntax-plugins/processor/index.ts index 0a447759e..6fdebeac5 100644 --- a/arkui-plugins/ui-syntax-plugins/processor/index.ts +++ b/arkui-plugins/ui-syntax-plugins/processor/index.ts @@ -15,16 +15,25 @@ import * as arkts from '@koalaui/libarkts'; import { UISyntaxRule, UISyntaxRuleContext } from '../rules/ui-syntax-rule'; -import { getContainerComponents } from '../utils'; +import { getUIComponents } from '../utils'; export type UISyntaxRuleProcessor = { parsed(node: arkts.AstNode): void; }; +export interface UISyntaxRuleComponents { + builtInAttributes: string[]; + containerComponents: string[]; + atomicComponents: string[]; + singleChildComponents: string[]; + validParentComponent: Map; + validChildComponent: Map; +} + export function createUISyntaxRuleProcessor( rules: UISyntaxRule[], ): UISyntaxRuleProcessor { - const containerComponents = getContainerComponents('../../components/'); + const componentsInfo: UISyntaxRuleComponents = getUIComponents('../../components/'); const context: UISyntaxRuleContext = { report(options) { const position = arkts.getStartPosition(options.node); @@ -39,17 +48,33 @@ export function createUISyntaxRuleProcessor( options.message, ); } + + let args: string[] = []; + const kind: arkts.DiagnosticKind = + arkts.DiagnosticKind.create(message, arkts.PluginDiagnosticType.ES2PANDA_PLUGIN_ERROR); + if (options.fix) { + const diagnosticInfo: arkts.DiagnosticInfo = arkts.DiagnosticInfo.create(kind, ...args); + const suggestionInfo: arkts.SuggestionInfo = + arkts.SuggestionInfo.create(kind, options.fix(options.node).code, ...args); + const startPosition = arkts.getStartPosition(options.node); + const endPosition = arkts.getEndPosition(options.node); + const sourceRange: arkts.SourceRange = arkts.SourceRange.create(startPosition, endPosition); + arkts.Diagnostic.logDiagnosticWithSuggestion(diagnosticInfo, suggestionInfo, sourceRange); + } else { + arkts.Diagnostic.logDiagnostic(kind, arkts.getStartPosition(options.node)); + } + // todo if (options.fix) { const suggestion = options.fix(options.node); - console.log(`error: ${message}`); + console.log(`syntax-error: ${message}`); console.log(`range: (${suggestion.range[0].index()}, ${suggestion.range[0].line()}) - (${suggestion.range[1].index()}, ${suggestion.range[1].line()})`, `code: ${suggestion.code}`); } else { console.log(`syntax-error: ${message} (${position.index()},${position.line()})`); } }, - containerComponents: containerComponents, + componentsInfo: componentsInfo }; const instances = rules.map((rule) => rule.setup(context)); diff --git a/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts b/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts index c71a7c298..f0096765c 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts @@ -14,6 +14,7 @@ */ import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRuleComponents } from 'ui-syntax-plugins/processor'; export type FixSuggestion = { range: [start: arkts.SourcePosition, end: arkts.SourcePosition]; @@ -29,7 +30,8 @@ export type ReportOptions = { export type UISyntaxRuleContext = { report(options: ReportOptions): void; - containerComponents?: Set | undefined; + configOfComponent?: Set | undefined; + componentsInfo: UISyntaxRuleComponents; }; export type UISyntaxRuleHandler = (node: arkts.AstNode) => void; diff --git a/arkui-plugins/ui-syntax-plugins/utils/index.ts b/arkui-plugins/ui-syntax-plugins/utils/index.ts index 87ba336a7..6e025ba13 100644 --- a/arkui-plugins/ui-syntax-plugins/utils/index.ts +++ b/arkui-plugins/ui-syntax-plugins/utils/index.ts @@ -16,6 +16,8 @@ import * as arkts from '@koalaui/libarkts'; import * as fs from 'fs'; import * as path from 'path'; +import { UISyntaxRuleComponents } from 'ui-syntax-plugins/processor'; +import { UISyntaxRuleContext } from 'ui-syntax-plugins/rules/ui-syntax-rule'; export const PresetDecorators = { BUILDER_PARAM: 'BuilderParam', @@ -174,11 +176,19 @@ interface ComponentJson { name: string; atomic?: boolean; attrs: string[]; + single?: boolean; + parents?: string[]; + children?: string[]; } -export function getContainerComponents(dirPath: string): Set { - const resultSet = new Set(); +export function getUIComponents(dirPath: string): UISyntaxRuleComponents { const absolutePath = path.resolve(__dirname, dirPath); + let builtInAttributes: string[] = []; + let containerComponents: string[] = []; + let atomicComponents: string[] = []; + let singleChildComponents: string[] = []; + let validParentComponent: Map = new Map(); + let validChildComponent: Map = new Map(); if (!fs.existsSync(absolutePath)) { throw new Error(`Directory does not exist: ${absolutePath}`); @@ -191,10 +201,59 @@ export function getContainerComponents(dirPath: string): Set { const filePath = path.join(absolutePath, file); const fileContent = fs.readFileSync(filePath, 'utf-8'); const componentJson: ComponentJson = JSON.parse(fileContent); + // Record the container component name if ((!componentJson.atomic || componentJson.atomic !== true) && (componentJson.name)) { - resultSet.add(componentJson.name); + containerComponents.push(componentJson.name); } + // Record the atomic component name + if (componentJson.atomic && componentJson.atomic === true && componentJson.name) { + atomicComponents.push(componentJson.name); + } + // Record the name of a single subcomponent component name + if (componentJson.single && componentJson.single === true && componentJson.name) { + singleChildComponents.push(componentJson.name); + } + // Record a valid parent component name + if (componentJson.parents && componentJson.name) { + validParentComponent.set(componentJson.name, componentJson.parents); + } + // Record a valid children component name + if (componentJson.children && componentJson.name) { + validChildComponent.set(componentJson.name, componentJson.children); + } + // Document all built-in attributes + componentJson.attrs?.filter(attr => !builtInAttributes.includes(attr)) + .forEach(attr => builtInAttributes.push(attr)); } }); - return resultSet; + const componentsInfo: UISyntaxRuleComponents = { + builtInAttributes, + containerComponents, + atomicComponents, + singleChildComponents, + validParentComponent, + validChildComponent, + }; + + return componentsInfo; +} + +export function isBuiltInAttribute(context: UISyntaxRuleContext, attributeName: string): boolean { + return context.componentsInfo.builtInAttributes.includes(attributeName); +} +export function isBuildInComponent(context: UISyntaxRuleContext, componentName: string): boolean { + return context.componentsInfo.containerComponents.includes(componentName) || + context.componentsInfo.atomicComponents.includes(componentName); +} + +export function isAtomicComponent(context: UISyntaxRuleContext, componentName: string): boolean { + return context.componentsInfo.atomicComponents.includes(componentName); +} + +export function isContainerComponent(context: UISyntaxRuleContext, componentName: string): boolean { + return context.componentsInfo.containerComponents.includes(componentName); +} + +export function isSingleChildComponent(context: UISyntaxRuleContext, componentName: string): boolean { + return context.componentsInfo.singleChildComponents.includes(componentName); } \ No newline at end of file diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index 31984c2dd..4172fef24 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -488,3 +488,95 @@ KBoolean impl_IsArrayExpression(KNativePointer nodePtr) return GetImpl()->IsArrayExpression(node); } KOALA_INTEROP_1(IsArrayExpression, KBoolean, KNativePointer) + +KNativePointer impl_CreateDiagnosticKind(KNativePointer context, KStringPtr& message, KInt type) +{ + const auto _context = reinterpret_cast(context); + const auto _message = getStringCopy(message); + const auto _type = static_cast(type); + return const_cast(GetImpl()->CreateDiagnosticKind(_context, _message, _type)); +} +KOALA_INTEROP_3(CreateDiagnosticKind, KNativePointer, KNativePointer, KStringPtr, KInt); + +inline KUInt unpackUInt(const KByte* bytes) +{ + const KUInt BYTE_0 = 0; + const KUInt BYTE_1 = 1; + const KUInt BYTE_2 = 2; + const KUInt BYTE_3 = 3; + + const KUInt BYTE_1_SHIFT = 8; + const KUInt BYTE_2_SHIFT = 16; + const KUInt BYTE_3_SHIFT = 24; + return (bytes[BYTE_0] | (bytes[BYTE_1] << BYTE_1_SHIFT) + | (bytes[BYTE_2] << BYTE_2_SHIFT) | (bytes[BYTE_3] << BYTE_3_SHIFT) + ); +} + +KNativePointer impl_CreateDiagnosticInfo(KNativePointer context, KNativePointer kind, KStringArray argsPtr, KInt argc) +{ + const auto _context = reinterpret_cast(context); + const auto _kind = reinterpret_cast(kind); + 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); +} +KOALA_INTEROP_4(CreateDiagnosticInfo, KNativePointer, KNativePointer, KNativePointer, KStringArray, KInt); + +KNativePointer impl_CreateSuggestionInfo(KNativePointer context, KNativePointer kind, KStringArray argsPtr, + KInt argc, KStringPtr& substitutionCode) +{ + const auto _context = reinterpret_cast(context); + const auto _kind = reinterpret_cast(kind); + 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); +} +KOALA_INTEROP_5(CreateSuggestionInfo, KNativePointer, KNativePointer, KNativePointer, + KStringArray, KInt, KStringPtr); +void impl_LogDiagnostic(KNativePointer context, KNativePointer kind, KStringArray argvPtr, + KInt argc, KNativePointer pos) +{ + auto&& _context_ = reinterpret_cast(context); + auto&& _kind_ = reinterpret_cast(kind); + auto&& _pos_ = reinterpret_cast(pos); + 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_); +} +KOALA_INTEROP_V5(LogDiagnostic, KNativePointer, KNativePointer, KStringArray, KInt, KNativePointer); +void impl_LogDiagnosticWithSuggestion(KNativePointer context, KNativePointer diagnosticInfo, + KNativePointer suggestionInfo, KNativePointer range) +{ + const auto _context = reinterpret_cast(context); + const auto _diagnosticInfo = reinterpret_cast(diagnosticInfo); + const auto _suggestionInfo = reinterpret_cast(suggestionInfo); + const auto _range = reinterpret_cast(range); + GetImpl()->LogDiagnosticWithSuggestion(_context, _diagnosticInfo, _suggestionInfo, _range); +} +KOALA_INTEROP_V4(LogDiagnosticWithSuggestion, KNativePointer, KNativePointer, KNativePointer, KNativePointer); \ No newline at end of file diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 78314c0cc..8d584d2ab 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -24,6 +24,7 @@ import { } from '@koalaui/interop'; import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generated/Es2pandaNativeModule'; import * as path from 'path'; +import { PluginDiagnosticType } from './arkts-api/peers/DiagnosticKind'; // TODO: this type should be in interop export type KPtrArray = BigUint64Array; @@ -820,7 +821,7 @@ export class Es2pandaNativeModule { _ClassVariableDeclaration(context: KNativePointer, classInstance: KNativePointer): KNativePointer { throw new Error('Not implemented'); } - + _IsMethodDefinition(node: KPtr): KBoolean { throw new Error('Not implemented'); } @@ -844,6 +845,27 @@ export class Es2pandaNativeModule { _IsArrayExpression(node: KPtr): KBoolean { throw new Error('Not implemented'); } + _CreateDiagnosticKind(context: KNativePointer, message: string, type: PluginDiagnosticType): KNativePointer { + throw new Error('Not implemented'); + } + + _CreateDiagnosticInfo(context: KNativePointer, kind: KNativePointer, args: string[], argc: number): KNativePointer { + throw new Error('Not implemented'); + } + + _CreateSuggestionInfo(context: KNativePointer, kind: KNativePointer, args: string[], + argc: number, substitutionCode: string): KNativePointer { + throw new Error('Not implemented'); + } + + _LogDiagnostic(context: KNativePointer, kind: KNativePointer, argv: string[], argc: number, pos: KNativePointer): void { + throw new Error('Not implemented'); + } + + _LogDiagnosticWithSuggestion(context: KNativePointer, diagnosticInfo: KNativePointer, + suggestionInfo?: KNativePointer, range?: KNativePointer): void { + throw new Error('Not implemented'); + } } export function initEs2panda(): Es2pandaNativeModule { diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index a77ec8acd..cf0b940cf 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -77,6 +77,10 @@ export * from "./peers/Program" export * from "./peers/ImportPathManager" export * from "./peers/SourcePosition" export * from "./peers/SourceRange" +export * from "./peers/Diagnostic" +export * from "./peers/DiagnosticInfo" +export * from "./peers/DiagnosticKind" +export * from "./peers/SuggestionInfo" export * from "./to-be-generated/MemberExpression" export * from "./static/globalUtils" export { global as arktsGlobal } from "./static/global"; diff --git a/koala-wrapper/src/arkts-api/peers/Diagnostic.ts b/koala-wrapper/src/arkts-api/peers/Diagnostic.ts new file mode 100644 index 000000000..79f24ec0b --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/Diagnostic.ts @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from './ArktsObject'; +import { global } from '../static/global'; +import { KNativePointer } from '@koalaui/interop'; +import { DiagnosticKind } from './DiagnosticKind'; +import { passStringArray } from '../utilities/private'; +import { SourcePosition } from './SourcePosition'; +import { SourceRange } from './SourceRange'; +import { DiagnosticInfo } from './DiagnosticInfo'; +import { SuggestionInfo } from './SuggestionInfo'; + +export class Diagnostic extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer); + } + static logDiagnostic(kind: DiagnosticKind, pos: SourcePosition, ...args: string[]): void { + global.es2panda._LogDiagnostic(global.context, kind.peer, passStringArray(args), args.length, pos.peer); + } + + static logDiagnosticWithSuggestion(diagnosticInfo: DiagnosticInfo, suggestionInfo: SuggestionInfo, + range: SourceRange): void { + global.es2panda._LogDiagnosticWithSuggestion(global.context, diagnosticInfo.peer, suggestionInfo.peer, range.peer); + } + +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/peers/DiagnosticInfo.ts b/koala-wrapper/src/arkts-api/peers/DiagnosticInfo.ts new file mode 100644 index 000000000..d67f7e839 --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/DiagnosticInfo.ts @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from './ArktsObject'; +import { global } from '../static/global'; +import { KNativePointer } from '@koalaui/interop'; +import { DiagnosticKind } from './DiagnosticKind'; +import { passStringArray } from '../utilities/private'; + +export class DiagnosticInfo extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer); + } + + static create(kind: DiagnosticKind, ...args: string[]): DiagnosticInfo { + return new DiagnosticInfo( + global.es2panda._CreateDiagnosticInfo(global.context, kind.peer, passStringArray(args), args.length) + ); + } + +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/peers/DiagnosticKind.ts b/koala-wrapper/src/arkts-api/peers/DiagnosticKind.ts new file mode 100644 index 000000000..9bae299f0 --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/DiagnosticKind.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from './ArktsObject'; +import { global } from '../static/global'; +import { KNativePointer } from '@koalaui/interop'; + +export enum PluginDiagnosticType { + ES2PANDA_PLUGIN_WARNING = 0, + ES2PANDA_PLUGIN_ERROR, +}; + +export class DiagnosticKind extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer); + } + + static create(message: string, type: PluginDiagnosticType): DiagnosticKind { + return new DiagnosticKind( + global.es2panda._CreateDiagnosticKind(global.context, message, type) + ); + } +} diff --git a/koala-wrapper/src/arkts-api/peers/SuggestionInfo.ts b/koala-wrapper/src/arkts-api/peers/SuggestionInfo.ts new file mode 100644 index 000000000..cb43685c9 --- /dev/null +++ b/koala-wrapper/src/arkts-api/peers/SuggestionInfo.ts @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ArktsObject } from './ArktsObject'; +import { global } from '../static/global'; +import { KNativePointer } from '@koalaui/interop'; +import { DiagnosticKind } from './DiagnosticKind'; +import { passStringArray } from '../utilities/private'; + +export class SuggestionInfo extends ArktsObject { + constructor(peer: KNativePointer) { + super(peer); + } + + static create(kind: DiagnosticKind, substitutionCode: string, ...args: string[]): SuggestionInfo { + return new SuggestionInfo( + global.es2panda._CreateSuggestionInfo(global.context, kind.peer, passStringArray(args), args.length, substitutionCode) + ); + } + +} \ No newline at end of file -- Gitee From 497d2ffd859d2b07a170ab33e510cfed194c826c Mon Sep 17 00:00:00 2001 From: Cuecuexiaoyu Date: Thu, 29 May 2025 16:44:35 +0800 Subject: [PATCH 102/123] add other kit imports Signed-off-by: Cuecuexiaoyu Change-Id: Id0de1f69557367d7d0761f739c60be5fedbe8609 --- arkui-plugins/common/program-visitor.ts | 4 +- .../non-void-return-type.test.ts | 2 +- .../function-with-receiver.test.ts | 8 +- .../internal-calls.test.ts | 2 +- .../non-void-method.test.ts | 2 +- .../class-constructor.test.ts | 6 +- .../class-properties.test.ts | 12 +- .../init-with-local-builder.test.ts | 20 +- .../decorators/builder/local-builder.test.ts | 4 +- .../observed-track/observed-only.test.ts | 34 +- .../observed-track-class-property.test.ts | 60 +- .../observed-track-complex-type.test.ts | 532 +++++++++--------- .../observed-track-extends.test.ts | 54 +- .../observed-track-implements.test.ts | 34 +- .../observed-track/observed-track.test.ts | 20 +- .../observed-track/track-only.test.ts | 20 +- .../decorators/prop/prop-basic-type.test.ts | 40 +- .../decorators/prop/prop-complex-type.test.ts | 108 ++-- .../decorators/prop/state-to-prop.test.ts | 34 +- .../provide-annotation-usage.test.ts | 48 +- .../provide-basic-type.test.ts | 30 +- .../provide-complex-type.test.ts | 84 +-- .../resource/resource-in-build.test.ts | 16 +- .../resource/resource-in-property.test.ts | 16 +- .../reusable/reusable-basic.test.ts | 12 +- .../reusable/reusable-complex.test.ts | 20 +- .../decorators/state/state-basic-type.test.ts | 30 +- .../state/state-complex-type.test.ts | 84 +-- .../decorators/state/state-to-state.test.ts | 18 +- .../storagelink-appstorage.test.ts | 22 +- .../storagelink-complex-type.test.ts | 58 +- .../storagelink-primitive-type.test.ts | 18 +- .../storageprop-appstorage.test.ts | 22 +- .../storageprop-complex-type.test.ts | 58 +- .../storageprop-primitive-type.test.ts | 18 +- .../decorators/watch/watch-basic.test.ts | 62 +- .../xcomponent/xcomponent-basic.test.ts | 8 +- .../ui-plugins/preprocessor-transform.ts | 2 +- 38 files changed, 811 insertions(+), 811 deletions(-) diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index a0a35f6c6..9281c0b78 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -17,7 +17,7 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor, VisitorOptions } from './abstract-visitor'; import { matchPrefix } from './arkts-utils'; import { debugDump, getDumpFileName } from './debug'; -import { InteroperAbilityNames, ARKUI_COMPONENT_IMPORT_NAME } from './predefines'; +import { InteroperAbilityNames, ARKUI_COMPONENT_IMPORT_NAME, KIT_ARKUI_NAME } from './predefines'; import { PluginContext } from './plugin-context'; import { LegacyTransformer } from '../ui-plugins/legacy-transformer'; import { ComponentTransformer } from '../ui-plugins/component-transformer'; @@ -61,7 +61,7 @@ function flattenVisitorsInHooks( function sortExternalSources(externalSources: arkts.ExternalSource[]): arkts.ExternalSource[] { return externalSources.sort((a, b) => { - const prefix = ARKUI_COMPONENT_IMPORT_NAME; + const prefix = ARKUI_COMPONENT_IMPORT_NAME || KIT_ARKUI_NAME; const hasPrefixA = a.getName().startsWith(prefix); const hasPrefixB = b.getName().startsWith(prefix); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts index 53e3243e1..19b061ad6 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts @@ -91,7 +91,7 @@ type B = ((str: string)=> void); class C { public str: string; public constructor(str: string) { - (this).str = str; + this.str = str; } } `; diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts index 219dec151..be488294a 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts @@ -45,7 +45,7 @@ function main() {} function foo1(this: B, __memo_context: __memo_context_type, __memo_id: __memo_id_type, str: string): void { const __memo_scope = __memo_context.scope(((__memo_id) + (38567515)), 2); - const __memo_parameter_this = __memo_scope.param(0, (this)), __memo_parameter_str = __memo_scope.param(1, str); + const __memo_parameter_this = __memo_scope.param(0, this), __memo_parameter_str = __memo_scope.param(1, str); if (__memo_scope.unchanged) { __memo_scope.cached; return; @@ -59,7 +59,7 @@ function foo1(this: B, __memo_context: __memo_context_type, __memo_id: __memo_id function foo2(this: B, __memo_context: __memo_context_type, __memo_id: __memo_id_type, str: string): B { const __memo_scope = __memo_context.scope(((__memo_id) + (167482260)), 2); - const __memo_parameter_this = __memo_scope.param(0, (this)), __memo_parameter_str = __memo_scope.param(1, str); + const __memo_parameter_this = __memo_scope.param(0, this), __memo_parameter_str = __memo_scope.param(1, str); if (__memo_scope.unchanged) { return __memo_scope.cached; } @@ -73,8 +73,8 @@ class B { if (__memo_scope.unchanged) { return __memo_scope.cached; } - foo1((this), __memo_context, ((__memo_id) + (119664703)), "morning"); - return __memo_scope.recache(foo2((this), __memo_context, ((__memo_id) + (181969214)), "afternoon")); + foo1(this, __memo_context, ((__memo_id) + (119664703)), "morning"); + return __memo_scope.recache(foo2(this, __memo_context, ((__memo_id) + (181969214)), "afternoon")); } public constructor() {} diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts index 095b43a43..11dae0f7e 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts @@ -51,7 +51,7 @@ class Test { __memo_scope.cached; return; } - (this).void_method(__memo_context, ((__memo_id) + ())); + this.void_method(__memo_context, ((__memo_id) + ())); { __memo_scope.recache(); return; diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts index f8bba95f0..a8ddef791 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts @@ -66,7 +66,7 @@ class Test { return 0; } public intrinsic_method_with_this(): int { - (this).void_method(__memo_context, ((__memo_id) + ())); + this.void_method(__memo_context, ((__memo_id) + ())); return 0; } public memoEntry(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() entry: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> R)): R { diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts index c912aba8d..28671e700 100644 --- a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts @@ -63,10 +63,10 @@ interface A { class AA { @memo() public a: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined; constructor() { - (this)(undefined); + this(undefined); } public constructor(arg: A | undefined) { - (this).a = ({let gensym%%_ = arg; + this.a = ({let gensym%%_ = arg; (((gensym%%_) == (null)) ? undefined : gensym%%_.a)}); } public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { @@ -75,7 +75,7 @@ class AA { __memo_scope.cached; return; } - ({let gensym%%_ = (this).a; + ({let gensym%%_ = this.a; (((gensym%%_) == (null)) ? undefined : gensym%%_(__memo_context, ((__memo_id) + ())))}); { __memo_scope.recache(); diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts index 3be259236..c98720039 100644 --- a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts @@ -49,8 +49,8 @@ class A { }); public arg_memo_type: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); public constructor() { - (this).arg = (() => {}); - (this).memo_arg = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + this.arg = (() => {}); + this.memo_arg = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); if (__memo_scope.unchanged) { __memo_scope.cached; @@ -61,7 +61,7 @@ class A { return; } }); - (this).arg_memo_type = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { + this.arg_memo_type = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); if (__memo_scope.unchanged) { __memo_scope.cached; @@ -79,9 +79,9 @@ class A { __memo_scope.cached; return; } - (this).arg(); - (this).memo_arg(__memo_context, ((__memo_id) + ())); - (this).arg_memo_type(__memo_context, ((__memo_id) + ())); + this.arg(); + this.memo_arg(__memo_context, ((__memo_id) + ())); + this.arg_memo_type(__memo_context, ((__memo_id) + ())); { __memo_scope.recache(); return; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts index 96bf7204b..21e7f2bb4 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts @@ -47,31 +47,31 @@ function main() {} @Component({freezeWhenInactive:false}) final class Child extends CustomComponent { public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; - (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? ((this).doNothingBuilder)) - (this).__backing_customBuilderParam2 = ((((({let gensym___14041256 = initializers; - (((gensym___14041256) == (null)) ? undefined : gensym___14041256.customBuilderParam2)})) ?? (content))) ?? ((this).doNothingBuilder2)) + this.__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; + (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? (this.doNothingBuilder)) + this.__backing_customBuilderParam2 = ((((({let gensym___14041256 = initializers; + (((gensym___14041256) == (null)) ? undefined : gensym___14041256.customBuilderParam2)})) ?? (content))) ?? (this.doNothingBuilder2)) } public __updateStruct(initializers: __Options_Child | undefined): void {} private __backing_customBuilderParam?: @memo() (()=> void); public get customBuilderParam(): @memo() (()=> void) { - return (this).__backing_customBuilderParam!; + return this.__backing_customBuilderParam!; } public set customBuilderParam(@memo() value: (()=> void)) { - (this).__backing_customBuilderParam = value; + this.__backing_customBuilderParam = value; } private __backing_customBuilderParam2?: @memo() ((str: string)=> void); public get customBuilderParam2(): @memo() ((str: string)=> void) { - return (this).__backing_customBuilderParam2!; + return this.__backing_customBuilderParam2!; } public set customBuilderParam2(@memo() value: ((str: string)=> void)) { - (this).__backing_customBuilderParam2 = value; + this.__backing_customBuilderParam2 = value; } @memo() public doNothingBuilder() {} @memo() public doNothingBuilder2(str: string) {} @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - (this).customBuilderParam(); - (this).customBuilderParam2("hello"); + this.customBuilderParam(); + this.customBuilderParam2("hello"); } public constructor() {} } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts index e13c9d93a..9769285c5 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts @@ -64,8 +64,8 @@ function main() {} } @memo() public _build(@memo() style: ((instance: BuilderDemo)=> BuilderDemo) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_BuilderDemo | undefined): void { Column(undefined, undefined, @memo() (() => { - (this).showTextBuilder(); - (this).showTextValueBuilder("Hello @Builder"); + this.showTextBuilder(); + this.showTextValueBuilder("Hello @Builder"); })); } public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts index a6164cd81..08e0ec65b 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts @@ -71,15 +71,15 @@ function main() {} private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -93,32 +93,32 @@ function main() {} public constructor() {} public get propA(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_propA; + return this.__backing_propA; } public set propA(newValue: number) { - if ((((this).__backing_propA) !== (newValue))) { - (this).__backing_propA = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("propA"); + if (((this.__backing_propA) !== (newValue))) { + this.__backing_propA = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("propA"); } } public get trackA(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_trackA; + return this.__backing_trackA; } public set trackA(newValue: number) { - if ((((this).__backing_trackA) !== (newValue))) { - (this).__backing_trackA = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("trackA"); + if (((this.__backing_trackA) !== (newValue))) { + this.__backing_trackA = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("trackA"); } } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts index 5c1cf76ed..5bd7f7551 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts @@ -76,15 +76,15 @@ class E implements IObservedObject { private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -98,18 +98,18 @@ class E implements IObservedObject { public constructor() {} public get trackE(): Info { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_trackE.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_trackE.addRef(); } - setObservationDepth((this).__backing_trackE.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_trackE.value; + setObservationDepth(this.__backing_trackE.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_trackE.value; } public set trackE(newValue: Info) { - if ((((this).__backing_trackE.value) !== (newValue))) { - (this).__backing_trackE.value = newValue; - (this).__meta_trackE.fireChange(); - (this).executeOnSubscribingWatches("trackE"); + if (((this.__backing_trackE.value) !== (newValue))) { + this.__backing_trackE.value = newValue; + this.__meta_trackE.fireChange(); + this.executeOnSubscribingWatches("trackE"); } } @@ -119,15 +119,15 @@ class E implements IObservedObject { private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -141,34 +141,34 @@ class E implements IObservedObject { public constructor() {} public get propE1(): Info { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_propE1.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_propE1.value; + setObservationDepth(this.__backing_propE1.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_propE1.value; } public set propE1(newValue: Info) { - if ((((this).__backing_propE1.value) !== (newValue))) { - (this).__backing_propE1.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("propE1"); + if (((this.__backing_propE1.value) !== (newValue))) { + this.__backing_propE1.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("propE1"); } } public get trackE1(): Info { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_trackE1.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_trackE1.value; + setObservationDepth(this.__backing_trackE1.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_trackE1.value; } public set trackE1(newValue: Info) { - if ((((this).__backing_trackE1.value) !== (newValue))) { - (this).__backing_trackE1.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("trackE1"); + if (((this.__backing_trackE1.value) !== (newValue))) { + this.__backing_trackE1.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("trackE1"); } } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts index ecf1f1221..371c48a6c 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts @@ -81,7 +81,7 @@ final class Status extends BaseEnum { public constructor(ordinal: int, value: int) { super(value); - (this).#ordinal = ordinal; + this.#ordinal = ordinal; } public static readonly Success: Status = new Status(0, 200); @@ -99,7 +99,7 @@ final class Status extends BaseEnum { private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; public getName(): String { - return Status.#NamesArray[(this).#ordinal]; + return Status.#NamesArray[this.#ordinal]; } public static getValueOf(name: String): Status { @@ -121,11 +121,11 @@ final class Status extends BaseEnum { } public valueOf(): int { - return Status.#ValuesArray[(this).#ordinal]; + return Status.#ValuesArray[this.#ordinal]; } public toString(): String { - return Status.#StringValuesArray[(this).#ordinal]; + return Status.#StringValuesArray[this.#ordinal]; } public static values(): Status[] { @@ -133,7 +133,7 @@ final class Status extends BaseEnum { } public getOrdinal(): int { - return (this).#ordinal; + return this.#ordinal; } public static $_get(e: Status): String { @@ -146,15 +146,15 @@ final class Status extends BaseEnum { private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -228,174 +228,174 @@ final class Status extends BaseEnum { public constructor() {} public get numA(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_numA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_numA.addRef(); } - return (this).__backing_numA; + return this.__backing_numA; } public set numA(newValue: number) { - if ((((this).__backing_numA) !== (newValue))) { - (this).__backing_numA = newValue; - (this).__meta_numA.fireChange(); - (this).executeOnSubscribingWatches("numA"); + if (((this.__backing_numA) !== (newValue))) { + this.__backing_numA = newValue; + this.__meta_numA.fireChange(); + this.executeOnSubscribingWatches("numA"); } } public get stringA(): string { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_stringA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_stringA.addRef(); } - return (this).__backing_stringA; + return this.__backing_stringA; } public set stringA(newValue: string) { - if ((((this).__backing_stringA) !== (newValue))) { - (this).__backing_stringA = newValue; - (this).__meta_stringA.fireChange(); - (this).executeOnSubscribingWatches("stringA"); + if (((this.__backing_stringA) !== (newValue))) { + this.__backing_stringA = newValue; + this.__meta_stringA.fireChange(); + this.executeOnSubscribingWatches("stringA"); } } public get booleanA(): boolean { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_booleanA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_booleanA.addRef(); } - return (this).__backing_booleanA; + return this.__backing_booleanA; } public set booleanA(newValue: boolean) { - if ((((this).__backing_booleanA) !== (newValue))) { - (this).__backing_booleanA = newValue; - (this).__meta_booleanA.fireChange(); - (this).executeOnSubscribingWatches("booleanA"); + if (((this.__backing_booleanA) !== (newValue))) { + this.__backing_booleanA = newValue; + this.__meta_booleanA.fireChange(); + this.executeOnSubscribingWatches("booleanA"); } } public get arrayA(): Array { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_arrayA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_arrayA.addRef(); } - setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_arrayA.value; + setObservationDepth(this.__backing_arrayA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_arrayA.value; } public set arrayA(newValue: Array) { - if ((((this).__backing_arrayA.value) !== (newValue))) { - (this).__backing_arrayA.value = newValue; - (this).__meta_arrayA.fireChange(); - (this).executeOnSubscribingWatches("arrayA"); + if (((this.__backing_arrayA.value) !== (newValue))) { + this.__backing_arrayA.value = newValue; + this.__meta_arrayA.fireChange(); + this.executeOnSubscribingWatches("arrayA"); } } public get objectA(): Object { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_objectA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_objectA.addRef(); } - setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_objectA.value; + setObservationDepth(this.__backing_objectA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_objectA.value; } public set objectA(newValue: Object) { - if ((((this).__backing_objectA.value) !== (newValue))) { - (this).__backing_objectA.value = newValue; - (this).__meta_objectA.fireChange(); - (this).executeOnSubscribingWatches("objectA"); + if (((this.__backing_objectA.value) !== (newValue))) { + this.__backing_objectA.value = newValue; + this.__meta_objectA.fireChange(); + this.executeOnSubscribingWatches("objectA"); } } public get dateA(): Date { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_dateA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_dateA.addRef(); } - setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_dateA.value; + setObservationDepth(this.__backing_dateA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_dateA.value; } public set dateA(newValue: Date) { - if ((((this).__backing_dateA.value) !== (newValue))) { - (this).__backing_dateA.value = newValue; - (this).__meta_dateA.fireChange(); - (this).executeOnSubscribingWatches("dateA"); + if (((this.__backing_dateA.value) !== (newValue))) { + this.__backing_dateA.value = newValue; + this.__meta_dateA.fireChange(); + this.executeOnSubscribingWatches("dateA"); } } public get setA(): Set { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_setA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_setA.addRef(); } - setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_setA.value; + setObservationDepth(this.__backing_setA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_setA.value; } public set setA(newValue: Set) { - if ((((this).__backing_setA.value) !== (newValue))) { - (this).__backing_setA.value = newValue; - (this).__meta_setA.fireChange(); - (this).executeOnSubscribingWatches("setA"); + if (((this.__backing_setA.value) !== (newValue))) { + this.__backing_setA.value = newValue; + this.__meta_setA.fireChange(); + this.executeOnSubscribingWatches("setA"); } } public get mapA(): Map { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_mapA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_mapA.addRef(); } - setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_mapA.value; + setObservationDepth(this.__backing_mapA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_mapA.value; } public set mapA(newValue: Map) { - if ((((this).__backing_mapA.value) !== (newValue))) { - (this).__backing_mapA.value = newValue; - (this).__meta_mapA.fireChange(); - (this).executeOnSubscribingWatches("mapA"); + if (((this.__backing_mapA.value) !== (newValue))) { + this.__backing_mapA.value = newValue; + this.__meta_mapA.fireChange(); + this.executeOnSubscribingWatches("mapA"); } } public get unionA(): string | undefined { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_unionA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_unionA.addRef(); } - return (this).__backing_unionA; + return this.__backing_unionA; } public set unionA(newValue: string | undefined) { - if ((((this).__backing_unionA) !== (newValue))) { - (this).__backing_unionA = newValue; - (this).__meta_unionA.fireChange(); - (this).executeOnSubscribingWatches("unionA"); + if (((this.__backing_unionA) !== (newValue))) { + this.__backing_unionA = newValue; + this.__meta_unionA.fireChange(); + this.executeOnSubscribingWatches("unionA"); } } public get classA(): Person { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_classA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_classA.addRef(); } - setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_classA.value; + setObservationDepth(this.__backing_classA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_classA.value; } public set classA(newValue: Person) { - if ((((this).__backing_classA.value) !== (newValue))) { - (this).__backing_classA.value = newValue; - (this).__meta_classA.fireChange(); - (this).executeOnSubscribingWatches("classA"); + if (((this.__backing_classA.value) !== (newValue))) { + this.__backing_classA.value = newValue; + this.__meta_classA.fireChange(); + this.executeOnSubscribingWatches("classA"); } } public get enumA(): Status { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_enumA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_enumA.addRef(); } - setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_enumA.value; + setObservationDepth(this.__backing_enumA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_enumA.value; } public set enumA(newValue: Status) { - if ((((this).__backing_enumA.value) !== (newValue))) { - (this).__backing_enumA.value = newValue; - (this).__meta_enumA.fireChange(); - (this).executeOnSubscribingWatches("enumA"); + if (((this.__backing_enumA.value) !== (newValue))) { + this.__backing_enumA.value = newValue; + this.__meta_enumA.fireChange(); + this.executeOnSubscribingWatches("enumA"); } } @@ -405,15 +405,15 @@ final class Status extends BaseEnum { private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -445,174 +445,174 @@ final class Status extends BaseEnum { public constructor() {} public get numA(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_numA; + return this.__backing_numA; } public set numA(newValue: number) { - if ((((this).__backing_numA) !== (newValue))) { - (this).__backing_numA = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("numA"); + if (((this.__backing_numA) !== (newValue))) { + this.__backing_numA = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("numA"); } } public get stringA(): string { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_stringA; + return this.__backing_stringA; } public set stringA(newValue: string) { - if ((((this).__backing_stringA) !== (newValue))) { - (this).__backing_stringA = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("stringA"); + if (((this.__backing_stringA) !== (newValue))) { + this.__backing_stringA = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("stringA"); } } public get booleanA(): boolean { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_booleanA; + return this.__backing_booleanA; } public set booleanA(newValue: boolean) { - if ((((this).__backing_booleanA) !== (newValue))) { - (this).__backing_booleanA = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("booleanA"); + if (((this.__backing_booleanA) !== (newValue))) { + this.__backing_booleanA = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("booleanA"); } } public get arrayA(): Array { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_arrayA.value; + setObservationDepth(this.__backing_arrayA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_arrayA.value; } public set arrayA(newValue: Array) { - if ((((this).__backing_arrayA.value) !== (newValue))) { - (this).__backing_arrayA.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("arrayA"); + if (((this.__backing_arrayA.value) !== (newValue))) { + this.__backing_arrayA.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("arrayA"); } } public get objectA(): Object { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_objectA.value; + setObservationDepth(this.__backing_objectA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_objectA.value; } public set objectA(newValue: Object) { - if ((((this).__backing_objectA.value) !== (newValue))) { - (this).__backing_objectA.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("objectA"); + if (((this.__backing_objectA.value) !== (newValue))) { + this.__backing_objectA.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("objectA"); } } public get dateA(): Date { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_dateA.value; + setObservationDepth(this.__backing_dateA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_dateA.value; } public set dateA(newValue: Date) { - if ((((this).__backing_dateA.value) !== (newValue))) { - (this).__backing_dateA.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("dateA"); + if (((this.__backing_dateA.value) !== (newValue))) { + this.__backing_dateA.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("dateA"); } } public get setA(): Set { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_setA.value; + setObservationDepth(this.__backing_setA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_setA.value; } public set setA(newValue: Set) { - if ((((this).__backing_setA.value) !== (newValue))) { - (this).__backing_setA.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("setA"); + if (((this.__backing_setA.value) !== (newValue))) { + this.__backing_setA.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("setA"); } } public get mapA(): Map { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_mapA.value; + setObservationDepth(this.__backing_mapA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_mapA.value; } public set mapA(newValue: Map) { - if ((((this).__backing_mapA.value) !== (newValue))) { - (this).__backing_mapA.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("mapA"); + if (((this.__backing_mapA.value) !== (newValue))) { + this.__backing_mapA.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("mapA"); } } public get unionA(): string | undefined { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_unionA; + return this.__backing_unionA; } public set unionA(newValue: string | undefined) { - if ((((this).__backing_unionA) !== (newValue))) { - (this).__backing_unionA = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("unionA"); + if (((this.__backing_unionA) !== (newValue))) { + this.__backing_unionA = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("unionA"); } } public get classA(): Person { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_classA.value; + setObservationDepth(this.__backing_classA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_classA.value; } public set classA(newValue: Person) { - if ((((this).__backing_classA.value) !== (newValue))) { - (this).__backing_classA.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("classA"); + if (((this.__backing_classA.value) !== (newValue))) { + this.__backing_classA.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("classA"); } } public get enumA(): Status { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_enumA.value; + setObservationDepth(this.__backing_enumA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_enumA.value; } public set enumA(newValue: Status) { - if ((((this).__backing_enumA.value) !== (newValue))) { - (this).__backing_enumA.value = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("enumA"); + if (((this.__backing_enumA.value) !== (newValue))) { + this.__backing_enumA.value = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("enumA"); } } @@ -622,15 +622,15 @@ class mixed3 implements IObservedObject { private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -682,174 +682,174 @@ class mixed3 implements IObservedObject { public constructor() {} public get numA(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_numA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_numA.addRef(); } - return (this).__backing_numA; + return this.__backing_numA; } public set numA(newValue: number) { - if ((((this).__backing_numA) !== (newValue))) { - (this).__backing_numA = newValue; - (this).__meta_numA.fireChange(); - (this).executeOnSubscribingWatches("numA"); + if (((this.__backing_numA) !== (newValue))) { + this.__backing_numA = newValue; + this.__meta_numA.fireChange(); + this.executeOnSubscribingWatches("numA"); } } public get stringA(): string { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_stringA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_stringA.addRef(); } - return (this).__backing_stringA; + return this.__backing_stringA; } public set stringA(newValue: string) { - if ((((this).__backing_stringA) !== (newValue))) { - (this).__backing_stringA = newValue; - (this).__meta_stringA.fireChange(); - (this).executeOnSubscribingWatches("stringA"); + if (((this.__backing_stringA) !== (newValue))) { + this.__backing_stringA = newValue; + this.__meta_stringA.fireChange(); + this.executeOnSubscribingWatches("stringA"); } } public get booleanA(): boolean { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_booleanA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_booleanA.addRef(); } - return (this).__backing_booleanA; + return this.__backing_booleanA; } public set booleanA(newValue: boolean) { - if ((((this).__backing_booleanA) !== (newValue))) { - (this).__backing_booleanA = newValue; - (this).__meta_booleanA.fireChange(); - (this).executeOnSubscribingWatches("booleanA"); + if (((this.__backing_booleanA) !== (newValue))) { + this.__backing_booleanA = newValue; + this.__meta_booleanA.fireChange(); + this.executeOnSubscribingWatches("booleanA"); } } public get arrayA(): Array { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_arrayA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_arrayA.addRef(); } - setObservationDepth((this).__backing_arrayA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_arrayA.value; + setObservationDepth(this.__backing_arrayA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_arrayA.value; } public set arrayA(newValue: Array) { - if ((((this).__backing_arrayA.value) !== (newValue))) { - (this).__backing_arrayA.value = newValue; - (this).__meta_arrayA.fireChange(); - (this).executeOnSubscribingWatches("arrayA"); + if (((this.__backing_arrayA.value) !== (newValue))) { + this.__backing_arrayA.value = newValue; + this.__meta_arrayA.fireChange(); + this.executeOnSubscribingWatches("arrayA"); } } public get objectA(): Object { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_objectA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_objectA.addRef(); } - setObservationDepth((this).__backing_objectA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_objectA.value; + setObservationDepth(this.__backing_objectA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_objectA.value; } public set objectA(newValue: Object) { - if ((((this).__backing_objectA.value) !== (newValue))) { - (this).__backing_objectA.value = newValue; - (this).__meta_objectA.fireChange(); - (this).executeOnSubscribingWatches("objectA"); + if (((this.__backing_objectA.value) !== (newValue))) { + this.__backing_objectA.value = newValue; + this.__meta_objectA.fireChange(); + this.executeOnSubscribingWatches("objectA"); } } public get dateA(): Date { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_dateA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_dateA.addRef(); } - setObservationDepth((this).__backing_dateA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_dateA.value; + setObservationDepth(this.__backing_dateA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_dateA.value; } public set dateA(newValue: Date) { - if ((((this).__backing_dateA.value) !== (newValue))) { - (this).__backing_dateA.value = newValue; - (this).__meta_dateA.fireChange(); - (this).executeOnSubscribingWatches("dateA"); + if (((this.__backing_dateA.value) !== (newValue))) { + this.__backing_dateA.value = newValue; + this.__meta_dateA.fireChange(); + this.executeOnSubscribingWatches("dateA"); } } public get setA(): Set { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_setA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_setA.addRef(); } - setObservationDepth((this).__backing_setA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_setA.value; + setObservationDepth(this.__backing_setA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_setA.value; } public set setA(newValue: Set) { - if ((((this).__backing_setA.value) !== (newValue))) { - (this).__backing_setA.value = newValue; - (this).__meta_setA.fireChange(); - (this).executeOnSubscribingWatches("setA"); + if (((this.__backing_setA.value) !== (newValue))) { + this.__backing_setA.value = newValue; + this.__meta_setA.fireChange(); + this.executeOnSubscribingWatches("setA"); } } public get mapA(): Map { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_mapA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_mapA.addRef(); } - setObservationDepth((this).__backing_mapA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_mapA.value; + setObservationDepth(this.__backing_mapA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_mapA.value; } public set mapA(newValue: Map) { - if ((((this).__backing_mapA.value) !== (newValue))) { - (this).__backing_mapA.value = newValue; - (this).__meta_mapA.fireChange(); - (this).executeOnSubscribingWatches("mapA"); + if (((this.__backing_mapA.value) !== (newValue))) { + this.__backing_mapA.value = newValue; + this.__meta_mapA.fireChange(); + this.executeOnSubscribingWatches("mapA"); } } public get unionA(): string | undefined { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_unionA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_unionA.addRef(); } - return (this).__backing_unionA; + return this.__backing_unionA; } public set unionA(newValue: string | undefined) { - if ((((this).__backing_unionA) !== (newValue))) { - (this).__backing_unionA = newValue; - (this).__meta_unionA.fireChange(); - (this).executeOnSubscribingWatches("unionA"); + if (((this.__backing_unionA) !== (newValue))) { + this.__backing_unionA = newValue; + this.__meta_unionA.fireChange(); + this.executeOnSubscribingWatches("unionA"); } } public get classA(): Person { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_classA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_classA.addRef(); } - setObservationDepth((this).__backing_classA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_classA.value; + setObservationDepth(this.__backing_classA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_classA.value; } public set classA(newValue: Person) { - if ((((this).__backing_classA.value) !== (newValue))) { - (this).__backing_classA.value = newValue; - (this).__meta_classA.fireChange(); - (this).executeOnSubscribingWatches("classA"); + if (((this.__backing_classA.value) !== (newValue))) { + this.__backing_classA.value = newValue; + this.__meta_classA.fireChange(); + this.executeOnSubscribingWatches("classA"); } } public get enumA(): Status { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_enumA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_enumA.addRef(); } - setObservationDepth((this).__backing_enumA.value, (((this)._permissibleAddRefDepth) - (1))); - return (this).__backing_enumA.value; + setObservationDepth(this.__backing_enumA.value, ((this._permissibleAddRefDepth) - (1))); + return this.__backing_enumA.value; } public set enumA(newValue: Status) { - if ((((this).__backing_enumA.value) !== (newValue))) { - (this).__backing_enumA.value = newValue; - (this).__meta_enumA.fireChange(); - (this).executeOnSubscribingWatches("enumA"); + if (((this.__backing_enumA.value) !== (newValue))) { + this.__backing_enumA.value = newValue; + this.__meta_enumA.fireChange(); + this.executeOnSubscribingWatches("enumA"); } } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts index ba37d587a..f3f3a001e 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts @@ -71,15 +71,15 @@ function main() {} private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -93,32 +93,32 @@ function main() {} public constructor() {} public get propA(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_propA; + return this.__backing_propA; } public set propA(newValue: number) { - if ((((this).__backing_propA) !== (newValue))) { - (this).__backing_propA = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("propA"); + if (((this.__backing_propA) !== (newValue))) { + this.__backing_propA = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("propA"); } } public get trackA(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_trackA; + return this.__backing_trackA; } public set trackA(newValue: number) { - if ((((this).__backing_trackA) !== (newValue))) { - (this).__backing_trackA = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("trackA"); + if (((this.__backing_trackA) !== (newValue))) { + this.__backing_trackA = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("trackA"); } } @@ -135,15 +135,15 @@ class G extends A { private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -155,17 +155,17 @@ class G extends A { public constructor() {} public get propG(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_propG.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_propG.addRef(); } - return (this).__backing_propG; + return this.__backing_propG; } public set propG(newValue: number) { - if ((((this).__backing_propG) !== (newValue))) { - (this).__backing_propG = newValue; - (this).__meta_propG.fireChange(); - (this).executeOnSubscribingWatches("propG"); + if (((this.__backing_propG) !== (newValue))) { + this.__backing_propG = newValue; + this.__meta_propG.fireChange(); + this.executeOnSubscribingWatches("propG"); } } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts index e088b941b..f71a5e922 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts @@ -85,15 +85,15 @@ interface trackInterface { private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -107,33 +107,33 @@ interface trackInterface { public constructor() {} public set propF(newValue: number) { - if ((((this).__backing_propF) !== (newValue))) { - (this).__backing_propF = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("propF"); + if (((this.__backing_propF) !== (newValue))) { + this.__backing_propF = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("propF"); } } public get propF(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_propF; + return this.__backing_propF; } public set trackF(newValue: number) { - if ((((this).__backing_trackF) !== (newValue))) { - (this).__backing_trackF = newValue; - (this).__meta.fireChange(); - (this).executeOnSubscribingWatches("trackF"); + if (((this.__backing_trackF) !== (newValue))) { + this.__backing_trackF = newValue; + this.__meta.fireChange(); + this.executeOnSubscribingWatches("trackF"); } } public get trackF(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta.addRef(); } - return (this).__backing_trackF; + return this.__backing_trackF; } } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts index 81a3f5074..9f28609dc 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts @@ -71,15 +71,15 @@ function main() {} private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -93,17 +93,17 @@ function main() {} public constructor() {} public get trackB(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_trackB.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_trackB.addRef(); } - return (this).__backing_trackB; + return this.__backing_trackB; } public set trackB(newValue: number) { - if ((((this).__backing_trackB) !== (newValue))) { - (this).__backing_trackB = newValue; - (this).__meta_trackB.fireChange(); - (this).executeOnSubscribingWatches("trackB"); + if (((this.__backing_trackB) !== (newValue))) { + this.__backing_trackB = newValue; + this.__meta_trackB.fireChange(); + this.executeOnSubscribingWatches("trackB"); } } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts index e6740faa7..a1e60b0fa 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts @@ -71,15 +71,15 @@ class C implements IObservedObject { private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -93,17 +93,17 @@ class C implements IObservedObject { public constructor() {} public get trackC(): number { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_trackC.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_trackC.addRef(); } - return (this).__backing_trackC; + return this.__backing_trackC; } public set trackC(newValue: number) { - if ((((this).__backing_trackC) !== (newValue))) { - (this).__backing_trackC = newValue; - (this).__meta_trackC.fireChange(); - (this).executeOnSubscribingWatches("trackC"); + if (((this.__backing_trackC) !== (newValue))) { + this.__backing_trackC = newValue; + this.__meta_trackC.fireChange(); + this.executeOnSubscribingWatches("trackC"); } } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts index 7284beb5e..9ed163723 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts @@ -49,73 +49,73 @@ function main() {} @Component({freezeWhenInactive:false}) final class PropParent extends CustomComponent { public __initializeStruct(initializers: __Options_PropParent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_propVar1 = new PropDecoratedVariable("propVar1", ((({let gensym___95172135 = initializers; + this.__backing_propVar1 = new PropDecoratedVariable("propVar1", ((({let gensym___95172135 = initializers; (((gensym___95172135) == (null)) ? undefined : gensym___95172135.propVar1)})) ?? ("propVar1"))); - (this).__backing_propVar2 = new PropDecoratedVariable("propVar2", ((({let gensym___222490386 = initializers; + this.__backing_propVar2 = new PropDecoratedVariable("propVar2", ((({let gensym___222490386 = initializers; (((gensym___222490386) == (null)) ? undefined : gensym___222490386.propVar2)})) ?? (50))); - (this).__backing_propVar3 = new PropDecoratedVariable("propVar3", ((({let gensym___201781257 = initializers; + this.__backing_propVar3 = new PropDecoratedVariable("propVar3", ((({let gensym___201781257 = initializers; (((gensym___201781257) == (null)) ? undefined : gensym___201781257.propVar3)})) ?? (true))); - (this).__backing_propVar4 = new PropDecoratedVariable("propVar4", ((({let gensym___22028950 = initializers; + this.__backing_propVar4 = new PropDecoratedVariable("propVar4", ((({let gensym___22028950 = initializers; (((gensym___22028950) == (null)) ? undefined : gensym___22028950.propVar4)})) ?? (undefined))); - (this).__backing_propVar5 = new PropDecoratedVariable("propVar5", ((({let gensym___54872258 = initializers; + this.__backing_propVar5 = new PropDecoratedVariable("propVar5", ((({let gensym___54872258 = initializers; (((gensym___54872258) == (null)) ? undefined : gensym___54872258.propVar5)})) ?? (null))); } public __updateStruct(initializers: __Options_PropParent | undefined): void { if (((({let gensym___67969738 = initializers; (((gensym___67969738) == (null)) ? undefined : gensym___67969738.propVar1)})) !== (undefined))) { - (this).__backing_propVar1!.update((initializers!.propVar1 as string)); + this.__backing_propVar1!.update((initializers!.propVar1 as string)); } if (((({let gensym___52350476 = initializers; (((gensym___52350476) == (null)) ? undefined : gensym___52350476.propVar2)})) !== (undefined))) { - (this).__backing_propVar2!.update((initializers!.propVar2 as number)); + this.__backing_propVar2!.update((initializers!.propVar2 as number)); } if (((({let gensym___103864283 = initializers; (((gensym___103864283) == (null)) ? undefined : gensym___103864283.propVar3)})) !== (undefined))) { - (this).__backing_propVar3!.update((initializers!.propVar3 as boolean)); + this.__backing_propVar3!.update((initializers!.propVar3 as boolean)); } if (((({let gensym___175155715 = initializers; (((gensym___175155715) == (null)) ? undefined : gensym___175155715.propVar4)})) !== (undefined))) { - (this).__backing_propVar4!.update((initializers!.propVar4 as undefined)); + this.__backing_propVar4!.update((initializers!.propVar4 as undefined)); } if (((({let gensym___134530703 = initializers; (((gensym___134530703) == (null)) ? undefined : gensym___134530703.propVar5)})) !== (undefined))) { - (this).__backing_propVar5!.update((initializers!.propVar5 as null)); + this.__backing_propVar5!.update((initializers!.propVar5 as null)); } } private __backing_propVar1?: PropDecoratedVariable; public get propVar1(): string { - return (this).__backing_propVar1!.get(); + return this.__backing_propVar1!.get(); } public set propVar1(value: string) { - (this).__backing_propVar1!.set(value); + this.__backing_propVar1!.set(value); } private __backing_propVar2?: PropDecoratedVariable; public get propVar2(): number { - return (this).__backing_propVar2!.get(); + return this.__backing_propVar2!.get(); } public set propVar2(value: number) { - (this).__backing_propVar2!.set(value); + this.__backing_propVar2!.set(value); } private __backing_propVar3?: PropDecoratedVariable; public get propVar3(): boolean { - return (this).__backing_propVar3!.get(); + return this.__backing_propVar3!.get(); } public set propVar3(value: boolean) { - (this).__backing_propVar3!.set(value); + this.__backing_propVar3!.set(value); } private __backing_propVar4?: PropDecoratedVariable; public get propVar4(): undefined { - return (this).__backing_propVar4!.get(); + return this.__backing_propVar4!.get(); } public set propVar4(value: undefined) { - (this).__backing_propVar4!.set(value); + this.__backing_propVar4!.set(value); } private __backing_propVar5?: PropDecoratedVariable; public get propVar5(): null { - return (this).__backing_propVar5!.get(); + return this.__backing_propVar5!.get(); } public set propVar5(value: null) { - (this).__backing_propVar5!.set(value); + this.__backing_propVar5!.set(value); } @memo() public _build(@memo() style: ((instance: PropParent)=> PropParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_PropParent | undefined): void {} public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts index 5c6262494..7db445781 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts @@ -50,7 +50,7 @@ function main() {} class Per { public num: number; public constructor(num: number) { - (this).num = num; + this.num = num; } } @@ -59,7 +59,7 @@ final class PropType extends BaseEnum { private static () {} public constructor(ordinal: int, value: int) { super(value); - (this).#ordinal = ordinal; + this.#ordinal = ordinal; } public static readonly TYPE1: PropType = new PropType(0, 0); public static readonly TYPE2: PropType = new PropType(1, 1); @@ -69,7 +69,7 @@ final class PropType extends BaseEnum { private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; private static readonly #ItemsArray: PropType[] = [PropType.TYPE1, PropType.TYPE2, PropType.TYPE3]; public getName(): String { - return PropType.#NamesArray[(this).#ordinal]; + return PropType.#NamesArray[this.#ordinal]; } public static getValueOf(name: String): PropType { for (let i = 0;((i) < (PropType.#NamesArray.length));(++i)) { @@ -88,16 +88,16 @@ final class PropType extends BaseEnum { throw new Error((("No enum PropType with value ") + (value))); } public valueOf(): int { - return PropType.#ValuesArray[(this).#ordinal]; + return PropType.#ValuesArray[this.#ordinal]; } public toString(): String { - return PropType.#StringValuesArray[(this).#ordinal]; + return PropType.#StringValuesArray[this.#ordinal]; } public static values(): PropType[] { return PropType.#ItemsArray; } public getOrdinal(): int { - return (this).#ordinal; + return this.#ordinal; } public static $_get(e: PropType): String { return e.getName(); @@ -106,164 +106,164 @@ final class PropType extends BaseEnum { @Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_propVar1 = new PropDecoratedVariable("propVar1", ((({let gensym___95172135 = initializers; + this.__backing_propVar1 = new PropDecoratedVariable("propVar1", ((({let gensym___95172135 = initializers; (((gensym___95172135) == (null)) ? undefined : gensym___95172135.propVar1)})) ?? (new Per(6)))); - (this).__backing_propVar2 = new PropDecoratedVariable>("propVar2", ((({let gensym___222490386 = initializers; + this.__backing_propVar2 = new PropDecoratedVariable>("propVar2", ((({let gensym___222490386 = initializers; (((gensym___222490386) == (null)) ? undefined : gensym___222490386.propVar2)})) ?? (new Array(3, 6, 8)))); - (this).__backing_propVar3 = new PropDecoratedVariable("propVar3", ((({let gensym___201781257 = initializers; + this.__backing_propVar3 = new PropDecoratedVariable("propVar3", ((({let gensym___201781257 = initializers; (((gensym___201781257) == (null)) ? undefined : gensym___201781257.propVar3)})) ?? (PropType.TYPE3))); - (this).__backing_propVar4 = new PropDecoratedVariable>("propVar4", ((({let gensym___22028950 = initializers; + this.__backing_propVar4 = new PropDecoratedVariable>("propVar4", ((({let gensym___22028950 = initializers; (((gensym___22028950) == (null)) ? undefined : gensym___22028950.propVar4)})) ?? (new Set(new Array("aa", "bb"))))); - (this).__backing_propVar5 = new PropDecoratedVariable>("propVar5", ((({let gensym___54872258 = initializers; + this.__backing_propVar5 = new PropDecoratedVariable>("propVar5", ((({let gensym___54872258 = initializers; (((gensym___54872258) == (null)) ? undefined : gensym___54872258.propVar5)})) ?? ([true, false]))); - (this).__backing_propVar6 = new PropDecoratedVariable>("propVar6", ((({let gensym___128760941 = initializers; + this.__backing_propVar6 = new PropDecoratedVariable>("propVar6", ((({let gensym___128760941 = initializers; (((gensym___128760941) == (null)) ? undefined : gensym___128760941.propVar6)})) ?? (new Array(new Per(7), new Per(11))))); - (this).__backing_propVar7 = new PropDecoratedVariable>("propVar7", ((({let gensym___30534085 = initializers; + this.__backing_propVar7 = new PropDecoratedVariable>("propVar7", ((({let gensym___30534085 = initializers; (((gensym___30534085) == (null)) ? undefined : gensym___30534085.propVar7)})) ?? ([new Per(7), new Per(11)]))); - (this).__backing_propVar8 = new PropDecoratedVariable<((sr: string)=> void)>("propVar8", ((({let gensym___12471776 = initializers; + this.__backing_propVar8 = new PropDecoratedVariable<((sr: string)=> void)>("propVar8", ((({let gensym___12471776 = initializers; (((gensym___12471776) == (null)) ? undefined : gensym___12471776.propVar8)})) ?? (((sr: string) => {})))); - (this).__backing_propVar9 = new PropDecoratedVariable("propVar9", ((({let gensym___123472108 = initializers; + this.__backing_propVar9 = new PropDecoratedVariable("propVar9", ((({let gensym___123472108 = initializers; (((gensym___123472108) == (null)) ? undefined : gensym___123472108.propVar9)})) ?? (new Date("2025-4-23")))); - (this).__backing_propVar10 = new PropDecoratedVariable>("propVar10", ((({let gensym___147847012 = initializers; + this.__backing_propVar10 = new PropDecoratedVariable>("propVar10", ((({let gensym___147847012 = initializers; (((gensym___147847012) == (null)) ? undefined : gensym___147847012.propVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]])))); - (this).__backing_propVar11 = new PropDecoratedVariable("propVar11", ((({let gensym___117026760 = initializers; + this.__backing_propVar11 = new PropDecoratedVariable("propVar11", ((({let gensym___117026760 = initializers; (((gensym___117026760) == (null)) ? undefined : gensym___117026760.propVar11)})) ?? (0.0))); - (this).__backing_propVar12 = new PropDecoratedVariable | Per>("propVar12", ((({let gensym___220245132 = initializers; + this.__backing_propVar12 = new PropDecoratedVariable | Per>("propVar12", ((({let gensym___220245132 = initializers; (((gensym___220245132) == (null)) ? undefined : gensym___220245132.propVar12)})) ?? (new Per(6)))); } public __updateStruct(initializers: __Options_Parent | undefined): void { if (((({let gensym___67969738 = initializers; (((gensym___67969738) == (null)) ? undefined : gensym___67969738.propVar1)})) !== (undefined))) { - (this).__backing_propVar1!.update((initializers!.propVar1 as Per)); + this.__backing_propVar1!.update((initializers!.propVar1 as Per)); } if (((({let gensym___52350476 = initializers; (((gensym___52350476) == (null)) ? undefined : gensym___52350476.propVar2)})) !== (undefined))) { - (this).__backing_propVar2!.update((initializers!.propVar2 as Array)); + this.__backing_propVar2!.update((initializers!.propVar2 as Array)); } if (((({let gensym___103864283 = initializers; (((gensym___103864283) == (null)) ? undefined : gensym___103864283.propVar3)})) !== (undefined))) { - (this).__backing_propVar3!.update((initializers!.propVar3 as PropType)); + this.__backing_propVar3!.update((initializers!.propVar3 as PropType)); } if (((({let gensym___175155715 = initializers; (((gensym___175155715) == (null)) ? undefined : gensym___175155715.propVar4)})) !== (undefined))) { - (this).__backing_propVar4!.update((initializers!.propVar4 as Set)); + this.__backing_propVar4!.update((initializers!.propVar4 as Set)); } if (((({let gensym___134530703 = initializers; (((gensym___134530703) == (null)) ? undefined : gensym___134530703.propVar5)})) !== (undefined))) { - (this).__backing_propVar5!.update((initializers!.propVar5 as Array)); + this.__backing_propVar5!.update((initializers!.propVar5 as Array)); } if (((({let gensym___211600890 = initializers; (((gensym___211600890) == (null)) ? undefined : gensym___211600890.propVar6)})) !== (undefined))) { - (this).__backing_propVar6!.update((initializers!.propVar6 as Array)); + this.__backing_propVar6!.update((initializers!.propVar6 as Array)); } if (((({let gensym___124229427 = initializers; (((gensym___124229427) == (null)) ? undefined : gensym___124229427.propVar7)})) !== (undefined))) { - (this).__backing_propVar7!.update((initializers!.propVar7 as Array)); + this.__backing_propVar7!.update((initializers!.propVar7 as Array)); } if (((({let gensym___248056380 = initializers; (((gensym___248056380) == (null)) ? undefined : gensym___248056380.propVar8)})) !== (undefined))) { - (this).__backing_propVar8!.update((initializers!.propVar8 as ((sr: string)=> void))); + this.__backing_propVar8!.update((initializers!.propVar8 as ((sr: string)=> void))); } if (((({let gensym___55399278 = initializers; (((gensym___55399278) == (null)) ? undefined : gensym___55399278.propVar9)})) !== (undefined))) { - (this).__backing_propVar9!.update((initializers!.propVar9 as Date)); + this.__backing_propVar9!.update((initializers!.propVar9 as Date)); } if (((({let gensym___125042885 = initializers; (((gensym___125042885) == (null)) ? undefined : gensym___125042885.propVar10)})) !== (undefined))) { - (this).__backing_propVar10!.update((initializers!.propVar10 as Map)); + this.__backing_propVar10!.update((initializers!.propVar10 as Map)); } if (((({let gensym___2015283 = initializers; (((gensym___2015283) == (null)) ? undefined : gensym___2015283.propVar11)})) !== (undefined))) { - (this).__backing_propVar11!.update((initializers!.propVar11 as string | number)); + this.__backing_propVar11!.update((initializers!.propVar11 as string | number)); } if (((({let gensym___39009414 = initializers; (((gensym___39009414) == (null)) ? undefined : gensym___39009414.propVar12)})) !== (undefined))) { - (this).__backing_propVar12!.update((initializers!.propVar12 as Set | Per)); + this.__backing_propVar12!.update((initializers!.propVar12 as Set | Per)); } } private __backing_propVar1?: PropDecoratedVariable; public get propVar1(): Per { - return (this).__backing_propVar1!.get(); + return this.__backing_propVar1!.get(); } public set propVar1(value: Per) { - (this).__backing_propVar1!.set(value); + this.__backing_propVar1!.set(value); } private __backing_propVar2?: PropDecoratedVariable>; public get propVar2(): Array { - return (this).__backing_propVar2!.get(); + return this.__backing_propVar2!.get(); } public set propVar2(value: Array) { - (this).__backing_propVar2!.set(value); + this.__backing_propVar2!.set(value); } private __backing_propVar3?: PropDecoratedVariable; public get propVar3(): PropType { - return (this).__backing_propVar3!.get(); + return this.__backing_propVar3!.get(); } public set propVar3(value: PropType) { - (this).__backing_propVar3!.set(value); + this.__backing_propVar3!.set(value); } private __backing_propVar4?: PropDecoratedVariable>; public get propVar4(): Set { - return (this).__backing_propVar4!.get(); + return this.__backing_propVar4!.get(); } public set propVar4(value: Set) { - (this).__backing_propVar4!.set(value); + this.__backing_propVar4!.set(value); } private __backing_propVar5?: PropDecoratedVariable>; public get propVar5(): Array { - return (this).__backing_propVar5!.get(); + return this.__backing_propVar5!.get(); } public set propVar5(value: Array) { - (this).__backing_propVar5!.set(value); + this.__backing_propVar5!.set(value); } private __backing_propVar6?: PropDecoratedVariable>; public get propVar6(): Array { - return (this).__backing_propVar6!.get(); + return this.__backing_propVar6!.get(); } public set propVar6(value: Array) { - (this).__backing_propVar6!.set(value); + this.__backing_propVar6!.set(value); } private __backing_propVar7?: PropDecoratedVariable>; public get propVar7(): Array { - return (this).__backing_propVar7!.get(); + return this.__backing_propVar7!.get(); } public set propVar7(value: Array) { - (this).__backing_propVar7!.set(value); + this.__backing_propVar7!.set(value); } private __backing_propVar8?: PropDecoratedVariable<((sr: string)=> void)>; public get propVar8(): ((sr: string)=> void) { - return (this).__backing_propVar8!.get(); + return this.__backing_propVar8!.get(); } public set propVar8(value: ((sr: string)=> void)) { - (this).__backing_propVar8!.set(value); + this.__backing_propVar8!.set(value); } private __backing_propVar9?: PropDecoratedVariable; public get propVar9(): Date { - return (this).__backing_propVar9!.get(); + return this.__backing_propVar9!.get(); } public set propVar9(value: Date) { - (this).__backing_propVar9!.set(value); + this.__backing_propVar9!.set(value); } private __backing_propVar10?: PropDecoratedVariable>; public get propVar10(): Map { - return (this).__backing_propVar10!.get(); + return this.__backing_propVar10!.get(); } public set propVar10(value: Map) { - (this).__backing_propVar10!.set(value); + this.__backing_propVar10!.set(value); } private __backing_propVar11?: PropDecoratedVariable; public get propVar11(): string | number { - return (this).__backing_propVar11!.get(); + return this.__backing_propVar11!.get(); } public set propVar11(value: string | number) { - (this).__backing_propVar11!.set(value); + this.__backing_propVar11!.set(value); } private __backing_propVar12?: PropDecoratedVariable | Per>; public get propVar12(): Set | Per { - return (this).__backing_propVar12!.get(); + return this.__backing_propVar12!.get(); } public set propVar12(value: Set | Per) { - (this).__backing_propVar12!.set(value); + this.__backing_propVar12!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts index 71b40bf8c..0809c2d46 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts @@ -53,42 +53,42 @@ function main() {} @Component({freezeWhenInactive:false}) final class CountDownComponent extends CustomComponent { public __initializeStruct(initializers: __Options_CountDownComponent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_count = new PropDecoratedVariable("count", ((({let gensym___58710805 = initializers; + this.__backing_count = new PropDecoratedVariable("count", ((({let gensym___58710805 = initializers; (((gensym___58710805) == (null)) ? undefined : gensym___58710805.count)})) ?? (0))); - (this).__backing_costOfOneAttempt = ((({let gensym___88948111 = initializers; + this.__backing_costOfOneAttempt = ((({let gensym___88948111 = initializers; (((gensym___88948111) == (null)) ? undefined : gensym___88948111.costOfOneAttempt)})) ?? (1)); } public __updateStruct(initializers: __Options_CountDownComponent | undefined): void { if (((({let gensym___188547633 = initializers; (((gensym___188547633) == (null)) ? undefined : gensym___188547633.count)})) !== (undefined))) { - (this).__backing_count!.update((initializers!.count as number)); + this.__backing_count!.update((initializers!.count as number)); } } private __backing_count?: PropDecoratedVariable; public get count(): number { - return (this).__backing_count!.get(); + return this.__backing_count!.get(); } public set count(value: number) { - (this).__backing_count!.set(value); + this.__backing_count!.set(value); } private __backing_costOfOneAttempt?: number; public get costOfOneAttempt(): number { - return ((this).__backing_costOfOneAttempt as number); + return (this.__backing_costOfOneAttempt as number); } public set costOfOneAttempt(value: number) { - (this).__backing_costOfOneAttempt = value; + this.__backing_costOfOneAttempt = value; } @memo() public _build(@memo() style: ((instance: CountDownComponent)=> CountDownComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CountDownComponent | undefined): void { Column(undefined, undefined, (() => { - if ((((this).count) > (0))) { - Text(undefined, (((("You have") + ((this).count))) + ("Nuggets left")), undefined, undefined); + if (((this.count) > (0))) { + Text(undefined, (((("You have") + (this.count))) + ("Nuggets left")), undefined, undefined); } else { Text(undefined, "Game over!", undefined, undefined); } Button(@memo() ((instance: UIButtonAttribute): void => { instance.onClick(((e: ClickEvent) => { - (this).count -= (this).costOfOneAttempt; + this.count -= this.costOfOneAttempt; })); return; }), "Try again", undefined, undefined); @@ -99,36 +99,36 @@ function main() {} @Component({freezeWhenInactive:false}) final class ParentComponent extends CustomComponent { public __initializeStruct(initializers: __Options_ParentComponent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_countDownStartValue = new StateDecoratedVariable("countDownStartValue", ((({let gensym___249912438 = initializers; + this.__backing_countDownStartValue = new StateDecoratedVariable("countDownStartValue", ((({let gensym___249912438 = initializers; (((gensym___249912438) == (null)) ? undefined : gensym___249912438.countDownStartValue)})) ?? (10))); } public __updateStruct(initializers: __Options_ParentComponent | undefined): void {} private __backing_countDownStartValue?: StateDecoratedVariable; public get countDownStartValue(): number { - return (this).__backing_countDownStartValue!.get(); + return this.__backing_countDownStartValue!.get(); } public set countDownStartValue(value: number) { - (this).__backing_countDownStartValue!.set(value); + this.__backing_countDownStartValue!.set(value); } @memo() public _build(@memo() style: ((instance: ParentComponent)=> ParentComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ParentComponent | undefined): void { Column(undefined, undefined, (() => { - Text(undefined, (((("Grant") + ((this).countDownStartValue))) + ("nuggets to play.")), undefined, undefined); + Text(undefined, (((("Grant") + (this.countDownStartValue))) + ("nuggets to play.")), undefined, undefined); Button(@memo() ((instance: UIButtonAttribute): void => { instance.onClick(((e: ClickEvent) => { - (this).countDownStartValue += 1; + this.countDownStartValue += 1; })); return; }), "+1 - Nuggets in New Game", undefined, undefined); Button(@memo() ((instance: UIButtonAttribute): void => { instance.onClick(((e: ClickEvent) => { - (this).countDownStartValue -= 1; + this.countDownStartValue -= 1; })); return; }), "-1 - Nuggets in New Game", undefined, undefined); CountDownComponent._instantiateImpl(undefined, (() => { return new CountDownComponent(); }), ({ - count: (this).countDownStartValue, + count: this.countDownStartValue, costOfOneAttempt: 2, } as __Options_CountDownComponent), undefined, undefined); })); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts index d696b4a79..9f5787762 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts @@ -49,79 +49,79 @@ function main() {} @Component({freezeWhenInactive:false}) final class Ancestors extends CustomComponent { public __initializeStruct(initializers: __Options_Ancestors | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_count = (this).addProvidedVar("count", "count", ((({let gensym___58710805 = initializers; + this.__backing_count = this.addProvidedVar("count", "count", ((({let gensym___58710805 = initializers; (((gensym___58710805) == (null)) ? undefined : gensym___58710805.count)})) ?? ("Child0")), false); - (this).__backing_count1 = (this).addProvidedVar("count1", "prov1", ((({let gensym___84874570 = initializers; + this.__backing_count1 = this.addProvidedVar("count1", "prov1", ((({let gensym___84874570 = initializers; (((gensym___84874570) == (null)) ? undefined : gensym___84874570.count1)})) ?? ("Child1")), false); - (this).__backing_count2 = (this).addProvidedVar("count2", "prov2", ((({let gensym___124037738 = initializers; + this.__backing_count2 = this.addProvidedVar("count2", "prov2", ((({let gensym___124037738 = initializers; (((gensym___124037738) == (null)) ? undefined : gensym___124037738.count2)})) ?? ("Child2")), false); - (this).__backing_count3 = (this).addProvidedVar("count3", "prov3", ((({let gensym___199202238 = initializers; + this.__backing_count3 = this.addProvidedVar("count3", "prov3", ((({let gensym___199202238 = initializers; (((gensym___199202238) == (null)) ? undefined : gensym___199202238.count3)})) ?? ("Child3")), true); - (this).__backing_count4 = (this).addProvidedVar("count4", "count4", ((({let gensym___4359740 = initializers; + this.__backing_count4 = this.addProvidedVar("count4", "count4", ((({let gensym___4359740 = initializers; (((gensym___4359740) == (null)) ? undefined : gensym___4359740.count4)})) ?? ("Child4")), false); - (this).__backing_count5 = (this).addProvidedVar("count5", "count5", ((({let gensym___208755050 = initializers; + this.__backing_count5 = this.addProvidedVar("count5", "count5", ((({let gensym___208755050 = initializers; (((gensym___208755050) == (null)) ? undefined : gensym___208755050.count5)})) ?? ("Child5")), true); - (this).__backing_count6 = (this).addProvidedVar("count6", "", ((({let gensym___37571585 = initializers; + this.__backing_count6 = this.addProvidedVar("count6", "", ((({let gensym___37571585 = initializers; (((gensym___37571585) == (null)) ? undefined : gensym___37571585.count6)})) ?? ("Child6")), true); - (this).__backing_count7 = (this).addProvidedVar("count7", "", ((({let gensym___2162781 = initializers; + this.__backing_count7 = this.addProvidedVar("count7", "", ((({let gensym___2162781 = initializers; (((gensym___2162781) == (null)) ? undefined : gensym___2162781.count7)})) ?? ("Child7")), false); } public __updateStruct(initializers: __Options_Ancestors | undefined): void {} private __backing_count?: ProvideDecoratedVariable; public get count(): string | undefined { - return (this).__backing_count!.get(); + return this.__backing_count!.get(); } public set count(value: string | undefined) { - (this).__backing_count!.set(value); + this.__backing_count!.set(value); } private __backing_count1?: ProvideDecoratedVariable; public get count1(): string | undefined { - return (this).__backing_count1!.get(); + return this.__backing_count1!.get(); } public set count1(value: string | undefined) { - (this).__backing_count1!.set(value); + this.__backing_count1!.set(value); } private __backing_count2?: ProvideDecoratedVariable; public get count2(): string | undefined { - return (this).__backing_count2!.get(); + return this.__backing_count2!.get(); } public set count2(value: string | undefined) { - (this).__backing_count2!.set(value); + this.__backing_count2!.set(value); } private __backing_count3?: ProvideDecoratedVariable; public get count3(): string | undefined { - return (this).__backing_count3!.get(); + return this.__backing_count3!.get(); } public set count3(value: string | undefined) { - (this).__backing_count3!.set(value); + this.__backing_count3!.set(value); } private __backing_count4?: ProvideDecoratedVariable; public get count4(): string | undefined { - return (this).__backing_count4!.get(); + return this.__backing_count4!.get(); } public set count4(value: string | undefined) { - (this).__backing_count4!.set(value); + this.__backing_count4!.set(value); } private __backing_count5?: ProvideDecoratedVariable; public get count5(): string | undefined { - return (this).__backing_count5!.get(); + return this.__backing_count5!.get(); } public set count5(value: string | undefined) { - (this).__backing_count5!.set(value); + this.__backing_count5!.set(value); } private __backing_count6?: ProvideDecoratedVariable; public get count6(): string | undefined { - return (this).__backing_count6!.get(); + return this.__backing_count6!.get(); } public set count6(value: string | undefined) { - (this).__backing_count6!.set(value); + this.__backing_count6!.set(value); } private __backing_count7?: ProvideDecoratedVariable; public get count7(): string | undefined { - return (this).__backing_count7!.get(); + return this.__backing_count7!.get(); } public set count7(value: string | undefined) { - (this).__backing_count7!.set(value); + this.__backing_count7!.set(value); } @memo() public _build(@memo() style: ((instance: Ancestors)=> Ancestors) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Ancestors | undefined): void {} public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts index 92e8579d7..dffbb429f 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts @@ -49,52 +49,52 @@ function main() {} @Component({freezeWhenInactive:false}) final class PropParent extends CustomComponent { public __initializeStruct(initializers: __Options_PropParent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_provideVar1 = (this).addProvidedVar("provideVar1", "provideVar1", ((({let gensym___181030638 = initializers; + this.__backing_provideVar1 = this.addProvidedVar("provideVar1", "provideVar1", ((({let gensym___181030638 = initializers; (((gensym___181030638) == (null)) ? undefined : gensym___181030638.provideVar1)})) ?? ("propVar1")), false); - (this).__backing_provideVar2 = (this).addProvidedVar("provideVar2", "provideVar2", ((({let gensym___143944235 = initializers; + this.__backing_provideVar2 = this.addProvidedVar("provideVar2", "provideVar2", ((({let gensym___143944235 = initializers; (((gensym___143944235) == (null)) ? undefined : gensym___143944235.provideVar2)})) ?? (50)), false); - (this).__backing_provideVar3 = (this).addProvidedVar("provideVar3", "provideVar3", ((({let gensym___262195977 = initializers; + this.__backing_provideVar3 = this.addProvidedVar("provideVar3", "provideVar3", ((({let gensym___262195977 = initializers; (((gensym___262195977) == (null)) ? undefined : gensym___262195977.provideVar3)})) ?? (true)), false); - (this).__backing_provideVar4 = (this).addProvidedVar("provideVar4", "provideVar4", ((({let gensym___85711435 = initializers; + this.__backing_provideVar4 = this.addProvidedVar("provideVar4", "provideVar4", ((({let gensym___85711435 = initializers; (((gensym___85711435) == (null)) ? undefined : gensym___85711435.provideVar4)})) ?? (undefined)), false); - (this).__backing_provideVar5 = (this).addProvidedVar("provideVar5", "provideVar5", ((({let gensym___139253630 = initializers; + this.__backing_provideVar5 = this.addProvidedVar("provideVar5", "provideVar5", ((({let gensym___139253630 = initializers; (((gensym___139253630) == (null)) ? undefined : gensym___139253630.provideVar5)})) ?? (null)), false); } public __updateStruct(initializers: __Options_PropParent | undefined): void {} private __backing_provideVar1?: ProvideDecoratedVariable; public get provideVar1(): string { - return (this).__backing_provideVar1!.get(); + return this.__backing_provideVar1!.get(); } public set provideVar1(value: string) { - (this).__backing_provideVar1!.set(value); + this.__backing_provideVar1!.set(value); } private __backing_provideVar2?: ProvideDecoratedVariable; public get provideVar2(): number { - return (this).__backing_provideVar2!.get(); + return this.__backing_provideVar2!.get(); } public set provideVar2(value: number) { - (this).__backing_provideVar2!.set(value); + this.__backing_provideVar2!.set(value); } private __backing_provideVar3?: ProvideDecoratedVariable; public get provideVar3(): boolean { - return (this).__backing_provideVar3!.get(); + return this.__backing_provideVar3!.get(); } public set provideVar3(value: boolean) { - (this).__backing_provideVar3!.set(value); + this.__backing_provideVar3!.set(value); } private __backing_provideVar4?: ProvideDecoratedVariable; public get provideVar4(): undefined { - return (this).__backing_provideVar4!.get(); + return this.__backing_provideVar4!.get(); } public set provideVar4(value: undefined) { - (this).__backing_provideVar4!.set(value); + this.__backing_provideVar4!.set(value); } private __backing_provideVar5?: ProvideDecoratedVariable; public get provideVar5(): null { - return (this).__backing_provideVar5!.get(); + return this.__backing_provideVar5!.get(); } public set provideVar5(value: null) { - (this).__backing_provideVar5!.set(value); + this.__backing_provideVar5!.set(value); } @memo() public _build(@memo() style: ((instance: PropParent)=> PropParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_PropParent | undefined): void {} public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts index 51952cc98..6684a83fe 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts @@ -50,7 +50,7 @@ function main() {} class Per { public num: number; public constructor(num: number) { - (this).num = num; + this.num = num; } } @@ -59,7 +59,7 @@ final class PropType extends BaseEnum { private static () {} public constructor(ordinal: int, value: int) { super(value); - (this).#ordinal = ordinal; + this.#ordinal = ordinal; } public static readonly TYPE1: PropType = new PropType(0, 0); public static readonly TYPE2: PropType = new PropType(1, 1); @@ -69,7 +69,7 @@ final class PropType extends BaseEnum { private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; private static readonly #ItemsArray: PropType[] = [PropType.TYPE1, PropType.TYPE2, PropType.TYPE3]; public getName(): String { - return PropType.#NamesArray[(this).#ordinal]; + return PropType.#NamesArray[this.#ordinal]; } public static getValueOf(name: String): PropType { for (let i = 0;((i) < (PropType.#NamesArray.length));(++i)) { @@ -88,16 +88,16 @@ final class PropType extends BaseEnum { throw new Error((("No enum PropType with value ") + (value))); } public valueOf(): int { - return PropType.#ValuesArray[(this).#ordinal]; + return PropType.#ValuesArray[this.#ordinal]; } public toString(): String { - return PropType.#StringValuesArray[(this).#ordinal]; + return PropType.#StringValuesArray[this.#ordinal]; } public static values(): PropType[] { return PropType.#ItemsArray; } public getOrdinal(): int { - return (this).#ordinal; + return this.#ordinal; } public static $_get(e: PropType): String { return e.getName(); @@ -106,115 +106,115 @@ final class PropType extends BaseEnum { @Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_provideVar1 = (this).addProvidedVar("provideVar1", "provideVar1", ((({let gensym___181030638 = initializers; + this.__backing_provideVar1 = this.addProvidedVar("provideVar1", "provideVar1", ((({let gensym___181030638 = initializers; (((gensym___181030638) == (null)) ? undefined : gensym___181030638.provideVar1)})) ?? (new Per(6))), false); - (this).__backing_provideVar2 = (this).addProvidedVar>("provideVar2", "provideVar2", ((({let gensym___143944235 = initializers; + this.__backing_provideVar2 = this.addProvidedVar>("provideVar2", "provideVar2", ((({let gensym___143944235 = initializers; (((gensym___143944235) == (null)) ? undefined : gensym___143944235.provideVar2)})) ?? (new Array(3, 6, 8))), false); - (this).__backing_provideVar3 = (this).addProvidedVar("provideVar3", "provideVar3", ((({let gensym___262195977 = initializers; + this.__backing_provideVar3 = this.addProvidedVar("provideVar3", "provideVar3", ((({let gensym___262195977 = initializers; (((gensym___262195977) == (null)) ? undefined : gensym___262195977.provideVar3)})) ?? (PropType.TYPE3)), false); - (this).__backing_provideVar4 = (this).addProvidedVar>("provideVar4", "provideVar4", ((({let gensym___85711435 = initializers; + this.__backing_provideVar4 = this.addProvidedVar>("provideVar4", "provideVar4", ((({let gensym___85711435 = initializers; (((gensym___85711435) == (null)) ? undefined : gensym___85711435.provideVar4)})) ?? (new Set(new Array("aa", "bb")))), false); - (this).__backing_provideVar5 = (this).addProvidedVar>("provideVar5", "provideVar5", ((({let gensym___139253630 = initializers; + this.__backing_provideVar5 = this.addProvidedVar>("provideVar5", "provideVar5", ((({let gensym___139253630 = initializers; (((gensym___139253630) == (null)) ? undefined : gensym___139253630.provideVar5)})) ?? ([true, false])), false); - (this).__backing_provideVar6 = (this).addProvidedVar>("provideVar6", "provideVar6", ((({let gensym___146872112 = initializers; + this.__backing_provideVar6 = this.addProvidedVar>("provideVar6", "provideVar6", ((({let gensym___146872112 = initializers; (((gensym___146872112) == (null)) ? undefined : gensym___146872112.provideVar6)})) ?? (new Array(new Per(7), new Per(11)))), false); - (this).__backing_provideVar7 = (this).addProvidedVar>("provideVar7", "provideVar7", ((({let gensym___174412117 = initializers; + this.__backing_provideVar7 = this.addProvidedVar>("provideVar7", "provideVar7", ((({let gensym___174412117 = initializers; (((gensym___174412117) == (null)) ? undefined : gensym___174412117.provideVar7)})) ?? ([new Per(7), new Per(11)])), false); - (this).__backing_provideVar8 = (this).addProvidedVar<((sr: string)=> void)>("provideVar8", "provideVar8", ((({let gensym___253467853 = initializers; + this.__backing_provideVar8 = this.addProvidedVar<((sr: string)=> void)>("provideVar8", "provideVar8", ((({let gensym___253467853 = initializers; (((gensym___253467853) == (null)) ? undefined : gensym___253467853.provideVar8)})) ?? (((sr: string) => {}))), false); - (this).__backing_provideVar9 = (this).addProvidedVar("provideVar9", "provideVar9", ((({let gensym___179115605 = initializers; + this.__backing_provideVar9 = this.addProvidedVar("provideVar9", "provideVar9", ((({let gensym___179115605 = initializers; (((gensym___179115605) == (null)) ? undefined : gensym___179115605.provideVar9)})) ?? (new Date("2025-4-23"))), false); - (this).__backing_provideVar10 = (this).addProvidedVar>("provideVar10", "provideVar10", ((({let gensym___209671248 = initializers; + this.__backing_provideVar10 = this.addProvidedVar>("provideVar10", "provideVar10", ((({let gensym___209671248 = initializers; (((gensym___209671248) == (null)) ? undefined : gensym___209671248.provideVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]]))), false); - (this).__backing_provideVar11 = (this).addProvidedVar("provideVar11", "provideVar11", ((({let gensym___150211849 = initializers; + this.__backing_provideVar11 = this.addProvidedVar("provideVar11", "provideVar11", ((({let gensym___150211849 = initializers; (((gensym___150211849) == (null)) ? undefined : gensym___150211849.provideVar11)})) ?? (0.0)), false); - (this).__backing_provideVar12 = (this).addProvidedVar | Per>("provideVar12", "provideVar12", ((({let gensym___256025818 = initializers; + this.__backing_provideVar12 = this.addProvidedVar | Per>("provideVar12", "provideVar12", ((({let gensym___256025818 = initializers; (((gensym___256025818) == (null)) ? undefined : gensym___256025818.provideVar12)})) ?? (new Per(6))), false); } public __updateStruct(initializers: __Options_Parent | undefined): void {} private __backing_provideVar1?: ProvideDecoratedVariable; public get provideVar1(): Per { - return (this).__backing_provideVar1!.get(); + return this.__backing_provideVar1!.get(); } public set provideVar1(value: Per) { - (this).__backing_provideVar1!.set(value); + this.__backing_provideVar1!.set(value); } private __backing_provideVar2?: ProvideDecoratedVariable>; public get provideVar2(): Array { - return (this).__backing_provideVar2!.get(); + return this.__backing_provideVar2!.get(); } public set provideVar2(value: Array) { - (this).__backing_provideVar2!.set(value); + this.__backing_provideVar2!.set(value); } private __backing_provideVar3?: ProvideDecoratedVariable; public get provideVar3(): PropType { - return (this).__backing_provideVar3!.get(); + return this.__backing_provideVar3!.get(); } public set provideVar3(value: PropType) { - (this).__backing_provideVar3!.set(value); + this.__backing_provideVar3!.set(value); } private __backing_provideVar4?: ProvideDecoratedVariable>; public get provideVar4(): Set { - return (this).__backing_provideVar4!.get(); + return this.__backing_provideVar4!.get(); } public set provideVar4(value: Set) { - (this).__backing_provideVar4!.set(value); + this.__backing_provideVar4!.set(value); } private __backing_provideVar5?: ProvideDecoratedVariable>; public get provideVar5(): Array { - return (this).__backing_provideVar5!.get(); + return this.__backing_provideVar5!.get(); } public set provideVar5(value: Array) { - (this).__backing_provideVar5!.set(value); + this.__backing_provideVar5!.set(value); } private __backing_provideVar6?: ProvideDecoratedVariable>; public get provideVar6(): Array { - return (this).__backing_provideVar6!.get(); + return this.__backing_provideVar6!.get(); } public set provideVar6(value: Array) { - (this).__backing_provideVar6!.set(value); + this.__backing_provideVar6!.set(value); } private __backing_provideVar7?: ProvideDecoratedVariable>; public get provideVar7(): Array { - return (this).__backing_provideVar7!.get(); + return this.__backing_provideVar7!.get(); } public set provideVar7(value: Array) { - (this).__backing_provideVar7!.set(value); + this.__backing_provideVar7!.set(value); } private __backing_provideVar8?: ProvideDecoratedVariable<((sr: string)=> void)>; public get provideVar8(): ((sr: string)=> void) { - return (this).__backing_provideVar8!.get(); + return this.__backing_provideVar8!.get(); } public set provideVar8(value: ((sr: string)=> void)) { - (this).__backing_provideVar8!.set(value); + this.__backing_provideVar8!.set(value); } private __backing_provideVar9?: ProvideDecoratedVariable; public get provideVar9(): Date { - return (this).__backing_provideVar9!.get(); + return this.__backing_provideVar9!.get(); } public set provideVar9(value: Date) { - (this).__backing_provideVar9!.set(value); + this.__backing_provideVar9!.set(value); } private __backing_provideVar10?: ProvideDecoratedVariable>; public get provideVar10(): Map { - return (this).__backing_provideVar10!.get(); + return this.__backing_provideVar10!.get(); } public set provideVar10(value: Map) { - (this).__backing_provideVar10!.set(value); + this.__backing_provideVar10!.set(value); } private __backing_provideVar11?: ProvideDecoratedVariable; public get provideVar11(): string | number { - return (this).__backing_provideVar11!.get(); + return this.__backing_provideVar11!.get(); } public set provideVar11(value: string | number) { - (this).__backing_provideVar11!.set(value); + this.__backing_provideVar11!.set(value); } private __backing_provideVar12?: ProvideDecoratedVariable | Per>; public get provideVar12(): Set | Per { - return (this).__backing_provideVar12!.get(); + return this.__backing_provideVar12!.get(); } public set provideVar12(value: Set | Per) { - (this).__backing_provideVar12!.set(value); + this.__backing_provideVar12!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts index dc235c38c..ad9e6798b 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts @@ -55,25 +55,25 @@ function main() {} @Component({freezeWhenInactive:false}) final class ResourceComponent extends CustomComponent { public __initializeStruct(initializers: __Options_ResourceComponent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_str1 = ((({let gensym___147578113 = initializers; + this.__backing_str1 = ((({let gensym___147578113 = initializers; (((gensym___147578113) == (null)) ? undefined : gensym___147578113.str1)})) ?? ("app.media.ri")); - (this).__backing_str2 = ((({let gensym___220149772 = initializers; + this.__backing_str2 = ((({let gensym___220149772 = initializers; (((gensym___220149772) == (null)) ? undefined : gensym___220149772.str2)})) ?? ("app.photo2.png")); } public __updateStruct(initializers: __Options_ResourceComponent | undefined): void {} private __backing_str1?: string; public get str1(): string { - return ((this).__backing_str1 as string); + return (this.__backing_str1 as string); } public set str1(value: string) { - (this).__backing_str1 = value; + this.__backing_str1 = value; } private __backing_str2?: string; public get str2(): string { - return ((this).__backing_str2 as string); + return (this.__backing_str2 as string); } public set str2(value: string) { - (this).__backing_str2 = value; + this.__backing_str2 = value; } @memo() public _build(@memo() style: ((instance: ResourceComponent)=> ResourceComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ResourceComponent | undefined): void { @@ -83,8 +83,8 @@ function main() {} TextInput(undefined, { text: _r("", "", "app.string.input_content"), }, undefined); - Text(undefined, _r("", "", (this).str1), undefined, undefined); - Text(undefined, _r("", "", (this).str2), undefined, undefined); + Text(undefined, _r("", "", this.str1), undefined, undefined); + Text(undefined, _r("", "", this.str2), undefined, undefined); Select(undefined, new Array({ value: "aaa", icon: _r("", "", "app.media.selection"), diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts index e84095778..741751b9f 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts @@ -54,31 +54,31 @@ i = _r("", "", "app.string.app_name"); @Component({freezeWhenInactive:false}) final class ResourceComponent extends CustomComponent { public __initializeStruct(initializers: __Options_ResourceComponent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_str = ((({let gensym___42103502 = initializers; + this.__backing_str = ((({let gensym___42103502 = initializers; (((gensym___42103502) == (null)) ? undefined : gensym___42103502.str)})) ?? (_r("", "", "app.string.app_name"))); - (this).__backing_icon = ((({let gensym___38135554 = initializers; + this.__backing_icon = ((({let gensym___38135554 = initializers; (((gensym___38135554) == (null)) ? undefined : gensym___38135554.icon)})) ?? (_rawfile("", "", "app.photo.png"))); } public __updateStruct(initializers: __Options_ResourceComponent | undefined): void {} private __backing_str?: Resource; public get str(): Resource { - return ((this).__backing_str as Resource); + return (this.__backing_str as Resource); } public set str(value: Resource) { - (this).__backing_str = value; + this.__backing_str = value; } private __backing_icon?: Resource; public get icon(): Resource { - return ((this).__backing_icon as Resource); + return (this.__backing_icon as Resource); } public set icon(value: Resource) { - (this).__backing_icon = value; + this.__backing_icon = value; } @memo() public _build(@memo() style: ((instance: ResourceComponent)=> ResourceComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ResourceComponent | undefined): void { Column(undefined, undefined, (() => { - Text(undefined, (this).str, undefined, undefined); + Text(undefined, this.str, undefined, undefined); Text(undefined, i, undefined, undefined); - Image(undefined, (this).icon, undefined, undefined); + Image(undefined, this.icon, undefined, undefined); })); } public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts index aead2d3df..0589b25ab 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts @@ -80,9 +80,9 @@ function main() {} public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { if (({let gensym___98468840 = initializers; (((gensym___98468840) == (null)) ? undefined : gensym___98468840.__backing_num)})) { - (this).__backing_num = new LinkDecoratedVariable("num", initializers!.__backing_num!); + this.__backing_num = new LinkDecoratedVariable("num", initializers!.__backing_num!); }; - (this).__backing_num1 = new StateDecoratedVariable("num1", ((({let gensym___33833641 = initializers; + this.__backing_num1 = new StateDecoratedVariable("num1", ((({let gensym___33833641 = initializers; (((gensym___33833641) == (null)) ? undefined : gensym___33833641.num1)})) ?? (2))); } @@ -99,21 +99,21 @@ function main() {} private __backing_num?: LinkDecoratedVariable; public get num(): number { - return (this).__backing_num!.get(); + return this.__backing_num!.get(); } public set num(value: number) { - (this).__backing_num!.set(value); + this.__backing_num!.set(value); } private __backing_num1?: StateDecoratedVariable; public get num1(): number { - return (this).__backing_num1!.get(); + return this.__backing_num1!.get(); } public set num1(value: number) { - (this).__backing_num1!.set(value); + this.__backing_num1!.set(value); } @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts index 29ab50400..873738ced 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts @@ -67,14 +67,14 @@ class Message { public value: string | undefined; public constructor(value: string) { - (this).value = value; + this.value = value; } } @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_display = new StateDecoratedVariable("display", ((({let gensym___83835842 = initializers; + this.__backing_display = new StateDecoratedVariable("display", ((({let gensym___83835842 = initializers; (((gensym___83835842) == (null)) ? undefined : gensym___83835842.display)})) ?? (true))); } @@ -83,11 +83,11 @@ class Message { private __backing_display?: StateDecoratedVariable; public get display(): boolean { - return (this).__backing_display!.get(); + return this.__backing_display!.get(); } public set display(value: boolean) { - (this).__backing_display!.set(value); + this.__backing_display!.set(value); } @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { @@ -97,11 +97,11 @@ class Message { }), undefined, (() => { Button(@memo() ((instance: UIButtonAttribute): void => { instance.fontSize(30).fontWeight(FontWeight.Bold).onClick(((e: ClickEvent) => { - (this).display = !((this).display); + this.display = !(this.display); })); return; }), "Hello", undefined, undefined); - if ((this).display) { + if (this.display) { Child._instantiateImpl(undefined, (() => { return new Child(); }), ({ @@ -117,7 +117,7 @@ class Message { @Reusable() @Component({freezeWhenInactive:false}) final class Child extends CustomComponent { public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_message = new StateDecoratedVariable("message", ((({let gensym___91869411 = initializers; + this.__backing_message = new StateDecoratedVariable("message", ((({let gensym___91869411 = initializers; (((gensym___91869411) == (null)) ? undefined : gensym___91869411.message)})) ?? (new Message("AboutToReuse")))); } @@ -133,11 +133,11 @@ class Message { private __backing_message?: StateDecoratedVariable; public get message(): Message { - return (this).__backing_message!.get(); + return this.__backing_message!.get(); } public set message(value: Message) { - (this).__backing_message!.set(value); + this.__backing_message!.set(value); } public aboutToReuse(params: Record) { @@ -152,7 +152,7 @@ class Message { Text(@memo() ((instance: UITextAttribute): void => { instance.fontSize(30); return; - }), (this).message.value, undefined, undefined); + }), this.message.value, undefined, undefined); })); } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts index 77e81ddc0..96d03ea4b 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts @@ -49,52 +49,52 @@ function main() {} @Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_stateVar1 = new StateDecoratedVariable("stateVar1", ((({let gensym___213853607 = initializers; + this.__backing_stateVar1 = new StateDecoratedVariable("stateVar1", ((({let gensym___213853607 = initializers; (((gensym___213853607) == (null)) ? undefined : gensym___213853607.stateVar1)})) ?? ("stateVar1"))); - (this).__backing_stateVar2 = new StateDecoratedVariable("stateVar2", ((({let gensym___113574154 = initializers; + this.__backing_stateVar2 = new StateDecoratedVariable("stateVar2", ((({let gensym___113574154 = initializers; (((gensym___113574154) == (null)) ? undefined : gensym___113574154.stateVar2)})) ?? (50))); - (this).__backing_stateVar3 = new StateDecoratedVariable("stateVar3", ((({let gensym___166994972 = initializers; + this.__backing_stateVar3 = new StateDecoratedVariable("stateVar3", ((({let gensym___166994972 = initializers; (((gensym___166994972) == (null)) ? undefined : gensym___166994972.stateVar3)})) ?? (true))); - (this).__backing_stateVar4 = new StateDecoratedVariable("stateVar4", ((({let gensym___148024261 = initializers; + this.__backing_stateVar4 = new StateDecoratedVariable("stateVar4", ((({let gensym___148024261 = initializers; (((gensym___148024261) == (null)) ? undefined : gensym___148024261.stateVar4)})) ?? (undefined))); - (this).__backing_stateVar5 = new StateDecoratedVariable("stateVar5", ((({let gensym___99384342 = initializers; + this.__backing_stateVar5 = new StateDecoratedVariable("stateVar5", ((({let gensym___99384342 = initializers; (((gensym___99384342) == (null)) ? undefined : gensym___99384342.stateVar5)})) ?? (null))); } public __updateStruct(initializers: __Options_Parent | undefined): void {} private __backing_stateVar1?: StateDecoratedVariable; public get stateVar1(): string { - return (this).__backing_stateVar1!.get(); + return this.__backing_stateVar1!.get(); } public set stateVar1(value: string) { - (this).__backing_stateVar1!.set(value); + this.__backing_stateVar1!.set(value); } private __backing_stateVar2?: StateDecoratedVariable; public get stateVar2(): number { - return (this).__backing_stateVar2!.get(); + return this.__backing_stateVar2!.get(); } public set stateVar2(value: number) { - (this).__backing_stateVar2!.set(value); + this.__backing_stateVar2!.set(value); } private __backing_stateVar3?: StateDecoratedVariable; public get stateVar3(): boolean { - return (this).__backing_stateVar3!.get(); + return this.__backing_stateVar3!.get(); } public set stateVar3(value: boolean) { - (this).__backing_stateVar3!.set(value); + this.__backing_stateVar3!.set(value); } private __backing_stateVar4?: StateDecoratedVariable; public get stateVar4(): undefined { - return (this).__backing_stateVar4!.get(); + return this.__backing_stateVar4!.get(); } public set stateVar4(value: undefined) { - (this).__backing_stateVar4!.set(value); + this.__backing_stateVar4!.set(value); } private __backing_stateVar5?: StateDecoratedVariable; public get stateVar5(): null { - return (this).__backing_stateVar5!.get(); + return this.__backing_stateVar5!.get(); } public set stateVar5(value: null) { - (this).__backing_stateVar5!.set(value); + this.__backing_stateVar5!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts index fdb92c74a..e42e34006 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts @@ -50,7 +50,7 @@ function main() {} class Per { public num: number; public constructor(num: number) { - (this).num = num; + this.num = num; } } @@ -59,7 +59,7 @@ final class StateType extends BaseEnum { private static () {} public constructor(ordinal: int, value: int) { super(value); - (this).#ordinal = ordinal; + this.#ordinal = ordinal; } public static readonly TYPE1: StateType = new StateType(0, 0); public static readonly TYPE2: StateType = new StateType(1, 1); @@ -69,7 +69,7 @@ final class StateType extends BaseEnum { private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; private static readonly #ItemsArray: StateType[] = [StateType.TYPE1, StateType.TYPE2, StateType.TYPE3]; public getName(): String { - return StateType.#NamesArray[(this).#ordinal]; + return StateType.#NamesArray[this.#ordinal]; } public static getValueOf(name: String): StateType { for (let i = 0;((i) < (StateType.#NamesArray.length));(++i)) { @@ -88,16 +88,16 @@ final class StateType extends BaseEnum { throw new Error((("No enum StateType with value ") + (value))); } public valueOf(): int { - return StateType.#ValuesArray[(this).#ordinal]; + return StateType.#ValuesArray[this.#ordinal]; } public toString(): String { - return StateType.#StringValuesArray[(this).#ordinal]; + return StateType.#StringValuesArray[this.#ordinal]; } public static values(): StateType[] { return StateType.#ItemsArray; } public getOrdinal(): int { - return (this).#ordinal; + return this.#ordinal; } public static $_get(e: StateType): String { return e.getName(); @@ -106,115 +106,115 @@ final class StateType extends BaseEnum { @Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_stateVar1 = new StateDecoratedVariable("stateVar1", ((({let gensym___213853607 = initializers; + this.__backing_stateVar1 = new StateDecoratedVariable("stateVar1", ((({let gensym___213853607 = initializers; (((gensym___213853607) == (null)) ? undefined : gensym___213853607.stateVar1)})) ?? (new Per(6)))); - (this).__backing_stateVar2 = new StateDecoratedVariable>("stateVar2", ((({let gensym___113574154 = initializers; + this.__backing_stateVar2 = new StateDecoratedVariable>("stateVar2", ((({let gensym___113574154 = initializers; (((gensym___113574154) == (null)) ? undefined : gensym___113574154.stateVar2)})) ?? (new Array(3, 6, 8)))); - (this).__backing_stateVar3 = new StateDecoratedVariable("stateVar3", ((({let gensym___166994972 = initializers; + this.__backing_stateVar3 = new StateDecoratedVariable("stateVar3", ((({let gensym___166994972 = initializers; (((gensym___166994972) == (null)) ? undefined : gensym___166994972.stateVar3)})) ?? (StateType.TYPE3))); - (this).__backing_stateVar4 = new StateDecoratedVariable>("stateVar4", ((({let gensym___148024261 = initializers; + this.__backing_stateVar4 = new StateDecoratedVariable>("stateVar4", ((({let gensym___148024261 = initializers; (((gensym___148024261) == (null)) ? undefined : gensym___148024261.stateVar4)})) ?? (new Set(new Array("aa", "bb"))))); - (this).__backing_stateVar5 = new StateDecoratedVariable>("stateVar5", ((({let gensym___99384342 = initializers; + this.__backing_stateVar5 = new StateDecoratedVariable>("stateVar5", ((({let gensym___99384342 = initializers; (((gensym___99384342) == (null)) ? undefined : gensym___99384342.stateVar5)})) ?? ([true, false]))); - (this).__backing_stateVar6 = new StateDecoratedVariable>("stateVar6", ((({let gensym___133364871 = initializers; + this.__backing_stateVar6 = new StateDecoratedVariable>("stateVar6", ((({let gensym___133364871 = initializers; (((gensym___133364871) == (null)) ? undefined : gensym___133364871.stateVar6)})) ?? (new Array(new Per(7), new Per(11))))); - (this).__backing_stateVar7 = new StateDecoratedVariable>("stateVar7", ((({let gensym___69403028 = initializers; + this.__backing_stateVar7 = new StateDecoratedVariable>("stateVar7", ((({let gensym___69403028 = initializers; (((gensym___69403028) == (null)) ? undefined : gensym___69403028.stateVar7)})) ?? ([new Per(7), new Per(11)]))); - (this).__backing_stateVar8 = new StateDecoratedVariable<((sr: string)=> void)>("stateVar8", ((({let gensym___219403122 = initializers; + this.__backing_stateVar8 = new StateDecoratedVariable<((sr: string)=> void)>("stateVar8", ((({let gensym___219403122 = initializers; (((gensym___219403122) == (null)) ? undefined : gensym___219403122.stateVar8)})) ?? (((sr: string) => {})))); - (this).__backing_stateVar9 = new StateDecoratedVariable("stateVar9", ((({let gensym___171171899 = initializers; + this.__backing_stateVar9 = new StateDecoratedVariable("stateVar9", ((({let gensym___171171899 = initializers; (((gensym___171171899) == (null)) ? undefined : gensym___171171899.stateVar9)})) ?? (new Date("2025-4-23")))); - (this).__backing_stateVar10 = new StateDecoratedVariable>("stateVar10", ((({let gensym___91651348 = initializers; + this.__backing_stateVar10 = new StateDecoratedVariable>("stateVar10", ((({let gensym___91651348 = initializers; (((gensym___91651348) == (null)) ? undefined : gensym___91651348.stateVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]])))); - (this).__backing_stateVar11 = new StateDecoratedVariable("stateVar11", ((({let gensym___56045278 = initializers; + this.__backing_stateVar11 = new StateDecoratedVariable("stateVar11", ((({let gensym___56045278 = initializers; (((gensym___56045278) == (null)) ? undefined : gensym___56045278.stateVar11)})) ?? (0.0))); - (this).__backing_stateVar12 = new StateDecoratedVariable | Per>("stateVar12", ((({let gensym___164759887 = initializers; + this.__backing_stateVar12 = new StateDecoratedVariable | Per>("stateVar12", ((({let gensym___164759887 = initializers; (((gensym___164759887) == (null)) ? undefined : gensym___164759887.stateVar12)})) ?? (new Per(6)))); } public __updateStruct(initializers: __Options_Parent | undefined): void {} private __backing_stateVar1?: StateDecoratedVariable; public get stateVar1(): Per { - return (this).__backing_stateVar1!.get(); + return this.__backing_stateVar1!.get(); } public set stateVar1(value: Per) { - (this).__backing_stateVar1!.set(value); + this.__backing_stateVar1!.set(value); } private __backing_stateVar2?: StateDecoratedVariable>; public get stateVar2(): Array { - return (this).__backing_stateVar2!.get(); + return this.__backing_stateVar2!.get(); } public set stateVar2(value: Array) { - (this).__backing_stateVar2!.set(value); + this.__backing_stateVar2!.set(value); } private __backing_stateVar3?: StateDecoratedVariable; public get stateVar3(): StateType { - return (this).__backing_stateVar3!.get(); + return this.__backing_stateVar3!.get(); } public set stateVar3(value: StateType) { - (this).__backing_stateVar3!.set(value); + this.__backing_stateVar3!.set(value); } private __backing_stateVar4?: StateDecoratedVariable>; public get stateVar4(): Set { - return (this).__backing_stateVar4!.get(); + return this.__backing_stateVar4!.get(); } public set stateVar4(value: Set) { - (this).__backing_stateVar4!.set(value); + this.__backing_stateVar4!.set(value); } private __backing_stateVar5?: StateDecoratedVariable>; public get stateVar5(): Array { - return (this).__backing_stateVar5!.get(); + return this.__backing_stateVar5!.get(); } public set stateVar5(value: Array) { - (this).__backing_stateVar5!.set(value); + this.__backing_stateVar5!.set(value); } private __backing_stateVar6?: StateDecoratedVariable>; public get stateVar6(): Array { - return (this).__backing_stateVar6!.get(); + return this.__backing_stateVar6!.get(); } public set stateVar6(value: Array) { - (this).__backing_stateVar6!.set(value); + this.__backing_stateVar6!.set(value); } private __backing_stateVar7?: StateDecoratedVariable>; public get stateVar7(): Array { - return (this).__backing_stateVar7!.get(); + return this.__backing_stateVar7!.get(); } public set stateVar7(value: Array) { - (this).__backing_stateVar7!.set(value); + this.__backing_stateVar7!.set(value); } private __backing_stateVar8?: StateDecoratedVariable<((sr: string)=> void)>; public get stateVar8(): ((sr: string)=> void) { - return (this).__backing_stateVar8!.get(); + return this.__backing_stateVar8!.get(); } public set stateVar8(value: ((sr: string)=> void)) { - (this).__backing_stateVar8!.set(value); + this.__backing_stateVar8!.set(value); } private __backing_stateVar9?: StateDecoratedVariable; public get stateVar9(): Date { - return (this).__backing_stateVar9!.get(); + return this.__backing_stateVar9!.get(); } public set stateVar9(value: Date) { - (this).__backing_stateVar9!.set(value); + this.__backing_stateVar9!.set(value); } private __backing_stateVar10?: StateDecoratedVariable>; public get stateVar10(): Map { - return (this).__backing_stateVar10!.get(); + return this.__backing_stateVar10!.get(); } public set stateVar10(value: Map) { - (this).__backing_stateVar10!.set(value); + this.__backing_stateVar10!.set(value); } private __backing_stateVar11?: StateDecoratedVariable; public get stateVar11(): string | number { - return (this).__backing_stateVar11!.get(); + return this.__backing_stateVar11!.get(); } public set stateVar11(value: string | number) { - (this).__backing_stateVar11!.set(value); + this.__backing_stateVar11!.set(value); } private __backing_stateVar12?: StateDecoratedVariable | Per>; public get stateVar12(): Set | Per { - return (this).__backing_stateVar12!.get(); + return this.__backing_stateVar12!.get(); } public set stateVar12(value: Set | Per) { - (this).__backing_stateVar12!.set(value); + this.__backing_stateVar12!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts index 406d937b5..52a438991 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts @@ -52,29 +52,29 @@ function main() {} class Per { public str: string; public constructor(str: string) { - (this).str = str; + this.str = str; } } @Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_parentVar1 = new StateDecoratedVariable("parentVar1", ((({let gensym___247315634 = initializers; + this.__backing_parentVar1 = new StateDecoratedVariable("parentVar1", ((({let gensym___247315634 = initializers; (((gensym___247315634) == (null)) ? undefined : gensym___247315634.parentVar1)})) ?? (new Per("hello")))); } public __updateStruct(initializers: __Options_Parent | undefined): void {} private __backing_parentVar1?: StateDecoratedVariable; public get parentVar1(): Per { - return (this).__backing_parentVar1!.get(); + return this.__backing_parentVar1!.get(); } public set parentVar1(value: Per) { - (this).__backing_parentVar1!.set(value); + this.__backing_parentVar1!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void { Column(undefined, undefined, (() => { Child._instantiateImpl(undefined, (() => { return new Child(); }), ({ - childVar1: (this).parentVar1, + childVar1: this.parentVar1, } as __Options_Child), undefined, undefined); })); } @@ -83,19 +83,19 @@ class Per { @Component({freezeWhenInactive:false}) final class Child extends CustomComponent { public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_childVar1 = new StateDecoratedVariable("childVar1", ((({let gensym___218939886 = initializers; + this.__backing_childVar1 = new StateDecoratedVariable("childVar1", ((({let gensym___218939886 = initializers; (((gensym___218939886) == (null)) ? undefined : gensym___218939886.childVar1)})) ?? (new Per("ccc")))); } public __updateStruct(initializers: __Options_Child | undefined): void {} private __backing_childVar1?: StateDecoratedVariable; public get childVar1(): Per { - return (this).__backing_childVar1!.get(); + return this.__backing_childVar1!.get(); } public set childVar1(value: Per) { - (this).__backing_childVar1!.set(value); + this.__backing_childVar1!.set(value); } @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - Text(undefined, (this).childVar1.str, undefined, undefined); + Text(undefined, this.childVar1.str, undefined, undefined); } public constructor() {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts index b41f7e584..7f4460286 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts @@ -66,15 +66,15 @@ class Data { public code: number; public constructor(code: number) { - (this).code = code; + this.code = code; } } @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_storageLink = new StorageLinkDecoratedVariable("PropA", "storageLink", 1) - (this).__backing_storageLinkObject = new StorageLinkDecoratedVariable("PropB", "storageLinkObject", new Data(1)) + this.__backing_storageLink = new StorageLinkDecoratedVariable("PropA", "storageLink", 1) + this.__backing_storageLinkObject = new StorageLinkDecoratedVariable("PropB", "storageLinkObject", new Data(1)) } public __updateStruct(initializers: __Options_Index | undefined): void {} @@ -82,37 +82,37 @@ class Data { private __backing_storageLink?: StorageLinkDecoratedVariable; public get storageLink(): number { - return (this).__backing_storageLink!.get(); + return this.__backing_storageLink!.get(); } public set storageLink(value: number) { - (this).__backing_storageLink!.set(value); + this.__backing_storageLink!.set(value); } private __backing_storageLinkObject?: StorageLinkDecoratedVariable; public get storageLinkObject(): Data { - return (this).__backing_storageLinkObject!.get(); + return this.__backing_storageLinkObject!.get(); } public set storageLinkObject(value: Data) { - (this).__backing_storageLinkObject!.set(value); + this.__backing_storageLinkObject!.set(value); } @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { Column(undefined, undefined, (() => { Text(@memo() ((instance: UITextAttribute): void => { instance.onClick(((e: ClickEvent) => { - (this).storageLink += 1; + this.storageLink += 1; })); return; - }), \`From AppStorage \${(this).storageLink}\`, undefined, undefined); + }), \`From AppStorage \${this.storageLink}\`, undefined, undefined); Text(@memo() ((instance: UITextAttribute): void => { instance.onClick(((e: ClickEvent) => { - (this).storageLinkObject.code += 1; + this.storageLinkObject.code += 1; })); return; - }), \`From AppStorage \${(this).storageLinkObject.code}\`, undefined, undefined); + }), \`From AppStorage \${this.storageLinkObject.code}\`, undefined, undefined); })); } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts index 25fba5eb4..dba913594 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts @@ -71,7 +71,7 @@ final class Status extends BaseEnum { public constructor(ordinal: int, value: int) { super(value); - (this).#ordinal = ordinal; + this.#ordinal = ordinal; } public static readonly Success: Status = new Status(0, 200); @@ -89,7 +89,7 @@ final class Status extends BaseEnum { private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; public getName(): String { - return Status.#NamesArray[(this).#ordinal]; + return Status.#NamesArray[this.#ordinal]; } public static getValueOf(name: String): Status { @@ -111,11 +111,11 @@ final class Status extends BaseEnum { } public valueOf(): int { - return Status.#ValuesArray[(this).#ordinal]; + return Status.#ValuesArray[this.#ordinal]; } public toString(): String { - return Status.#StringValuesArray[(this).#ordinal]; + return Status.#StringValuesArray[this.#ordinal]; } public static values(): Status[] { @@ -123,7 +123,7 @@ final class Status extends BaseEnum { } public getOrdinal(): int { - return (this).#ordinal; + return this.#ordinal; } public static $_get(e: Status): String { @@ -134,14 +134,14 @@ final class Status extends BaseEnum { @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_arrayA = new StorageLinkDecoratedVariable>("Prop1", "arrayA", [1, 2, 3]) - (this).__backing_objectA = new StorageLinkDecoratedVariable("Prop2", "objectA", {}) - (this).__backing_dateA = new StorageLinkDecoratedVariable("Prop3", "dateA", new Date("2021-08-08")) - (this).__backing_setA = new StorageLinkDecoratedVariable>("Prop4", "setA", new Set()) - (this).__backing_mapA = new StorageLinkDecoratedVariable>("Prop5", "mapA", new Map()) - (this).__backing_unionA = new StorageLinkDecoratedVariable("Prop6", "unionA", "") - (this).__backing_classA = new StorageLinkDecoratedVariable("Prop7", "classA", new Person("John")) - (this).__backing_enumA = new StorageLinkDecoratedVariable("Prop8", "enumA", Status.NotFound) + this.__backing_arrayA = new StorageLinkDecoratedVariable>("Prop1", "arrayA", [1, 2, 3]) + this.__backing_objectA = new StorageLinkDecoratedVariable("Prop2", "objectA", {}) + this.__backing_dateA = new StorageLinkDecoratedVariable("Prop3", "dateA", new Date("2021-08-08")) + this.__backing_setA = new StorageLinkDecoratedVariable>("Prop4", "setA", new Set()) + this.__backing_mapA = new StorageLinkDecoratedVariable>("Prop5", "mapA", new Map()) + this.__backing_unionA = new StorageLinkDecoratedVariable("Prop6", "unionA", "") + this.__backing_classA = new StorageLinkDecoratedVariable("Prop7", "classA", new Person("John")) + this.__backing_enumA = new StorageLinkDecoratedVariable("Prop8", "enumA", Status.NotFound) } public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} @@ -149,81 +149,81 @@ final class Status extends BaseEnum { private __backing_arrayA?: StorageLinkDecoratedVariable>; public get arrayA(): Array { - return (this).__backing_arrayA!.get(); + return this.__backing_arrayA!.get(); } public set arrayA(value: Array) { - (this).__backing_arrayA!.set(value); + this.__backing_arrayA!.set(value); } private __backing_objectA?: StorageLinkDecoratedVariable; public get objectA(): Object { - return (this).__backing_objectA!.get(); + return this.__backing_objectA!.get(); } public set objectA(value: Object) { - (this).__backing_objectA!.set(value); + this.__backing_objectA!.set(value); } private __backing_dateA?: StorageLinkDecoratedVariable; public get dateA(): Date { - return (this).__backing_dateA!.get(); + return this.__backing_dateA!.get(); } public set dateA(value: Date) { - (this).__backing_dateA!.set(value); + this.__backing_dateA!.set(value); } private __backing_setA?: StorageLinkDecoratedVariable>; public get setA(): Set { - return (this).__backing_setA!.get(); + return this.__backing_setA!.get(); } public set setA(value: Set) { - (this).__backing_setA!.set(value); + this.__backing_setA!.set(value); } private __backing_mapA?: StorageLinkDecoratedVariable>; public get mapA(): Map { - return (this).__backing_mapA!.get(); + return this.__backing_mapA!.get(); } public set mapA(value: Map) { - (this).__backing_mapA!.set(value); + this.__backing_mapA!.set(value); } private __backing_unionA?: StorageLinkDecoratedVariable; public get unionA(): string | undefined { - return (this).__backing_unionA!.get(); + return this.__backing_unionA!.get(); } public set unionA(value: string | undefined) { - (this).__backing_unionA!.set(value); + this.__backing_unionA!.set(value); } private __backing_classA?: StorageLinkDecoratedVariable; public get classA(): Person { - return (this).__backing_classA!.get(); + return this.__backing_classA!.get(); } public set classA(value: Person) { - (this).__backing_classA!.set(value); + this.__backing_classA!.set(value); } private __backing_enumA?: StorageLinkDecoratedVariable; public get enumA(): Status { - return (this).__backing_enumA!.get(); + return this.__backing_enumA!.get(); } public set enumA(value: Status) { - (this).__backing_enumA!.set(value); + this.__backing_enumA!.set(value); } @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts index da4f0e41b..27a78307e 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts @@ -59,9 +59,9 @@ function main() {} @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_numA = new StorageLinkDecoratedVariable("Prop1", "numA", 33) - (this).__backing_stringA = new StorageLinkDecoratedVariable("Prop2", "stringA", "AA") - (this).__backing_booleanA = new StorageLinkDecoratedVariable("Prop3", "booleanA", true) + this.__backing_numA = new StorageLinkDecoratedVariable("Prop1", "numA", 33) + this.__backing_stringA = new StorageLinkDecoratedVariable("Prop2", "stringA", "AA") + this.__backing_booleanA = new StorageLinkDecoratedVariable("Prop3", "booleanA", true) } public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} @@ -69,31 +69,31 @@ function main() {} private __backing_numA?: StorageLinkDecoratedVariable; public get numA(): number { - return (this).__backing_numA!.get(); + return this.__backing_numA!.get(); } public set numA(value: number) { - (this).__backing_numA!.set(value); + this.__backing_numA!.set(value); } private __backing_stringA?: StorageLinkDecoratedVariable; public get stringA(): string { - return (this).__backing_stringA!.get(); + return this.__backing_stringA!.get(); } public set stringA(value: string) { - (this).__backing_stringA!.set(value); + this.__backing_stringA!.set(value); } private __backing_booleanA?: StorageLinkDecoratedVariable; public get booleanA(): boolean { - return (this).__backing_booleanA!.get(); + return this.__backing_booleanA!.get(); } public set booleanA(value: boolean) { - (this).__backing_booleanA!.set(value); + this.__backing_booleanA!.set(value); } @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts index d1074e980..e00d66d86 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts @@ -66,15 +66,15 @@ class Data { public code: number; public constructor(code: number) { - (this).code = code; + this.code = code; } } @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_storageProp = new StoragePropDecoratedVariable("PropA", "storageProp", 1) - (this).__backing_storagePropObject = new StoragePropDecoratedVariable("PropB", "storagePropObject", new Data(1)) + this.__backing_storageProp = new StoragePropDecoratedVariable("PropA", "storageProp", 1) + this.__backing_storagePropObject = new StoragePropDecoratedVariable("PropB", "storagePropObject", new Data(1)) } public __updateStruct(initializers: __Options_Index | undefined): void {} @@ -82,37 +82,37 @@ class Data { private __backing_storageProp?: StoragePropDecoratedVariable; public get storageProp(): number { - return (this).__backing_storageProp!.get(); + return this.__backing_storageProp!.get(); } public set storageProp(value: number) { - (this).__backing_storageProp!.set(value); + this.__backing_storageProp!.set(value); } private __backing_storagePropObject?: StoragePropDecoratedVariable; public get storagePropObject(): Data { - return (this).__backing_storagePropObject!.get(); + return this.__backing_storagePropObject!.get(); } public set storagePropObject(value: Data) { - (this).__backing_storagePropObject!.set(value); + this.__backing_storagePropObject!.set(value); } @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { Column(undefined, undefined, (() => { Text(@memo() ((instance: UITextAttribute): void => { instance.onClick(((e: ClickEvent) => { - (this).storageProp += 1; + this.storageProp += 1; })); return; - }), \`From AppStorage \${(this).storageProp}\`, undefined, undefined); + }), \`From AppStorage \${this.storageProp}\`, undefined, undefined); Text(@memo() ((instance: UITextAttribute): void => { instance.onClick(((e: ClickEvent) => { - (this).storagePropObject.code += 1; + this.storagePropObject.code += 1; })); return; - }), \`From AppStorage \${(this).storagePropObject.code}\`, undefined, undefined); + }), \`From AppStorage \${this.storagePropObject.code}\`, undefined, undefined); })); } diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts index 8580f8a27..ca212c7ca 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts @@ -71,7 +71,7 @@ final class Status extends BaseEnum { public constructor(ordinal: int, value: int) { super(value); - (this).#ordinal = ordinal; + this.#ordinal = ordinal; } public static readonly Success: Status = new Status(0, 200); @@ -89,7 +89,7 @@ final class Status extends BaseEnum { private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; public getName(): String { - return Status.#NamesArray[(this).#ordinal]; + return Status.#NamesArray[this.#ordinal]; } public static getValueOf(name: String): Status { @@ -111,11 +111,11 @@ final class Status extends BaseEnum { } public valueOf(): int { - return Status.#ValuesArray[(this).#ordinal]; + return Status.#ValuesArray[this.#ordinal]; } public toString(): String { - return Status.#StringValuesArray[(this).#ordinal]; + return Status.#StringValuesArray[this.#ordinal]; } public static values(): Status[] { @@ -123,7 +123,7 @@ final class Status extends BaseEnum { } public getOrdinal(): int { - return (this).#ordinal; + return this.#ordinal; } public static $_get(e: Status): String { @@ -134,14 +134,14 @@ final class Status extends BaseEnum { @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_arrayB = new StoragePropDecoratedVariable>("Prop1", "arrayB", [1, 2, 3]) - (this).__backing_objectB = new StoragePropDecoratedVariable("Prop2", "objectB", {}) - (this).__backing_dateB = new StoragePropDecoratedVariable("Prop3", "dateB", new Date("2021-09-09")) - (this).__backing_setB = new StoragePropDecoratedVariable>("Prop4", "setB", new Set()) - (this).__backing_mapB = new StoragePropDecoratedVariable>("Prop5", "mapB", new Map()) - (this).__backing_unionB = new StoragePropDecoratedVariable("Prop6", "unionB", "") - (this).__backing_classB = new StoragePropDecoratedVariable("Prop7", "classB", new Person("Kevin")) - (this).__backing_enumB = new StoragePropDecoratedVariable("Prop8", "enumB", Status.NotFound) + this.__backing_arrayB = new StoragePropDecoratedVariable>("Prop1", "arrayB", [1, 2, 3]) + this.__backing_objectB = new StoragePropDecoratedVariable("Prop2", "objectB", {}) + this.__backing_dateB = new StoragePropDecoratedVariable("Prop3", "dateB", new Date("2021-09-09")) + this.__backing_setB = new StoragePropDecoratedVariable>("Prop4", "setB", new Set()) + this.__backing_mapB = new StoragePropDecoratedVariable>("Prop5", "mapB", new Map()) + this.__backing_unionB = new StoragePropDecoratedVariable("Prop6", "unionB", "") + this.__backing_classB = new StoragePropDecoratedVariable("Prop7", "classB", new Person("Kevin")) + this.__backing_enumB = new StoragePropDecoratedVariable("Prop8", "enumB", Status.NotFound) } public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} @@ -149,81 +149,81 @@ final class Status extends BaseEnum { private __backing_arrayB?: StoragePropDecoratedVariable>; public get arrayB(): Array { - return (this).__backing_arrayB!.get(); + return this.__backing_arrayB!.get(); } public set arrayB(value: Array) { - (this).__backing_arrayB!.set(value); + this.__backing_arrayB!.set(value); } private __backing_objectB?: StoragePropDecoratedVariable; public get objectB(): Object { - return (this).__backing_objectB!.get(); + return this.__backing_objectB!.get(); } public set objectB(value: Object) { - (this).__backing_objectB!.set(value); + this.__backing_objectB!.set(value); } private __backing_dateB?: StoragePropDecoratedVariable; public get dateB(): Date { - return (this).__backing_dateB!.get(); + return this.__backing_dateB!.get(); } public set dateB(value: Date) { - (this).__backing_dateB!.set(value); + this.__backing_dateB!.set(value); } private __backing_setB?: StoragePropDecoratedVariable>; public get setB(): Set { - return (this).__backing_setB!.get(); + return this.__backing_setB!.get(); } public set setB(value: Set) { - (this).__backing_setB!.set(value); + this.__backing_setB!.set(value); } private __backing_mapB?: StoragePropDecoratedVariable>; public get mapB(): Map { - return (this).__backing_mapB!.get(); + return this.__backing_mapB!.get(); } public set mapB(value: Map) { - (this).__backing_mapB!.set(value); + this.__backing_mapB!.set(value); } private __backing_unionB?: StoragePropDecoratedVariable; public get unionB(): string | undefined { - return (this).__backing_unionB!.get(); + return this.__backing_unionB!.get(); } public set unionB(value: string | undefined) { - (this).__backing_unionB!.set(value); + this.__backing_unionB!.set(value); } private __backing_classB?: StoragePropDecoratedVariable; public get classB(): Person { - return (this).__backing_classB!.get(); + return this.__backing_classB!.get(); } public set classB(value: Person) { - (this).__backing_classB!.set(value); + this.__backing_classB!.set(value); } private __backing_enumB?: StoragePropDecoratedVariable; public get enumB(): Status { - return (this).__backing_enumB!.get(); + return this.__backing_enumB!.get(); } public set enumB(value: Status) { - (this).__backing_enumB!.set(value); + this.__backing_enumB!.set(value); } @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts index 988da9f67..d6247f205 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts @@ -59,9 +59,9 @@ function main() {} @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_numB = new StoragePropDecoratedVariable("Prop1", "numB", 43) - (this).__backing_stringB = new StoragePropDecoratedVariable("Prop2", "stringB", "BB") - (this).__backing_booleanB = new StoragePropDecoratedVariable("Prop3", "booleanB", false) + this.__backing_numB = new StoragePropDecoratedVariable("Prop1", "numB", 43) + this.__backing_stringB = new StoragePropDecoratedVariable("Prop2", "stringB", "BB") + this.__backing_booleanB = new StoragePropDecoratedVariable("Prop3", "booleanB", false) } public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} @@ -69,31 +69,31 @@ function main() {} private __backing_numB?: StoragePropDecoratedVariable; public get numB(): number { - return (this).__backing_numB!.get(); + return this.__backing_numB!.get(); } public set numB(value: number) { - (this).__backing_numB!.set(value); + this.__backing_numB!.set(value); } private __backing_stringB?: StoragePropDecoratedVariable; public get stringB(): string { - return (this).__backing_stringB!.get(); + return this.__backing_stringB!.get(); } public set stringB(value: string) { - (this).__backing_stringB!.set(value); + this.__backing_stringB!.set(value); } private __backing_booleanB?: StoragePropDecoratedVariable; public get booleanB(): boolean { - return (this).__backing_booleanB!.get(); + return this.__backing_booleanB!.get(); } public set booleanB(value: boolean) { - (this).__backing_booleanB!.set(value); + this.__backing_booleanB!.set(value); } @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts index 53e99fe54..fbb612c70 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts @@ -91,15 +91,15 @@ function main() {} private subscribedWatches: SubscribedWatches = new SubscribedWatches(); public addWatchSubscriber(watchId: WatchIdType): void { - (this).subscribedWatches.addWatchSubscriber(watchId); + this.subscribedWatches.addWatchSubscriber(watchId); } public removeWatchSubscriber(watchId: WatchIdType): boolean { - return (this).subscribedWatches.removeWatchSubscriber(watchId); + return this.subscribedWatches.removeWatchSubscriber(watchId); } public executeOnSubscribingWatches(propertyName: string): void { - (this).subscribedWatches.executeOnSubscribingWatches(propertyName); + this.subscribedWatches.executeOnSubscribingWatches(propertyName); } public _permissibleAddRefDepth: int32 = 0; @@ -113,17 +113,17 @@ function main() {} public constructor() {} public get trackA(): string { - if ((((this)._permissibleAddRefDepth) > (0))) { - (this).__meta_trackA.addRef(); + if (((this._permissibleAddRefDepth) > (0))) { + this.__meta_trackA.addRef(); } - return (this).__backing_trackA; + return this.__backing_trackA; } public set trackA(newValue: string) { - if ((((this).__backing_trackA) !== (newValue))) { - (this).__backing_trackA = newValue; - (this).__meta_trackA.fireChange(); - (this).executeOnSubscribingWatches("trackA"); + if (((this.__backing_trackA) !== (newValue))) { + this.__backing_trackA = newValue; + this.__meta_trackA.fireChange(); + this.executeOnSubscribingWatches("trackA"); } } @@ -131,81 +131,81 @@ function main() {} @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_statevar = new StateDecoratedVariable("statevar", ((({let gensym___76198660 = initializers; + this.__backing_statevar = new StateDecoratedVariable("statevar", ((({let gensym___76198660 = initializers; (((gensym___76198660) == (null)) ? undefined : gensym___76198660.statevar)})) ?? ("Hello World")), ((_: string): void => { - (this).stateOnChange(_); + this.stateOnChange(_); })); - (this).__backing_propvar = new PropDecoratedVariable("propvar", ((({let gensym___241486692 = initializers; + this.__backing_propvar = new PropDecoratedVariable("propvar", ((({let gensym___241486692 = initializers; (((gensym___241486692) == (null)) ? undefined : gensym___241486692.propvar)})) ?? ("Hello World")), ((_: string): void => { - (this).propOnChange(_); + this.propOnChange(_); })); - (this).__backing_storagelinkvar = new StorageLinkDecoratedVariable("prop1", "storagelinkvar", "Hello World", ((_: string): void => { - (this).storageLinkOnChange(_); + this.__backing_storagelinkvar = new StorageLinkDecoratedVariable("prop1", "storagelinkvar", "Hello World", ((_: string): void => { + this.storageLinkOnChange(_); })) - (this).__backing_storagepropvar = new StoragePropDecoratedVariable("prop2", "storagepropvar", "Hello World", ((_: string): void => { - (this).storagePropOnChange(_); + this.__backing_storagepropvar = new StoragePropDecoratedVariable("prop2", "storagepropvar", "Hello World", ((_: string): void => { + this.storagePropOnChange(_); })) - (this).__backing_providevar = (this).addProvidedVar("providevar", "providevar", ((({let gensym___194235814 = initializers; + this.__backing_providevar = this.addProvidedVar("providevar", "providevar", ((({let gensym___194235814 = initializers; (((gensym___194235814) == (null)) ? undefined : gensym___194235814.providevar)})) ?? ("Hello World")), false, ((_: string): void => { - (this).ProvideOnChange(_); + this.ProvideOnChange(_); })); } public __updateStruct(initializers: __Options_MyStateSample | undefined): void { if (((({let gensym___220608839 = initializers; (((gensym___220608839) == (null)) ? undefined : gensym___220608839.propvar)})) !== (undefined))) { - (this).__backing_propvar!.update((initializers!.propvar as string)); + this.__backing_propvar!.update((initializers!.propvar as string)); } } private __backing_statevar?: StateDecoratedVariable; public get statevar(): string { - return (this).__backing_statevar!.get(); + return this.__backing_statevar!.get(); } public set statevar(value: string) { - (this).__backing_statevar!.set(value); + this.__backing_statevar!.set(value); } private __backing_propvar?: PropDecoratedVariable; public get propvar(): string { - return (this).__backing_propvar!.get(); + return this.__backing_propvar!.get(); } public set propvar(value: string) { - (this).__backing_propvar!.set(value); + this.__backing_propvar!.set(value); } private __backing_storagelinkvar?: StorageLinkDecoratedVariable; public get storagelinkvar(): string { - return (this).__backing_storagelinkvar!.get(); + return this.__backing_storagelinkvar!.get(); } public set storagelinkvar(value: string) { - (this).__backing_storagelinkvar!.set(value); + this.__backing_storagelinkvar!.set(value); } private __backing_storagepropvar?: StoragePropDecoratedVariable; public get storagepropvar(): string { - return (this).__backing_storagepropvar!.get(); + return this.__backing_storagepropvar!.get(); } public set storagepropvar(value: string) { - (this).__backing_storagepropvar!.set(value); + this.__backing_storagepropvar!.set(value); } private __backing_providevar?: ProvideDecoratedVariable; public get providevar(): string { - return (this).__backing_providevar!.get(); + return this.__backing_providevar!.get(); } public set providevar(value: string) { - (this).__backing_providevar!.set(value); + this.__backing_providevar!.set(value); } public stateOnChange(propName: string) {} diff --git a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts index 54d600a56..fc5ee09c6 100644 --- a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts @@ -59,7 +59,7 @@ function main() {} @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_myXComponentController = ((({let gensym___221905990 = initializers; + this.__backing_myXComponentController = ((({let gensym___221905990 = initializers; (((gensym___221905990) == (null)) ? undefined : gensym___221905990.myXComponentController)})) ?? (new XComponentController())); } @@ -68,11 +68,11 @@ function main() {} private __backing_myXComponentController?: XComponentController; public get myXComponentController(): XComponentController { - return ((this).__backing_myXComponentController as XComponentController); + return (this.__backing_myXComponentController as XComponentController); } public set myXComponentController(value: XComponentController) { - (this).__backing_myXComponentController = value; + this.__backing_myXComponentController = value; } @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { @@ -88,7 +88,7 @@ function main() {} id: "xComponentId", type: XComponentType.TEXTURE, libraryname: "nativerender", - controller: (this).myXComponentController, + controller: this.myXComponentController, } as XComponentParameter), "", undefined); })); } diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 4f9570ec8..635a1e83a 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -121,7 +121,7 @@ export class PreprocessorTransformer extends AbstractVisitor { addDependencesImport(node: arkts.ETSImportDeclaration): void { if (!node.source) return; - const isFromCompImport: boolean = node.source.str === ARKUI_COMPONENT_IMPORT_NAME; + const isFromCompImport: boolean = node.source.str === ARKUI_COMPONENT_IMPORT_NAME || node.source.str === KIT_ARKUI_NAME; const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); node.specifiers.forEach((item: arkts.AstNode) => { if (!arkts.isImportSpecifier(item) || !item.imported?.name) return; -- Gitee From 0d0d78b7e3b17d56b102aebb932a6f87941cdd78 Mon Sep 17 00:00:00 2001 From: Cuecuexiaoyu Date: Tue, 27 May 2025 11:19:20 +0800 Subject: [PATCH 103/123] fix class property initialization bug Signed-off-by: Cuecuexiaoyu Change-Id: I1458a8c26aca2e854fb07e897d4713942161010d --- .../mock/decorators/link/state-to-link.ets | 10 +- .../decorators/link/link-basic-type.test.ts | 78 ++++---- .../decorators/link/link-complex-type.test.ts | 188 +++++++++--------- .../link/link-to-link-prop-state.test.ts | 98 ++++----- .../decorators/link/state-to-link.test.ts | 76 +++---- .../ui-plugins/component-transformer.ts | 12 +- .../ui-plugins/property-translators/utils.ts | 28 ++- arkui-plugins/ui-plugins/ui-factory.ts | 18 +- arkui-plugins/ui-plugins/utils.ts | 18 ++ koala-wrapper/src/arkts-api/index.ts | 1 + 10 files changed, 288 insertions(+), 239 deletions(-) diff --git a/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets b/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets index b2aaf247a..a3e02b8b7 100644 --- a/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets +++ b/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { Component, Entry, Column, Button, DatePicker } from "@ohos.arkui.component" +import { Component, Entry, Column, Button, DatePicker, ClickEvent } from "@ohos.arkui.component" import { Link, State } from "@ohos.arkui.stateManagement" @Component @@ -23,12 +23,12 @@ struct DateComponent { build() { Column() { Button('child increase the year by 1') - .onClick(() => { + .onClick((e: ClickEvent) => { this.selectedDate.setFullYear(this.selectedDate.getFullYear() + 1); }) Button('child update the new date') .margin(10) - .onClick(() => { + .onClick((e: ClickEvent) => { this.selectedDate = new Date('2023-09-09'); }) DatePicker({ @@ -50,12 +50,12 @@ struct ParentComponent { Column() { Button('parent increase the month by 1') .margin(10) - .onClick(() => { + .onClick((e: ClickEvent) => { this.parentSelectedDate.setMonth(this.parentSelectedDate.getMonth() + 1); }) Button('parent update the new date') .margin(10) - .onClick(() => { + .onClick((e: ClickEvent) => { this.parentSelectedDate = new Date('2023-07-07'); }) DatePicker({ diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts index 5a798dab0..340db6a9e 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts @@ -37,12 +37,12 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Link as Link } from "@ohos.arkui.stateManagement"; @@ -52,86 +52,86 @@ function main() {} public __initializeStruct(initializers: __Options_LinkParent | undefined, @memo() content: (()=> void) | undefined): void { if (({let gensym___11910109 = initializers; (((gensym___11910109) == (null)) ? undefined : gensym___11910109.__backing_linkVar1)})) { - (this).__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); + this.__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); }; if (({let gensym___181684045 = initializers; (((gensym___181684045) == (null)) ? undefined : gensym___181684045.__backing_linkVar2)})) { - (this).__backing_linkVar2 = new LinkDecoratedVariable("linkVar2", initializers!.__backing_linkVar2!); + this.__backing_linkVar2 = new LinkDecoratedVariable("linkVar2", initializers!.__backing_linkVar2!); }; if (({let gensym___24446313 = initializers; (((gensym___24446313) == (null)) ? undefined : gensym___24446313.__backing_linkVar3)})) { - (this).__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); + this.__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); }; if (({let gensym___167989826 = initializers; (((gensym___167989826) == (null)) ? undefined : gensym___167989826.__backing_linkVar4)})) { - (this).__backing_linkVar4 = new LinkDecoratedVariable("linkVar4", initializers!.__backing_linkVar4!); + this.__backing_linkVar4 = new LinkDecoratedVariable("linkVar4", initializers!.__backing_linkVar4!); }; if (({let gensym___157566097 = initializers; (((gensym___157566097) == (null)) ? undefined : gensym___157566097.__backing_linkVar5)})) { - (this).__backing_linkVar5 = new LinkDecoratedVariable("linkVar5", initializers!.__backing_linkVar5!); + this.__backing_linkVar5 = new LinkDecoratedVariable("linkVar5", initializers!.__backing_linkVar5!); }; } public __updateStruct(initializers: __Options_LinkParent | undefined): void {} private __backing_linkVar1?: LinkDecoratedVariable; public get linkVar1(): string { - return (this).__backing_linkVar1!.get(); + return this.__backing_linkVar1!.get(); } public set linkVar1(value: string) { - (this).__backing_linkVar1!.set(value); + this.__backing_linkVar1!.set(value); } private __backing_linkVar2?: LinkDecoratedVariable; public get linkVar2(): number { - return (this).__backing_linkVar2!.get(); + return this.__backing_linkVar2!.get(); } public set linkVar2(value: number) { - (this).__backing_linkVar2!.set(value); + this.__backing_linkVar2!.set(value); } private __backing_linkVar3?: LinkDecoratedVariable; public get linkVar3(): boolean { - return (this).__backing_linkVar3!.get(); + return this.__backing_linkVar3!.get(); } public set linkVar3(value: boolean) { - (this).__backing_linkVar3!.set(value); + this.__backing_linkVar3!.set(value); } private __backing_linkVar4?: LinkDecoratedVariable; public get linkVar4(): undefined { - return (this).__backing_linkVar4!.get(); + return this.__backing_linkVar4!.get(); } public set linkVar4(value: undefined) { - (this).__backing_linkVar4!.set(value); + this.__backing_linkVar4!.set(value); } private __backing_linkVar5?: LinkDecoratedVariable; public get linkVar5(): null { - return (this).__backing_linkVar5!.get(); + return this.__backing_linkVar5!.get(); } public set linkVar5(value: null) { - (this).__backing_linkVar5!.set(value); + this.__backing_linkVar5!.set(value); } @memo() public _build(@memo() style: ((instance: LinkParent)=> LinkParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_LinkParent | undefined): void {} public constructor() {} } interface __Options_LinkParent { - abstract set linkVar1(linkVar1: string | undefined) - abstract get linkVar1(): string | undefined - abstract set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar1(): DecoratedV1VariableBase | undefined - abstract set linkVar2(linkVar2: number | undefined) - abstract get linkVar2(): number | undefined - abstract set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar2(): DecoratedV1VariableBase | undefined - abstract set linkVar3(linkVar3: boolean | undefined) - abstract get linkVar3(): boolean | undefined - abstract set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar3(): DecoratedV1VariableBase | undefined - abstract set linkVar4(linkVar4: undefined | undefined) - abstract get linkVar4(): undefined | undefined - abstract set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar4(): DecoratedV1VariableBase | undefined - abstract set linkVar5(linkVar5: null | undefined) - abstract get linkVar5(): null | undefined - abstract set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar5(): DecoratedV1VariableBase | undefined + set linkVar1(linkVar1: string | undefined) + get linkVar1(): string | undefined + set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) + get __backing_linkVar1(): DecoratedV1VariableBase | undefined + set linkVar2(linkVar2: number | undefined) + get linkVar2(): number | undefined + set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase | undefined) + get __backing_linkVar2(): DecoratedV1VariableBase | undefined + set linkVar3(linkVar3: boolean | undefined) + get linkVar3(): boolean | undefined + set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) + get __backing_linkVar3(): DecoratedV1VariableBase | undefined + set linkVar4(linkVar4: undefined | undefined) + get linkVar4(): undefined | undefined + set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase | undefined) + get __backing_linkVar4(): DecoratedV1VariableBase | undefined + set linkVar5(linkVar5: null | undefined) + get linkVar5(): null | undefined + set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase | undefined) + get __backing_linkVar5(): DecoratedV1VariableBase | undefined } `; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts index 927e91220..486097a84 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts @@ -37,12 +37,12 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Link as Link } from "@ohos.arkui.stateManagement"; @@ -51,7 +51,7 @@ function main() {} class Per { public num: number; public constructor(num: number) { - (this).num = num; + this.num = num; } } @@ -60,7 +60,7 @@ final class LinkType extends BaseEnum { private static () {} public constructor(ordinal: int, value: int) { super(value); - (this).#ordinal = ordinal; + this.#ordinal = ordinal; } public static readonly TYPE1: LinkType = new LinkType(0, 0); public static readonly TYPE2: LinkType = new LinkType(1, 1); @@ -70,7 +70,7 @@ final class LinkType extends BaseEnum { private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; private static readonly #ItemsArray: LinkType[] = [LinkType.TYPE1, LinkType.TYPE2, LinkType.TYPE3]; public getName(): String { - return LinkType.#NamesArray[(this).#ordinal]; + return LinkType.#NamesArray[this.#ordinal]; } public static getValueOf(name: String): LinkType { for (let i = 0;((i) < (LinkType.#NamesArray.length));(++i)) { @@ -90,16 +90,16 @@ final class LinkType extends BaseEnum { throw new Error((("No enum LinkType with value ") + (value))); } public valueOf(): int { - return LinkType.#ValuesArray[(this).#ordinal]; + return LinkType.#ValuesArray[this.#ordinal]; } public toString(): String { - return LinkType.#StringValuesArray[(this).#ordinal]; + return LinkType.#StringValuesArray[this.#ordinal]; } public static values(): LinkType[] { return LinkType.#ItemsArray; } public getOrdinal(): int { - return (this).#ordinal; + return this.#ordinal; } public static $_get(e: LinkType): String { return e.getName(); @@ -110,191 +110,191 @@ final class LinkType extends BaseEnum { public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { if (({let gensym___11910109 = initializers; (((gensym___11910109) == (null)) ? undefined : gensym___11910109.__backing_linkVar1)})) { - (this).__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); + this.__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); }; if (({let gensym___181684045 = initializers; (((gensym___181684045) == (null)) ? undefined : gensym___181684045.__backing_linkVar2)})) { - (this).__backing_linkVar2 = new LinkDecoratedVariable>("linkVar2", initializers!.__backing_linkVar2!); + this.__backing_linkVar2 = new LinkDecoratedVariable>("linkVar2", initializers!.__backing_linkVar2!); }; if (({let gensym___24446313 = initializers; (((gensym___24446313) == (null)) ? undefined : gensym___24446313.__backing_linkVar3)})) { - (this).__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); + this.__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); }; if (({let gensym___167989826 = initializers; (((gensym___167989826) == (null)) ? undefined : gensym___167989826.__backing_linkVar4)})) { - (this).__backing_linkVar4 = new LinkDecoratedVariable>("linkVar4", initializers!.__backing_linkVar4!); + this.__backing_linkVar4 = new LinkDecoratedVariable>("linkVar4", initializers!.__backing_linkVar4!); }; if (({let gensym___157566097 = initializers; (((gensym___157566097) == (null)) ? undefined : gensym___157566097.__backing_linkVar5)})) { - (this).__backing_linkVar5 = new LinkDecoratedVariable>("linkVar5", initializers!.__backing_linkVar5!); + this.__backing_linkVar5 = new LinkDecoratedVariable>("linkVar5", initializers!.__backing_linkVar5!); }; if (({let gensym___60105491 = initializers; (((gensym___60105491) == (null)) ? undefined : gensym___60105491.__backing_linkVar6)})) { - (this).__backing_linkVar6 = new LinkDecoratedVariable>("linkVar6", initializers!.__backing_linkVar6!); + this.__backing_linkVar6 = new LinkDecoratedVariable>("linkVar6", initializers!.__backing_linkVar6!); }; if (({let gensym___3429048 = initializers; (((gensym___3429048) == (null)) ? undefined : gensym___3429048.__backing_linkVar7)})) { - (this).__backing_linkVar7 = new LinkDecoratedVariable>("linkVar7", initializers!.__backing_linkVar7!); + this.__backing_linkVar7 = new LinkDecoratedVariable>("linkVar7", initializers!.__backing_linkVar7!); }; if (({let gensym___139916435 = initializers; (((gensym___139916435) == (null)) ? undefined : gensym___139916435.__backing_linkVar8)})) { - (this).__backing_linkVar8 = new LinkDecoratedVariable<((sr: string)=> void)>("linkVar8", initializers!.__backing_linkVar8!); + this.__backing_linkVar8 = new LinkDecoratedVariable<((sr: string)=> void)>("linkVar8", initializers!.__backing_linkVar8!); }; if (({let gensym___145003260 = initializers; (((gensym___145003260) == (null)) ? undefined : gensym___145003260.__backing_linkVar9)})) { - (this).__backing_linkVar9 = new LinkDecoratedVariable("linkVar9", initializers!.__backing_linkVar9!); + this.__backing_linkVar9 = new LinkDecoratedVariable("linkVar9", initializers!.__backing_linkVar9!); }; if (({let gensym___122643185 = initializers; (((gensym___122643185) == (null)) ? undefined : gensym___122643185.__backing_linkVar10)})) { - (this).__backing_linkVar10 = new LinkDecoratedVariable>("linkVar10", initializers!.__backing_linkVar10!); + this.__backing_linkVar10 = new LinkDecoratedVariable>("linkVar10", initializers!.__backing_linkVar10!); }; if (({let gensym___222468503 = initializers; (((gensym___222468503) == (null)) ? undefined : gensym___222468503.__backing_linkVar11)})) { - (this).__backing_linkVar11 = new LinkDecoratedVariable("linkVar11", initializers!.__backing_linkVar11!); + this.__backing_linkVar11 = new LinkDecoratedVariable("linkVar11", initializers!.__backing_linkVar11!); }; if (({let gensym___243301539 = initializers; (((gensym___243301539) == (null)) ? undefined : gensym___243301539.__backing_linkVar12)})) { - (this).__backing_linkVar12 = new LinkDecoratedVariable | Per>("linkVar12", initializers!.__backing_linkVar12!); + this.__backing_linkVar12 = new LinkDecoratedVariable | Per>("linkVar12", initializers!.__backing_linkVar12!); }; } public __updateStruct(initializers: __Options_Parent | undefined): void {} private __backing_linkVar1?: LinkDecoratedVariable; public get linkVar1(): Per { - return (this).__backing_linkVar1!.get(); + return this.__backing_linkVar1!.get(); } public set linkVar1(value: Per) { - (this).__backing_linkVar1!.set(value); + this.__backing_linkVar1!.set(value); } private __backing_linkVar2?: LinkDecoratedVariable>; public get linkVar2(): Array { - return (this).__backing_linkVar2!.get(); + return this.__backing_linkVar2!.get(); } public set linkVar2(value: Array) { - (this).__backing_linkVar2!.set(value); + this.__backing_linkVar2!.set(value); } private __backing_linkVar3?: LinkDecoratedVariable; public get linkVar3(): LinkType { - return (this).__backing_linkVar3!.get(); + return this.__backing_linkVar3!.get(); } public set linkVar3(value: LinkType) { - (this).__backing_linkVar3!.set(value); + this.__backing_linkVar3!.set(value); } private __backing_linkVar4?: LinkDecoratedVariable>; public get linkVar4(): Set { - return (this).__backing_linkVar4!.get(); + return this.__backing_linkVar4!.get(); } public set linkVar4(value: Set) { - (this).__backing_linkVar4!.set(value); + this.__backing_linkVar4!.set(value); } private __backing_linkVar5?: LinkDecoratedVariable>; public get linkVar5(): Array { - return (this).__backing_linkVar5!.get(); + return this.__backing_linkVar5!.get(); } public set linkVar5(value: Array) { - (this).__backing_linkVar5!.set(value); + this.__backing_linkVar5!.set(value); } private __backing_linkVar6?: LinkDecoratedVariable>; public get linkVar6(): Array { - return (this).__backing_linkVar6!.get(); + return this.__backing_linkVar6!.get(); } public set linkVar6(value: Array) { - (this).__backing_linkVar6!.set(value); + this.__backing_linkVar6!.set(value); } private __backing_linkVar7?: LinkDecoratedVariable>; public get linkVar7(): Array { - return (this).__backing_linkVar7!.get(); + return this.__backing_linkVar7!.get(); } public set linkVar7(value: Array) { - (this).__backing_linkVar7!.set(value); + this.__backing_linkVar7!.set(value); } private __backing_linkVar8?: LinkDecoratedVariable<((sr: string)=> void)>; public get linkVar8(): ((sr: string)=> void) { - return (this).__backing_linkVar8!.get(); + return this.__backing_linkVar8!.get(); } public set linkVar8(value: ((sr: string)=> void)) { - (this).__backing_linkVar8!.set(value); + this.__backing_linkVar8!.set(value); } private __backing_linkVar9?: LinkDecoratedVariable; public get linkVar9(): Date { - return (this).__backing_linkVar9!.get(); + return this.__backing_linkVar9!.get(); } public set linkVar9(value: Date) { - (this).__backing_linkVar9!.set(value); + this.__backing_linkVar9!.set(value); } private __backing_linkVar10?: LinkDecoratedVariable>; public get linkVar10(): Map { - return (this).__backing_linkVar10!.get(); + return this.__backing_linkVar10!.get(); } public set linkVar10(value: Map) { - (this).__backing_linkVar10!.set(value); + this.__backing_linkVar10!.set(value); } private __backing_linkVar11?: LinkDecoratedVariable; public get linkVar11(): string | number { - return (this).__backing_linkVar11!.get(); + return this.__backing_linkVar11!.get(); } public set linkVar11(value: string | number) { - (this).__backing_linkVar11!.set(value); + this.__backing_linkVar11!.set(value); } private __backing_linkVar12?: LinkDecoratedVariable | Per>; public get linkVar12(): Set | Per { - return (this).__backing_linkVar12!.get(); + return this.__backing_linkVar12!.get(); } public set linkVar12(value: Set | Per) { - (this).__backing_linkVar12!.set(value); + this.__backing_linkVar12!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} public constructor() {} } interface __Options_Parent { - abstract set linkVar1(linkVar1: Per | undefined) - abstract get linkVar1(): Per | undefined - abstract set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar1(): DecoratedV1VariableBase | undefined - abstract set linkVar2(linkVar2: Array | undefined) - abstract get linkVar2(): Array | undefined - abstract set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase> | undefined) - abstract get __backing_linkVar2(): DecoratedV1VariableBase> | undefined - abstract set linkVar3(linkVar3: LinkType | undefined) - abstract get linkVar3(): LinkType | undefined - abstract set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar3(): DecoratedV1VariableBase | undefined - abstract set linkVar4(linkVar4: Set | undefined) - abstract get linkVar4(): Set | undefined - abstract set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase> | undefined) - abstract get __backing_linkVar4(): DecoratedV1VariableBase> | undefined - abstract set linkVar5(linkVar5: Array | undefined) - abstract get linkVar5(): Array | undefined - abstract set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase> | undefined) - abstract get __backing_linkVar5(): DecoratedV1VariableBase> | undefined - abstract set linkVar6(linkVar6: Array | undefined) - abstract get linkVar6(): Array | undefined - abstract set __backing_linkVar6(__backing_linkVar6: DecoratedV1VariableBase> | undefined) - abstract get __backing_linkVar6(): DecoratedV1VariableBase> | undefined - abstract set linkVar7(linkVar7: Array | undefined) - abstract get linkVar7(): Array | undefined - abstract set __backing_linkVar7(__backing_linkVar7: DecoratedV1VariableBase> | undefined) - abstract get __backing_linkVar7(): DecoratedV1VariableBase> | undefined - abstract set linkVar8(linkVar8: ((sr: string)=> void) | undefined) - abstract get linkVar8(): ((sr: string)=> void) | undefined - abstract set __backing_linkVar8(__backing_linkVar8: DecoratedV1VariableBase<((sr: string)=> void)> | undefined) - abstract get __backing_linkVar8(): DecoratedV1VariableBase<((sr: string)=> void)> | undefined - abstract set linkVar9(linkVar9: Date | undefined) - abstract get linkVar9(): Date | undefined - abstract set __backing_linkVar9(__backing_linkVar9: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar9(): DecoratedV1VariableBase | undefined - abstract set linkVar10(linkVar10: Map | undefined) - abstract get linkVar10(): Map | undefined - abstract set __backing_linkVar10(__backing_linkVar10: DecoratedV1VariableBase> | undefined) - abstract get __backing_linkVar10(): DecoratedV1VariableBase> | undefined - abstract set linkVar11(linkVar11: string | number | undefined) - abstract get linkVar11(): string | number | undefined - abstract set __backing_linkVar11(__backing_linkVar11: DecoratedV1VariableBase | undefined) - abstract get __backing_linkVar11(): DecoratedV1VariableBase | undefined - abstract set linkVar12(linkVar12: Set | Per | undefined) - abstract get linkVar12(): Set | Per | undefined - abstract set __backing_linkVar12(__backing_linkVar12: DecoratedV1VariableBase | Per> | undefined) - abstract get __backing_linkVar12(): DecoratedV1VariableBase | Per> | undefined + set linkVar1(linkVar1: Per | undefined) + get linkVar1(): Per | undefined + set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) + get __backing_linkVar1(): DecoratedV1VariableBase | undefined + set linkVar2(linkVar2: Array | undefined) + get linkVar2(): Array | undefined + set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase> | undefined) + get __backing_linkVar2(): DecoratedV1VariableBase> | undefined + set linkVar3(linkVar3: LinkType | undefined) + get linkVar3(): LinkType | undefined + set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) + get __backing_linkVar3(): DecoratedV1VariableBase | undefined + set linkVar4(linkVar4: Set | undefined) + get linkVar4(): Set | undefined + set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase> | undefined) + get __backing_linkVar4(): DecoratedV1VariableBase> | undefined + set linkVar5(linkVar5: Array | undefined) + get linkVar5(): Array | undefined + set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase> | undefined) + get __backing_linkVar5(): DecoratedV1VariableBase> | undefined + set linkVar6(linkVar6: Array | undefined) + get linkVar6(): Array | undefined + set __backing_linkVar6(__backing_linkVar6: DecoratedV1VariableBase> | undefined) + get __backing_linkVar6(): DecoratedV1VariableBase> | undefined + set linkVar7(linkVar7: Array | undefined) + get linkVar7(): Array | undefined + set __backing_linkVar7(__backing_linkVar7: DecoratedV1VariableBase> | undefined) + get __backing_linkVar7(): DecoratedV1VariableBase> | undefined + set linkVar8(linkVar8: ((sr: string)=> void) | undefined) + get linkVar8(): ((sr: string)=> void) | undefined + set __backing_linkVar8(__backing_linkVar8: DecoratedV1VariableBase<((sr: string)=> void)> | undefined) + get __backing_linkVar8(): DecoratedV1VariableBase<((sr: string)=> void)> | undefined + set linkVar9(linkVar9: Date | undefined) + get linkVar9(): Date | undefined + set __backing_linkVar9(__backing_linkVar9: DecoratedV1VariableBase | undefined) + get __backing_linkVar9(): DecoratedV1VariableBase | undefined + set linkVar10(linkVar10: Map | undefined) + get linkVar10(): Map | undefined + set __backing_linkVar10(__backing_linkVar10: DecoratedV1VariableBase> | undefined) + get __backing_linkVar10(): DecoratedV1VariableBase> | undefined + set linkVar11(linkVar11: string | number | undefined) + get linkVar11(): string | number | undefined + set __backing_linkVar11(__backing_linkVar11: DecoratedV1VariableBase | undefined) + get __backing_linkVar11(): DecoratedV1VariableBase | undefined + set linkVar12(linkVar12: Set | Per | undefined) + get linkVar12(): Set | Per | undefined + set __backing_linkVar12(__backing_linkVar12: DecoratedV1VariableBase | Per> | undefined) + get __backing_linkVar12(): DecoratedV1VariableBase | Per> | undefined } `; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts index 6e903b659..01a8275f9 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts @@ -37,16 +37,16 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { TextInputAttribute as TextInputAttribute } from "@ohos.arkui.component"; -import { ColumnAttribute as ColumnAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { UITextInputAttribute as UITextInputAttribute } from "@ohos.arkui.component"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, TextInput as TextInput } from "@ohos.arkui.component"; import { Link as Link, State as State, Prop as Prop } from "@ohos.arkui.stateManagement"; @@ -56,29 +56,29 @@ function main() {} public __initializeStruct(initializers: __Options_Parant | undefined, @memo() content: (()=> void) | undefined): void { if (({let gensym___10127521 = initializers; (((gensym___10127521) == (null)) ? undefined : gensym___10127521.__backing_text1)})) { - (this).__backing_text1 = new LinkDecoratedVariable("text1", initializers!.__backing_text1!); + this.__backing_text1 = new LinkDecoratedVariable("text1", initializers!.__backing_text1!); }; } public __updateStruct(initializers: __Options_Parant | undefined): void {} private __backing_text1?: LinkDecoratedVariable; public get text1(): string { - return (this).__backing_text1!.get(); + return this.__backing_text1!.get(); } public set text1(value: string) { - (this).__backing_text1!.set(value); + this.__backing_text1!.set(value); } @memo() public _build(@memo() style: ((instance: Parant)=> Parant) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parant | undefined): void { Column(undefined, undefined, (() => { TextInput(undefined, { - text: (this).text1, + text: this.text1, }, undefined); Child._instantiateImpl(undefined, (() => { return new Child(); }), ({ - __backing_childText: (this).__backing_text1, - childText2: (this).text1, - childText3: (this).text1, - childText4: (this).text1, + __backing_childText: this.__backing_text1, + childText2: this.text1, + childText3: this.text1, + childText4: this.text1, } as __Options_Child), undefined, undefined); })); } @@ -89,84 +89,84 @@ function main() {} public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { if (({let gensym___161337494 = initializers; (((gensym___161337494) == (null)) ? undefined : gensym___161337494.__backing_childText)})) { - (this).__backing_childText = new LinkDecoratedVariable("childText", initializers!.__backing_childText!); + this.__backing_childText = new LinkDecoratedVariable("childText", initializers!.__backing_childText!); }; - (this).__backing_childText2 = new StateDecoratedVariable("childText2", ((({let gensym___95513066 = initializers; + this.__backing_childText2 = new StateDecoratedVariable("childText2", ((({let gensym___95513066 = initializers; (((gensym___95513066) == (null)) ? undefined : gensym___95513066.childText2)})) ?? ("sss"))); - (this).__backing_childText3 = new PropDecoratedVariable("childText3", (initializers!.childText3 as string)); - (this).__backing_childText4 = new PropDecoratedVariable("childText4", ((({let gensym___162028107 = initializers; + this.__backing_childText3 = new PropDecoratedVariable("childText3", (initializers!.childText3 as string)); + this.__backing_childText4 = new PropDecoratedVariable("childText4", ((({let gensym___162028107 = initializers; (((gensym___162028107) == (null)) ? undefined : gensym___162028107.childText4)})) ?? ("cc"))); } public __updateStruct(initializers: __Options_Child | undefined): void { if (((({let gensym___77632518 = initializers; (((gensym___77632518) == (null)) ? undefined : gensym___77632518.childText3)})) !== (undefined))) { - (this).__backing_childText3!.update((initializers!.childText3 as string)); + this.__backing_childText3!.update((initializers!.childText3 as string)); } if (((({let gensym___250510741 = initializers; (((gensym___250510741) == (null)) ? undefined : gensym___250510741.childText4)})) !== (undefined))) { - (this).__backing_childText4!.update((initializers!.childText4 as string)); + this.__backing_childText4!.update((initializers!.childText4 as string)); } } private __backing_childText?: LinkDecoratedVariable; public get childText(): string { - return (this).__backing_childText!.get(); + return this.__backing_childText!.get(); } public set childText(value: string) { - (this).__backing_childText!.set(value); + this.__backing_childText!.set(value); } private __backing_childText2?: StateDecoratedVariable; public get childText2(): string { - return (this).__backing_childText2!.get(); + return this.__backing_childText2!.get(); } public set childText2(value: string) { - (this).__backing_childText2!.set(value); + this.__backing_childText2!.set(value); } private __backing_childText3?: PropDecoratedVariable; public get childText3(): string { - return (this).__backing_childText3!.get(); + return this.__backing_childText3!.get(); } public set childText3(value: string) { - (this).__backing_childText3!.set(value); + this.__backing_childText3!.set(value); } private __backing_childText4?: PropDecoratedVariable; public get childText4(): string { - return (this).__backing_childText4!.get(); + return this.__backing_childText4!.get(); } public set childText4(value: string) { - (this).__backing_childText4!.set(value); + this.__backing_childText4!.set(value); } @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { TextInput(undefined, { - text: (this).childText, + text: this.childText, }, undefined); } public constructor() {} } interface __Options_Parant { - abstract set text1(text1: string | undefined) - abstract get text1(): string | undefined - abstract set __backing_text1(__backing_text1: DecoratedV1VariableBase | undefined) - abstract get __backing_text1(): DecoratedV1VariableBase | undefined + set text1(text1: string | undefined) + get text1(): string | undefined + set __backing_text1(__backing_text1: DecoratedV1VariableBase | undefined) + get __backing_text1(): DecoratedV1VariableBase | undefined } interface __Options_Child { - abstract set childText(childText: string | undefined) - abstract get childText(): string | undefined - abstract set __backing_childText(__backing_childText: DecoratedV1VariableBase | undefined) - abstract get __backing_childText(): DecoratedV1VariableBase | undefined - abstract set childText2(childText2: string | undefined) - abstract get childText2(): string | undefined - abstract set __backing_childText2(__backing_childText2: StateDecoratedVariable | undefined) - abstract get __backing_childText2(): StateDecoratedVariable | undefined - abstract set childText3(childText3: string | undefined) - abstract get childText3(): string | undefined - abstract set __backing_childText3(__backing_childText3: PropDecoratedVariable | undefined) - abstract get __backing_childText3(): PropDecoratedVariable | undefined - abstract set childText4(childText4: string | undefined) - abstract get childText4(): string | undefined - abstract set __backing_childText4(__backing_childText4: PropDecoratedVariable | undefined) - abstract get __backing_childText4(): PropDecoratedVariable | undefined + set childText(childText: string | undefined) + get childText(): string | undefined + set __backing_childText(__backing_childText: DecoratedV1VariableBase | undefined) + get __backing_childText(): DecoratedV1VariableBase | undefined + set childText2(childText2: string | undefined) + get childText2(): string | undefined + set __backing_childText2(__backing_childText2: StateDecoratedVariable | undefined) + get __backing_childText2(): StateDecoratedVariable | undefined + set childText3(childText3: string | undefined) + get childText3(): string | undefined + set __backing_childText3(__backing_childText3: PropDecoratedVariable | undefined) + get __backing_childText3(): PropDecoratedVariable | undefined + set childText4(childText4: string | undefined) + get childText4(): string | undefined + set __backing_childText4(__backing_childText4: PropDecoratedVariable | undefined) + get __backing_childText4(): PropDecoratedVariable | undefined } `; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts index 300ebc5a9..cd9424e90 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts @@ -37,18 +37,18 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { DatePickerAttribute as DatePickerAttribute } from "@ohos.arkui.component"; -import { ButtonAttribute as ButtonAttribute } from "@ohos.arkui.component"; -import { ColumnAttribute as ColumnAttribute } from "@ohos.arkui.component"; -import { EntryPoint as EntryPoint } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; -import { Component as Component, Entry as Entry, Column as Column, Button as Button, DatePicker as DatePicker } from "@ohos.arkui.component"; +import { UIDatePickerAttribute as UIDatePickerAttribute } from "@ohos.arkui.component"; +import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; +import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { EntryPoint as EntryPoint } from "arkui.UserView"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; +import { Component as Component, Entry as Entry, Column as Column, Button as Button, DatePicker as DatePicker, ClickEvent as ClickEvent } from "@ohos.arkui.component"; import { Link as Link, State as State } from "@ohos.arkui.stateManagement"; function main() {} @@ -57,35 +57,35 @@ function main() {} public __initializeStruct(initializers: __Options_DateComponent | undefined, @memo() content: (()=> void) | undefined): void { if (({let gensym___164314175 = initializers; (((gensym___164314175) == (null)) ? undefined : gensym___164314175.__backing_selectedDate)})) { - (this).__backing_selectedDate = new LinkDecoratedVariable("selectedDate", initializers!.__backing_selectedDate!); + this.__backing_selectedDate = new LinkDecoratedVariable("selectedDate", initializers!.__backing_selectedDate!); }; } public __updateStruct(initializers: __Options_DateComponent | undefined): void {} private __backing_selectedDate?: LinkDecoratedVariable; public get selectedDate(): Date { - return (this).__backing_selectedDate!.get(); + return this.__backing_selectedDate!.get(); } public set selectedDate(value: Date) { - (this).__backing_selectedDate!.set(value); + this.__backing_selectedDate!.set(value); } @memo() public _build(@memo() style: ((instance: DateComponent)=> DateComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_DateComponent | undefined): void { Column(undefined, undefined, (() => { - Button(((instance: ButtonAttribute): void => { - instance.onClick((() => { - (this).selectedDate.setFullYear((((this).selectedDate.getFullYear()) + (1))); + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.onClick(((e: ClickEvent) => { + this.selectedDate.setFullYear(((this.selectedDate.getFullYear()) + (1))); })); return; }), "child increase the year by 1", undefined, undefined); - Button(((instance: ButtonAttribute): void => { - instance.margin(10).onClick((() => { - (this).selectedDate = new Date("2023-09-09"); + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.margin(10).onClick(((e: ClickEvent) => { + this.selectedDate = new Date("2023-09-09"); })); return; }), "child update the new date", undefined, undefined); DatePicker(undefined, { start: new Date("1970-1-1"), end: new Date("2100-1-1"), - selected: (this).selectedDate, + selected: this.selectedDate, }, undefined); })); } @@ -95,40 +95,40 @@ function main() {} @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class ParentComponent extends CustomComponent { public __initializeStruct(initializers: __Options_ParentComponent | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_parentSelectedDate = new StateDecoratedVariable("parentSelectedDate", ((({let gensym___80922148 = initializers; + this.__backing_parentSelectedDate = new StateDecoratedVariable("parentSelectedDate", ((({let gensym___80922148 = initializers; (((gensym___80922148) == (null)) ? undefined : gensym___80922148.parentSelectedDate)})) ?? (new Date("2021-08-08")))); } public __updateStruct(initializers: __Options_ParentComponent | undefined): void {} private __backing_parentSelectedDate?: StateDecoratedVariable; public get parentSelectedDate(): Date { - return (this).__backing_parentSelectedDate!.get(); + return this.__backing_parentSelectedDate!.get(); } public set parentSelectedDate(value: Date) { - (this).__backing_parentSelectedDate!.set(value); + this.__backing_parentSelectedDate!.set(value); } @memo() public _build(@memo() style: ((instance: ParentComponent)=> ParentComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ParentComponent | undefined): void { Column(undefined, undefined, (() => { - Button(((instance: ButtonAttribute): void => { - instance.margin(10).onClick((() => { - (this).parentSelectedDate.setMonth((((this).parentSelectedDate.getMonth()) + (1))); + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.margin(10).onClick(((e: ClickEvent) => { + this.parentSelectedDate.setMonth(((this.parentSelectedDate.getMonth()) + (1))); })); return; }), "parent increase the month by 1", undefined, undefined); - Button(((instance: ButtonAttribute): void => { - instance.margin(10).onClick((() => { - (this).parentSelectedDate = new Date("2023-07-07"); + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.margin(10).onClick(((e: ClickEvent) => { + this.parentSelectedDate = new Date("2023-07-07"); })); return; }), "parent update the new date", undefined, undefined); DatePicker(undefined, { start: new Date("1970-1-1"), end: new Date("2100-1-1"), - selected: (this).parentSelectedDate, + selected: this.parentSelectedDate, }, undefined); DateComponent._instantiateImpl(undefined, (() => { return new DateComponent(); }), ({ - __backing_selectedDate: (this).__backing_parentSelectedDate, + __backing_selectedDate: this.__backing_parentSelectedDate, } as __Options_DateComponent), undefined, undefined); })); } @@ -136,17 +136,17 @@ function main() {} } interface __Options_DateComponent { - abstract set selectedDate(selectedDate: Date | undefined) - abstract get selectedDate(): Date | undefined - abstract set __backing_selectedDate(__backing_selectedDate: DecoratedV1VariableBase | undefined) - abstract get __backing_selectedDate(): DecoratedV1VariableBase | undefined + set selectedDate(selectedDate: Date | undefined) + get selectedDate(): Date | undefined + set __backing_selectedDate(__backing_selectedDate: DecoratedV1VariableBase | undefined) + get __backing_selectedDate(): DecoratedV1VariableBase | undefined } interface __Options_ParentComponent { - abstract set parentSelectedDate(parentSelectedDate: Date | undefined) - abstract get parentSelectedDate(): Date | undefined - abstract set __backing_parentSelectedDate(__backing_parentSelectedDate: StateDecoratedVariable | undefined) - abstract get __backing_parentSelectedDate(): StateDecoratedVariable | undefined + set parentSelectedDate(parentSelectedDate: Date | undefined) + get parentSelectedDate(): Date | undefined + set __backing_parentSelectedDate(__backing_parentSelectedDate: StateDecoratedVariable | undefined) + get __backing_parentSelectedDate(): StateDecoratedVariable | undefined } class __EntryWrapper extends EntryPoint { diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index cc6b9acd4..db66f9d7e 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -31,11 +31,9 @@ import { hasDecorator, DecoratorNames, getStateManagementType, - collectPropertyDecorators + collectPropertyDecorators, } from './property-translators/utils'; -import { - factory -} from './ui-factory'; +import { factory } from './ui-factory'; import { StructMap } from '../common/program-visitor'; import { generateTempCallFunction } from './interop'; import { stringify } from 'querystring'; @@ -300,7 +298,11 @@ export class ComponentTransformer extends AbstractVisitor { ]) ) ), - [...newDefinitionBody, ...definition.body, ...staticMethodBody], + [ + ...newDefinitionBody, + ...definition.body.map((st: arkts.AstNode) => factory.PreprocessClassPropertyModifier(st)), + ...staticMethodBody, + ], definition.modifiers, arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL ); diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 9005d8d88..acdae5b2f 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -34,7 +34,7 @@ export enum DecoratorNames { LOCAL_STORAGE_PROP = 'LocalStorageProp', LOCAL_STORAGE_LINK = 'LocalStorageLink', REUSABLE = 'Reusable', - TRACK = 'Track' + TRACK = 'Track', } export function collectPropertyDecorators(property: arkts.ClassProperty): string[] { @@ -61,6 +61,20 @@ export function hasDecorator( return property.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName)); } +/** + * Determine whether the node `` is decorated by decorators that need initializing without assignment. + * + * @param st class property node + */ +export function needDefiniteOrOptionalModifier(st: arkts.ClassProperty): boolean { + return ( + hasDecorator(st, DecoratorNames.LINK) || + hasDecorator(st, DecoratorNames.CONSUME) || + hasDecorator(st, DecoratorNames.OBJECT_LINK) || + (hasDecorator(st, DecoratorNames.PROP) && !st.value) + ); +} + export function getStateManagementType(node: arkts.ClassProperty): string { if (hasDecorator(node, DecoratorNames.STATE)) { return 'StateDecoratedVariable'; @@ -307,12 +321,12 @@ export function generateToRecord(newName: string, originalName: string): arkts.P return arkts.Property.createProperty( arkts.factory.createStringLiteral(originalName), arkts.factory.createBinaryExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('paramsCasted'), - arkts.factory.createIdentifier(originalName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('paramsCasted'), + arkts.factory.createIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false ), arkts.ETSNewClassInstanceExpression.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index 90fefdee5..f41800a4b 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -14,9 +14,9 @@ */ import * as arkts from '@koalaui/libarkts'; -import { BuilderLambdaNames, CustomComponentNames, hasPropertyInAnnotation } from './utils'; +import { BuilderLambdaNames, CustomComponentNames, hasPropertyInAnnotation, hasNullOrUndefinedType } from './utils'; import { annotation } from '../common/arkts-utils'; -import { DecoratorNames } from './property-translators/utils'; +import { DecoratorNames, needDefiniteOrOptionalModifier } from './property-translators/utils'; export class factory { /** @@ -270,4 +270,18 @@ export class factory { false ); } + + /* + * add optional or definite modifier for class property needs initializing without assignment. + */ + static PreprocessClassPropertyModifier(st: arkts.AstNode): arkts.AstNode { + if (arkts.isClassProperty(st) && needDefiniteOrOptionalModifier(st)) { + if (st.typeAnnotation && hasNullOrUndefinedType(st.typeAnnotation)) { + st.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL; + } else { + st.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DEFINITE; + } + } + return st; + } } diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index d7276ab90..847a830a5 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -178,4 +178,22 @@ export function hasPropertyInAnnotation(annotation: arkts.AnnotationUsage, prope arkts.isIdentifier(annoProp.key) && annoProp.key.name === propertyName ); +} + +/** + * Determine whether the type node includes null or undefined type. + * + * @param type type node + */ +export function hasNullOrUndefinedType(type: arkts.TypeNode): boolean { + let res: boolean = false; + if (arkts.isETSUnionType(type)) { + type.types.forEach((item: arkts.TypeNode) => { + res = res || hasNullOrUndefinedType(item); + }); + } + if (arkts.isETSUndefinedType(type) || arkts.isETSNullType(type)) { + res = true; + } + return res; } \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index a77ec8acd..936a9b0f8 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -60,6 +60,7 @@ export * from "../generated/peers/TSClassImplements" export * from "../generated/peers/BooleanLiteral" export * from "../generated/peers/TSArrayType" export * from "../generated/peers/ArrayExpression"; +export * from "../generated/peers/ETSNullType"; export * from "./types" export * from "./utilities/private" -- Gitee From cc5a35601e25ba036b0dbd764c8839ea7177f67b Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 9 Apr 2025 23:32:38 +0800 Subject: [PATCH 104/123] support arkts cache Signed-off-by: Jiakai Shi Change-Id: I115ef6cbf60ef970bb2eb17caf988af865954209 --- arkui-plugins/common/arkts-utils.ts | 20 +- .../declaration-collector.ts} | 62 +- arkui-plugins/common/plugin-context.ts | 13 + arkui-plugins/common/predefines.ts | 83 ++- arkui-plugins/common/program-visitor.ts | 184 +++-- .../safe-types.ts} | 72 +- arkui-plugins/interop-plugins/index.ts | 1 - .../memo-plugins/function-transformer.ts | 49 +- arkui-plugins/memo-plugins/index.ts | 15 +- arkui-plugins/memo-plugins/memo-factory.ts | 3 +- .../memo-plugins/parameter-transformer.ts | 44 +- .../memo-plugins/signature-transformer.ts | 14 +- arkui-plugins/memo-plugins/utils.ts | 38 +- arkui-plugins/package.json | 3 +- .../demo/localtest/build_config_template.json | 7 +- .../test/demo/localtest/entry/new.ets | 74 +- .../mock/builder-lambda/simple-component.ets | 2 +- .../mock/common-utils/annotation.ets} | 26 +- .../decorators/reusable/reusable-basic.ets | 4 +- .../mock/imports/import-struct.ets} | 16 +- .../mock/imports/utils/simple-struct.ets} | 9 +- .../mock/memo/functions/argument-call.ets | 2 +- .../mock/memo/functions/declare-and-call.ets | 2 +- .../mock/memo/functions/inner-functions.ets | 2 +- .../memo/functions/non-void-return-type.ets | 2 +- .../mock/memo/functions/type-reference.ets | 2 +- .../mock/memo/functions/void-return-type.ets | 2 +- .../demo/mock/memo/lambdas/argument-call.ets | 2 +- .../memo/lambdas/function-with-receiver.ets | 2 +- .../mock/memo/lambdas/trailing-lambdas.ets | 2 +- .../demo/mock/memo/lambdas/void-lambda.ets | 2 +- .../demo/mock/memo/lambdas/with-receiver.ets | 2 +- .../demo/mock/memo/methods/argument-call.ets | 2 +- .../test/demo/mock/memo/methods/callable.ets | 2 +- .../mock/memo/methods/declare-and-call.ets | 2 +- .../demo/mock/memo/methods/internal-calls.ets | 2 +- .../mock/memo/methods/non-void-method.ets | 2 +- .../demo/mock/memo/methods/void-method.ets | 2 +- .../memo/properties/class-constructor.ets | 2 +- .../mock/memo/properties/class-properties.ets | 2 +- .../demo/mock/memo/properties/implements.ets | 2 +- .../demo/mock/memo/properties/interfaces.ets | 2 +- .../local/@ohos.arkui.component.text.d.ets | 132 ---- .../@ohos.arkui.stateManagement.common.d.ets | 61 -- .../@ohos.arkui.stateManagement.runtime.d.ets | 62 -- .../@ohos.arkui.stateManagement.storage.d.ets | 119 ---- arkui-plugins/test/package.json | 1 + arkui-plugins/test/test.log | 372 ---------- .../test/ut/common/annotation.test.ts | 191 +++++- .../argument-call.test.ts | 12 +- .../declare-and-call.test.ts | 12 +- .../inner-functions.test.ts | 12 +- .../non-void-return-type.test.ts | 12 +- .../type-reference.test.ts | 12 +- .../void-return-type.test.ts | 12 +- .../lambda-literals/argument-call.test.ts | 12 +- .../function-with-receiver.test.ts | 16 +- .../lambda-literals/trailing-lambdas.test.ts | 12 +- .../lambda-literals/void-lambda.test.ts | 12 +- .../lambda-literals/with-receiver.test.ts | 12 +- .../method-declarations/argument-call.test.ts | 12 +- .../method-declarations/callable.test.ts | 12 +- .../declare-and-call.test.ts | 12 +- .../internal-calls.test.ts | 12 +- .../non-void-method.test.ts | 18 +- .../method-declarations/void-method.test.ts | 12 +- .../class-constructor.test.ts | 12 +- .../class-properties.test.ts | 12 +- .../property-declarations/interfaces.test.ts | 12 +- .../animation/animation-basic.test.ts | 30 +- .../custom-component-call.test.ts | 64 +- .../builder-lambda/simple-component.test.ts | 12 +- .../style-with-receiver.test.ts | 27 +- .../builder-param-passing.test.ts | 57 +- .../init-with-local-builder.test.ts | 19 +- .../decorators/builder/global-builder.test.ts | 31 +- .../decorators/builder/local-builder.test.ts | 28 +- .../decorators/link/link-basic-type.test.ts | 87 ++- .../decorators/link/link-complex-type.test.ts | 174 ++--- .../link/link-to-link-prop-state.test.ts | 45 +- .../decorators/link/state-to-link.test.ts | 53 +- .../observed-track/observed-only.test.ts | 37 +- .../observed-track-class-property.test.ts | 35 +- .../observed-track-complex-type.test.ts | 38 +- .../observed-track-extends.test.ts | 37 +- .../observed-track-implements.test.ts | 37 +- .../observed-track/observed-track.test.ts | 37 +- .../observed-track/track-only.test.ts | 37 +- .../decorators/prop/prop-basic-type.test.ts | 21 +- .../decorators/prop/prop-complex-type.test.ts | 25 +- .../decorators/prop/state-to-prop.test.ts | 43 +- .../provide-annotation-usage.test.ts | 49 +- .../provide-basic-type.test.ts | 21 +- .../provide-complex-type.test.ts | 25 +- .../resource/resource-in-build.test.ts | 45 +- .../resource/resource-in-property.test.ts | 28 +- .../reusable/reusable-basic.test.ts | 57 +- .../reusable/reusable-complex.test.ts | 47 +- .../decorators/state/state-basic-type.test.ts | 21 +- .../state/state-complex-type.test.ts | 25 +- .../decorators/state/state-to-state.test.ts | 29 +- .../storagelink-appstorage.test.ts | 37 +- .../storagelink-complex-type.test.ts | 25 +- .../storagelink-primitive-type.test.ts | 21 +- .../storageprop-appstorage.test.ts | 37 +- .../storageprop-complex-type.test.ts | 25 +- .../storageprop-primitive-type.test.ts | 21 +- .../decorators/watch/watch-basic.test.ts | 63 +- .../ui-plugins/imports/import-struct.test.ts | 115 ++++ .../xcomponent/xcomponent-basic.test.ts | 31 +- arkui-plugins/test/utils/artkts-config.ts | 143 ++-- arkui-plugins/test/utils/cache.ts | 47 +- arkui-plugins/test/utils/compile.ts | 204 +++++- arkui-plugins/test/utils/global.ts | 76 ++- .../hash-generator.ts} | 46 +- arkui-plugins/test/utils/path-config.ts | 11 +- arkui-plugins/test/utils/plugin-driver.ts | 39 +- arkui-plugins/test/utils/plugin-tester.ts | 238 ++++--- .../plugins/builder-lambda-no-recheck.ts | 3 +- .../test/utils/plugins/memo-no-recheck.ts | 2 +- arkui-plugins/test/utils/plugins/recheck.ts | 2 +- .../test/utils/plugins/struct-no-recheck.ts | 3 +- .../test/utils/plugins/struct-to-component.ts | 2 +- .../test/utils/plugins/ui-no-recheck.ts | 3 +- arkui-plugins/test/utils/safe-types.ts | 10 +- .../serializable.ts} | 87 +-- arkui-plugins/test/utils/shared-types.ts | 120 ++++ arkui-plugins/test/utils/task-processor.ts | 548 +++++++++++++++ arkui-plugins/tsconfig.json | 7 +- .../builder-lambda-transformer.ts | 15 +- .../builder-lambda-translators/factory.ts | 257 ++++--- .../builder-lambda-translators/utils.ts | 51 +- .../ui-plugins/checked-transformer.ts | 439 ++---------- .../ui-plugins/component-transformer.ts | 263 ++++--- .../ui-plugins/entry-translators/factory.ts | 12 +- .../ui-plugins/entry-translators/utils.ts | 2 +- arkui-plugins/ui-plugins/import-collector.ts | 105 +++ arkui-plugins/ui-plugins/index.ts | 24 +- .../ui-plugins/legacy-transformer.ts | 6 +- .../ui-plugins/preprocessor-transform.ts | 75 +- .../ui-plugins/property-translators/base.ts | 93 +-- .../property-translators/builderParam.ts | 89 ++- .../property-translators/consume.ts | 62 +- .../property-translators/factory.ts | 349 +++++++++- .../ui-plugins/property-translators/index.ts | 135 ++-- .../ui-plugins/property-translators/link.ts | 76 ++- .../property-translators/localstoragelink.ts | 111 ++- .../property-translators/localstorageprop.ts | 147 ++-- .../property-translators/objectlink.ts | 70 +- .../property-translators/observedTrack.ts | 91 ++- .../ui-plugins/property-translators/prop.ts | 74 +- .../property-translators/provide.ts | 65 +- .../property-translators/regularProperty.ts | 33 +- .../ui-plugins/property-translators/state.ts | 78 ++- .../property-translators/storageProp.ts | 77 ++- .../property-translators/storagelink.ts | 77 ++- .../ui-plugins/property-translators/types.ts | 6 + .../ui-plugins/property-translators/utils.ts | 319 +++++++-- .../ui-plugins/struct-translators/factory.ts | 471 ++++++++++--- .../struct-translators/struct-transformer.ts | 195 ++---- .../ui-plugins/struct-translators/utils.ts | 35 +- arkui-plugins/ui-plugins/ui-factory.ts | 212 ++++-- arkui-plugins/ui-plugins/utils.ts | 295 +++++--- koala-wrapper/native/include/common.h | 2 +- koala-wrapper/native/src/bridges.cc | 63 +- koala-wrapper/native/src/common.cc | 68 +- koala-wrapper/native/src/generated/bridges.cc | 91 +-- koala-wrapper/src/Es2pandaNativeModule.ts | 48 +- .../src/arkts-api/factory/nodeFactory.ts | 639 ++++++++++-------- koala-wrapper/src/arkts-api/index.ts | 8 +- .../node-utilities/AnnotationDeclaration.ts | 41 +- .../node-utilities/MethodDefinition.ts | 3 +- .../node-utilities/TSInterfaceDeclaration.ts | 6 +- .../arkts-api/node-utilities/TryStatement.ts | 41 ++ koala-wrapper/src/arkts-api/peers/AstNode.ts | 103 +-- koala-wrapper/src/arkts-api/peers/Context.ts | 54 +- koala-wrapper/src/arkts-api/peers/Program.ts | 21 +- koala-wrapper/src/arkts-api/types.ts | 16 +- .../src/arkts-api/utilities/performance.ts | 78 ++- .../src/arkts-api/utilities/public.ts | 74 +- koala-wrapper/src/arkts-api/visitor.ts | 91 +-- .../src/generated/Es2pandaNativeModule.ts | 24 +- .../src/generated/peers/LabelPair.ts | 36 +- .../src/generated/peers/ScriptFunction.ts | 2 +- .../src/generated/peers/TryStatement.ts | 26 +- 185 files changed, 6665 insertions(+), 4535 deletions(-) rename arkui-plugins/{test/local/@ohos.arkui.component.enums.d.ets => common/declaration-collector.ts} (37%) rename arkui-plugins/{test/local/@ohos.arkui.component.common.d.ets => common/safe-types.ts} (31%) rename arkui-plugins/test/{local/@ohos.arkui.component.d.ets => demo/mock/common-utils/annotation.ets} (59%) rename arkui-plugins/test/{local/@ohos.arkui.stateManagement.d.ets => demo/mock/imports/import-struct.ets} (67%) rename arkui-plugins/test/{local/@ohos.arkui.external.resource.d.ets => demo/mock/imports/utils/simple-struct.ets} (81%) delete mode 100644 arkui-plugins/test/local/@ohos.arkui.component.text.d.ets delete mode 100644 arkui-plugins/test/local/@ohos.arkui.stateManagement.common.d.ets delete mode 100644 arkui-plugins/test/local/@ohos.arkui.stateManagement.runtime.d.ets delete mode 100644 arkui-plugins/test/local/@ohos.arkui.stateManagement.storage.d.ets delete mode 100644 arkui-plugins/test/test.log create mode 100644 arkui-plugins/test/ut/ui-plugins/imports/import-struct.test.ts rename arkui-plugins/test/{local/@ohos.arkui.component.styledString.d.ets => utils/hash-generator.ts} (36%) rename arkui-plugins/test/{local/@ohos.arkui.component.customComponent.d.ets => utils/serializable.ts} (30%) create mode 100644 arkui-plugins/test/utils/shared-types.ts create mode 100644 arkui-plugins/test/utils/task-processor.ts create mode 100644 arkui-plugins/ui-plugins/import-collector.ts rename arkui-plugins/test/local/@ohos.arkui.component.column.d.ets => koala-wrapper/src/arkts-api/node-utilities/AnnotationDeclaration.ts (39%) create mode 100644 koala-wrapper/src/arkts-api/node-utilities/TryStatement.ts rename arkui-plugins/test/local/@ohos.arkui.component.units.d.ets => koala-wrapper/src/generated/peers/LabelPair.ts (49%) diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index e62d9c991..9f2eb7a01 100644 --- a/arkui-plugins/common/arkts-utils.ts +++ b/arkui-plugins/common/arkts-utils.ts @@ -80,24 +80,6 @@ export function matchPrefix(prefixCollection: (string | RegExp)[], name: string) return false; } -export function updateStructMetadata( - structInfo: arkts.StructInfo, - propertyName: string, - properties: string[], - modifiers: arkts.Es2pandaModifierFlags, - hasStateManagementType?: boolean -): arkts.StructInfo { - const metadata: Record = structInfo.metadata ?? {}; - metadata[propertyName] = { - name: propertyName, - properties, - modifiers, - hasStateManagementType, - }; - structInfo.metadata = metadata; - return structInfo; -} - export function moveToFront(arr: T[], idx: number): T[] { if (idx < 0 || idx >= arr.length) { throw new Error(`Index ${idx} is out of bounds for array of length ${arr.length}`); @@ -106,4 +88,4 @@ export function moveToFront(arr: T[], idx: number): T[] { const copy = [...arr]; const [item] = copy.splice(idx, 1); return [item, ...copy]; -} \ No newline at end of file +} diff --git a/arkui-plugins/test/local/@ohos.arkui.component.enums.d.ets b/arkui-plugins/common/declaration-collector.ts similarity index 37% rename from arkui-plugins/test/local/@ohos.arkui.component.enums.d.ets rename to arkui-plugins/common/declaration-collector.ts index e72c21ace..81a1160bc 100644 --- a/arkui-plugins/test/local/@ohos.arkui.component.enums.d.ets +++ b/arkui-plugins/common/declaration-collector.ts @@ -1,10 +1,10 @@ /* - * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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 + * 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, @@ -12,42 +12,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import * as arkts from '@koalaui/libarkts'; -export declare enum FlexAlign { - Start = 0, - Center = 1, - End = 2, - SpaceBetween = 3, - SpaceAround = 4, - SpaceEvenly = 5 -} +export class DeclarationCollector { + public fromExternalSourceNames: Set; + static instance: DeclarationCollector; -export declare enum HorizontalAlign { - Start = 0, - Center = 1, - End = 2 -} + private constructor() { + this.fromExternalSourceNames = new Set(); + } -export declare enum IlluminatedType { - NONE = 0, - BORDER = 1, - CONTENT = 2, - BORDER_CONTENT = 3, - BLOOM_BORDER = 4, - BLOOM_BORDER_CONTENT = 5 -} + static getInstance(): DeclarationCollector { + if (!this.instance) { + this.instance = new DeclarationCollector(); + } + return this.instance; + } -export declare enum Color { - White = 0, - Black = 1, - Blue = 2, - Brown = 3, - Gray = 4, - Green = 5, - Grey = 6, - Orange = 7, - Pink = 8, - Red = 9, - Yellow = 10, - Transparent = 11 + collect(decl: arkts.AstNode | undefined): void { + if (!decl) { + return; + } + const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; + this.fromExternalSourceNames.add(moduleName); + } + + reset(): void { + this.fromExternalSourceNames.clear(); + } } \ No newline at end of file diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts index f0ad9ccb4..95843cb7b 100644 --- a/arkui-plugins/common/plugin-context.ts +++ b/arkui-plugins/common/plugin-context.ts @@ -74,10 +74,23 @@ export class PluginContext { } } +export interface DependentModuleConfig { + packageName: string; + moduleName: string; + moduleType: string; + modulePath: string; + sourceRoots: string[]; + entryFile: string; + language: string, + declFilesPath?: string, + dependencies?: string[] +} + export interface ProjectConfig { bundleName: string; moduleName: string; cachePath: string; + dependentModuleList: DependentModuleConfig[]; } export type PluginHandlerFunction = () => void; diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 1218495d3..f2644856a 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -24,41 +24,82 @@ export const EXTERNAL_SOURCE_PREFIX_NAMES: (string | RegExp)[] = [ /@arkts\..*/, /@ohos\.(?!arkui).*/, /@system\..*/, - /arkui\.(?![Uu]serView$)[A-Z]/, // temporary solution + /arkui\.(?!Ark|[Uu]serView$)[A-Z]/, // temporary solution /ability\..*/, ]; +export const ARKUI_IMPORT_PREFIX_NAMES: (string | RegExp)[] = [/@ohos\..*/, /arkui\..*/]; + export const ARKUI_COMPONENT_IMPORT_NAME: string = '@ohos.arkui.component'; export const ARKUI_STATEMANAGEMENT_IMPORT_NAME: string = '@ohos.arkui.stateManagement'; export const KIT_ARKUI_NAME: string = '@kit.ArkUI'; -export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ - ARKUI_COMPONENT_IMPORT_NAME, - ARKUI_STATEMANAGEMENT_IMPORT_NAME, -]; +export const KOALAUI_COMMON_IMPORT_NAME: string = '@koalaui.runtime.common'; export const IMPORT_SOURCE_MAP: Map> = new Map>([ ['arkui.stateManagement.runtime', new Set(['memo', '__memo_context_type', '__memo_id_type'])] ]); -export const OUTPUT_DEPENDENCY_MAP: Map = new Map([ - ['$r', ['_r']], - ['$rawfile', ['_rawfile']], - ['State', ['StateDecoratedVariable']], - ['Link', ['LinkDecoratedVariable', 'DecoratedV1VariableBase']], - ['Prop', ['PropDecoratedVariable']], - ['Provide', ['ProvideDecoratedVariable']], - ['Consume', ['ConsumeDecoratedVariable']], - ['StorageProp', ['StoragePropDecoratedVariable']], - ['StorageLink', ['StorageLinkDecoratedVariable']], - ['LocalStorageLink', ['StorageLinkState', 'MutableState', 'observableProxy']], - ['LocalStorageProp', ['StorageLinkState', 'SyncedProperty', 'observableProxy', 'propState']], - ['ObjectLink', ['ObjectLinkDecoratedVariable']], - ['Observed', ['MutableStateMeta', 'BackingValue', 'setObservationDepth', 'IObservedObject', 'int32', 'WatchIdType', 'SubscribedWatches']], - ['Track', ['MutableStateMeta', 'BackingValue', 'setObservationDepth', 'IObservedObject', 'int32', 'WatchIdType', 'SubscribedWatches']], - ['$$', ['Bindable']], +export const IMPORT_SOURCE_MAP_V2: Map = new Map([ + ['$r', ARKUI_COMPONENT_IMPORT_NAME], + ['$rawfile', ARKUI_COMPONENT_IMPORT_NAME], + ['_r', ARKUI_COMPONENT_IMPORT_NAME], + ['_rawfile', ARKUI_COMPONENT_IMPORT_NAME], + ['Bindable', ARKUI_COMPONENT_IMPORT_NAME], + ['State', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['Prop', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['Provide', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['Consume', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['StorageLink', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['StorageProp', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['LocalStorageLink', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['LocalStorageProp', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['Watch', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['ObjectLink', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['StateDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['MutableState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['contextLocalStateOf', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['contextLocal', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['observableProxy', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['SyncedProperty', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['objectLinkState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['propState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['AppStorageLinkState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['StorageLinkState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['DecoratedV1VariableBase', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['LinkDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['PropDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['StorageLinkDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['StoragePropDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['ProvideDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['ConsumeDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['ObjectLinkDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['MutableStateMeta', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['BackingValue', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['setObservationDepth', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['IObservedObject', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['WatchIdType', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['SubscribedWatches', ARKUI_STATEMANAGEMENT_IMPORT_NAME], + ['int32', KOALAUI_COMMON_IMPORT_NAME], ]); +export const OUTPUT_DEPENDENCY_MAP: Map = new Map([ + ['$r', []], + ['$rawfile', []], + ['State', []], + ['Link', []], + ['Prop', []], + ['Provide', []], + ['Consume', []], + ['StorageProp', []], + ['StorageLink', []], + ['LocalStorageLink', []], + ['LocalStorageProp', []], + ['ObjectLink', []], + ['Observed', []], + ['Track', []], + ['$$', []], +]); export enum InteroperAbilityNames { ARKTS_1_1 = '1.1', diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 9281c0b78..946ce5723 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -80,7 +80,7 @@ function sortExternalSources(externalSources: arkts.ExternalSource[]): arkts.Ext export interface StructMap { [key: string]: string; -} +} export class ProgramVisitor extends AbstractVisitor { private readonly pluginName: string; @@ -113,7 +113,7 @@ export class ProgramVisitor extends AbstractVisitor { this.legacyModuleList = []; } - getLegacyModule(): void { + private getLegacyModule(): void { const moduleList = this.pluginContext?.getProjectConfig()?.dependentModuleList; if (moduleList === undefined) { return; @@ -125,171 +125,209 @@ export class ProgramVisitor extends AbstractVisitor { continue; } if (!this.legacyStructMap.has(moduleName)) { - this.legacyStructMap.set(moduleName, {}); + this.legacyStructMap.set(moduleName, {}); this.legacyModuleList.push(moduleName); } } } - dumpHeaders( - currProgram: arkts.Program, + private dumpExternalSource( + script: arkts.AstNode, name: string, cachePath: string | undefined, prefixName: string, extensionName: string ): void { debugDump( - currProgram.astNode.dumpSrc(), - getDumpFileName(this.state, prefixName, undefined, name), + script.dumpSrc(), + getDumpFileName(this.state, prefixName, undefined, name), true, cachePath, extensionName ); } - programVisitor(program: arkts.Program): arkts.Program { - const skipPrefixes: (string | RegExp)[] = this.skipPrefixNames; + private visitLegacyInExternalSource(currProgram: arkts.Program, name: string): void { + if (this.state === arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) { + const structList = this.visitorLegacy(currProgram.astNode, currProgram, name); + const moduleName = name.split('/')[0]; + const structMap = this.legacyStructMap.get(moduleName)!; + for (const struct of structList) { + structMap[struct] = name; + } + } + } + + private visitNonLegacyInExternalSource( + program: arkts.Program, + currProgram: arkts.Program, + name: string, + cachePath?: string + ): void { + const extensionName: string = program.fileNameWithExtension; + this.dumpExternalSource(currProgram.astNode, name, cachePath, 'ORI', extensionName); + const script = this.visitor(currProgram.astNode, currProgram, name); + if (script) { + this.dumpExternalSource(script, name, cachePath, this.pluginName, extensionName); + } + } + + private visitNextProgramInQueue( + queue: arkts.Program[], + visited: Set, + externalSource: arkts.ExternalSource + ): void { + const nextProgramArr: arkts.Program[] = externalSource.programs ?? []; + for (const nextProgram of nextProgramArr) { + this.filenames.set(nextProgram.peer, externalSource.getName()); + if (!visited.has(nextProgram.peer)) { + queue.push(nextProgram); + } + } + } + + private visitExternalSources( + program: arkts.Program, + programQueue: arkts.Program[] + ): void { const visited = new Set(); - const queue: arkts.Program[] = [program]; + const queue: arkts.Program[] = programQueue; this.getLegacyModule(); + arkts.Performance.getInstance().createEvent(`${this.state}-external-source`); while (queue.length > 0) { const currProgram = queue.shift()!; - if (visited.has(currProgram.peer)) { + if (visited.has(currProgram.peer) || currProgram.isASTLowered()) { continue; } if (currProgram.peer !== program.peer) { const name: string = this.filenames.get(currProgram.peer)!; const cachePath: string | undefined = this.pluginContext?.getProjectConfig()?.cachePath; if (this.legacyModuleList && matchPrefix(this.legacyModuleList, name)) { - if (this.state === arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) { - const structList = this.visitorLegacy(currProgram.astNode, currProgram, name); - const moduleName = name.split('/')[0]; - const structMap = this.legacyStructMap.get(moduleName)!; - for (const struct of structList) { - structMap[struct] = name; - } - } + this.visitLegacyInExternalSource(currProgram, name); } else { - this.dumpHeaders(currProgram, name, cachePath, 'Ori', program.programFileNameWithExtension); - const script = this.visitor(currProgram.astNode, currProgram, name); - if (script) { - this.dumpHeaders(currProgram, name, cachePath, this.pluginName, program.programFileNameWithExtension); - } + this.visitNonLegacyInExternalSource(program, currProgram, name, cachePath); } } visited.add(currProgram.peer); - for (const externalSource of sortExternalSources(currProgram.externalSources)) { - if (matchPrefix(skipPrefixes, externalSource.getName())) { + for (const externalSource of currProgram.externalSources) { + if (matchPrefix(this.skipPrefixNames, externalSource.getName())) { continue; } - const nextProgramArr: arkts.Program[] = externalSource.programs ?? []; - for (const nextProgram of nextProgramArr) { - this.filenames.set(nextProgram.peer, externalSource.getName()); - if (!visited.has(nextProgram.peer)) { - queue.push(nextProgram); - } - } + this.visitNextProgramInQueue(queue, visited, externalSource); } } - const hasLegacy = this.legacyStructMap.size ? true : false; + arkts.Performance.getInstance().stopEvent(`${this.state}-external-source`, false); + } + + programVisitor(program: arkts.Program): arkts.Program { + this.visitExternalSources(program, [program]); + + arkts.Performance.getInstance().createEvent(`${this.state}-source`); let programScript = program.astNode; - programScript = this.visitor(programScript, program, this.externalSourceName, hasLegacy); + programScript = this.visitor(programScript, program, this.externalSourceName); + arkts.Performance.getInstance().stopEvent(`${this.state}-source`, false); + const visitorsToReset = flattenVisitorsInHooks(this.hooks, this.state); visitorsToReset.forEach((visitor) => visitor.reset()); + return program; } - preVisitor( + private preVisitor( + hook: ProgramHookLifeCycle | undefined, node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string ): void { - const isExternal: boolean = !!externalSourceName; - let hook: ProgramHookLifeCycle | undefined = isExternal ? this.hooks?.external : this.hooks?.source; let script: arkts.EtsScript = node as arkts.EtsScript; - const preVisitors = hook?.pre?.visitors ?? []; for (const transformer of preVisitors) { - transformer.isExternal = isExternal; - transformer.externalSourceName = externalSourceName; - transformer.program = program; - transformer.visitor(script); + this.visitTransformer(transformer, script, externalSourceName, program); if (!this.hooks?.external?.pre?.resetAfter) { transformer.reset(); } } } - postVisitor( + private postVisitor( + hook: ProgramHookLifeCycle | undefined, node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string ): void { - const isExternal: boolean = !!externalSourceName; - let hook: ProgramHookLifeCycle | undefined = isExternal ? this.hooks?.external : this.hooks?.source; let script: arkts.EtsScript = node as arkts.EtsScript; - const postVisitors = hook?.post?.visitors ?? []; for (const transformer of postVisitors) { - transformer.isExternal = isExternal; - transformer.externalSourceName = externalSourceName; - transformer.program = program; - transformer.visitor(script); + this.visitTransformer(transformer, script, externalSourceName, program); if (!this.hooks?.external?.pre?.resetAfter) { transformer.reset(); } } } - visitor( - node: arkts.AstNode, - program?: arkts.Program, - externalSourceName?: string, - hasLegacy: boolean = false - ): arkts.EtsScript { + visitor(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): arkts.EtsScript { + arkts.Performance.getInstance().createEvent(`${this.state}-${externalSourceName ?? 'SOURCE'}`); + let hook: ProgramHookLifeCycle | undefined; + let script: arkts.EtsScript = node as arkts.EtsScript; let count: number = 0; const isExternal: boolean = !!externalSourceName; // pre-run visitors - this.preVisitor(node, program, externalSourceName); + hook = isExternal ? this.hooks?.external : this.hooks?.source; + this.preVisitor(hook, node, program, externalSourceName); for (const transformer of this.visitors) { - transformer.isExternal = isExternal; - transformer.externalSourceName = externalSourceName; - transformer.program = program; - if (hasLegacy && transformer instanceof ComponentTransformer) { + if (this.legacyStructMap.size > 0 && transformer instanceof ComponentTransformer) { transformer.registerMap(this.legacyStructMap); } - script = transformer.visitor(script) as arkts.EtsScript; + this.visitTransformer(transformer, script, externalSourceName, program); transformer.reset(); + arkts.Performance.getInstance().createEvent('set-all-parent'); arkts.setAllParents(script); + arkts.Performance.getInstance().stopEvent('set-all-parent', false); if (!transformer.isExternal) { debugDump( script.dumpSrc(), getDumpFileName(this.state, this.pluginName, count, transformer.constructor.name), true, this.pluginContext?.getProjectConfig()?.cachePath, - program!.programFileNameWithExtension + program!.fileNameWithExtension ); count += 1; } } // post-run visitors - this.postVisitor(node, program, externalSourceName); + hook = isExternal ? this.hooks?.external : this.hooks?.source; + this.postVisitor(hook, node, program, externalSourceName); + arkts.Performance.getInstance().stopEvent(`${this.state}-${externalSourceName ?? 'SOURCE'}`, false); return script; } - visitorLegacy( - node: arkts.AstNode, - program?: arkts.Program, - externalSourceName?: string, - ): string[] { - const visitor = new LegacyTransformer(); - const script = visitor.visitor(node) as arkts.EtsScript; - const structList = visitor.getList(); + private visitorLegacy(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): string[] { + const transformer = new LegacyTransformer(); + transformer.isExternal = !!externalSourceName; + transformer.externalSourceName = externalSourceName; + transformer.program = program; + transformer.visitor(node); + const structList = transformer.getList(); return structList; } + + private visitTransformer( + transformer: AbstractVisitor, + script: arkts.EtsScript, + externalSourceName?: string, + program?: arkts.Program + ): arkts.EtsScript { + arkts.Performance.getInstance().createEvent(transformer.constructor.name); + transformer.isExternal = !!externalSourceName; + transformer.externalSourceName = externalSourceName; + transformer.program = program; + const newScript = transformer.visitor(script) as arkts.EtsScript; + arkts.Performance.getInstance().stopEvent(transformer.constructor.name, false); + return newScript; + } } diff --git a/arkui-plugins/test/local/@ohos.arkui.component.common.d.ets b/arkui-plugins/common/safe-types.ts similarity index 31% rename from arkui-plugins/test/local/@ohos.arkui.component.common.d.ets rename to arkui-plugins/common/safe-types.ts index 2ff6ea60a..899ef0c39 100644 --- a/arkui-plugins/test/local/@ohos.arkui.component.common.d.ets +++ b/arkui-plugins/common/safe-types.ts @@ -1,10 +1,10 @@ /* - * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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 + * 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, @@ -13,43 +13,31 @@ * limitations under the License. */ -import { Dimension, Length, ResourceColor } from "@ohos.arkui.component.units"; -import { IlluminatedType } from "@ohos.arkui.component.enums"; -import { memo } from '@ohos.arkui.stateManagement.runtime'; - -@Retention({policy: "SOURCE"}) -export @interface BuilderLambda { - value: string -} - -@Retention({policy: "SOURCE"}) -export declare @interface ComponentBuilder {}; - -@Retention({policy: "SOURCE"}) -export declare @interface BuilderParam {}; - -@Retention({policy: "SOURCE"}) -export declare @interface Builder {}; - -export declare interface LightSource { - positionX: Dimension; - positionY: Dimension; - positionZ: Dimension; - intensity: number; - color?: ResourceColor; -} - -export declare interface PointLightStyle { - lightSource?: LightSource; - illuminated?: IlluminatedType; - bloom?: number; -} - -export declare interface CommonMethod { - @memo - width(w: Length): this; - @memo - height(h: Length): this; - @memo - backgroundColor(color: ResourceColor): this; -} \ No newline at end of file +import * as arkts from '@koalaui/libarkts'; + +export type PartialExcept = Partial & Pick; + +type PartialArray = T extends readonly any[] | any[] ? T | undefined : T; +type PartialAstNode = T extends arkts.AstNode ? T | undefined : T; +type PartialObject = T extends object ? { [P in keyof T]?: T[P] } : T; +type PartialPrimitive = T; + +export type PartialNested = { + [P in keyof T]?: T[P] extends readonly any[] | any[] + ? PartialArray + : T[P] extends arkts.AstNode + ? PartialAstNode + : T[P] extends object + ? PartialObject + : PartialPrimitive; +}; + +type NestedKey = { + [P in keyof T]: P extends K ? T[P] : T[P] extends object ? NestedKey : T[P]; + }; + +export type PickNested = { + [P in keyof T]: P extends K ? T[P] : T[P] extends object ? NestedKey : T[P]; +}; + +export type PartialNestedExcept = PartialNested> & PickNested; \ No newline at end of file diff --git a/arkui-plugins/interop-plugins/index.ts b/arkui-plugins/interop-plugins/index.ts index 404892c34..21c971ce0 100644 --- a/arkui-plugins/interop-plugins/index.ts +++ b/arkui-plugins/interop-plugins/index.ts @@ -88,7 +88,6 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { program = programVisitor.programVisitor(program); script = program.astNode; - arkts.GlobalInfo.getInfoInstance()?.reset(); arkts.recheckSubtree(script); this.setArkTSAst(script); debugLog('interopTransform:checked exit'); diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 6259f6b27..fb059b409 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -72,6 +72,9 @@ export class FunctionTransformer extends AbstractVisitor { private readonly returnTransformer: ReturnTransformer; private readonly signatureTransformer: SignatureTransformer; + /* Tracking whether should import `__memo_context_type` and `__memo_id_type` */ + private modified = false; + constructor(options: FunctionTransformerOptions) { super(options); this.positionalIdTracker = options.positionalIdTracker; @@ -87,6 +90,7 @@ export class FunctionTransformer extends AbstractVisitor { super.reset(); this.scopes = []; this.stable = 0; + this.modified = false; this.parameterTransformer.reset(); this.returnTransformer.reset(); this.signatureTransformer.reset(); @@ -213,7 +217,7 @@ export class FunctionTransformer extends AbstractVisitor { checkMemoCallInFunction() { const scope = this.scopes[this.scopes.length - 1]; - if (scope?.regardAsSameScope === false && scope?.isMemo == false) { + if (scope?.regardAsSameScope === false && scope?.isMemo === false) { console.error(`Attempt to call @memo-function`); throw 'Invalid @memo usage'; } @@ -224,6 +228,9 @@ export class FunctionTransformer extends AbstractVisitor { if (!scriptFunction.body || !arkts.isBlockStatement(scriptFunction.body)) { return scriptFunction; } + if (this.parameterTransformer.isTracked(scriptFunction.body)) { + return scriptFunction; + } if (hasMemoIntrinsicAnnotation(scriptFunction) || hasMemoEntryAnnotation(scriptFunction)) { return scriptFunction; } @@ -255,6 +262,8 @@ export class FunctionTransformer extends AbstractVisitor { afterReturnTransformer, returnTypeInfo.node ); + this.modified = true; + this.parameterTransformer.track(updateScriptFunction.body); return updateScriptFunction; } @@ -267,14 +276,14 @@ export class FunctionTransformer extends AbstractVisitor { hasMemoIntrinsicAnnotation(node.scriptFunction) || hasMemoEntryAnnotation(node.scriptFunction); if (isMemo && node.scriptFunction.body) { + const hasIntrinsic = hasMemoIntrinsicAnnotation(node.scriptFunction); updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, node.name, - arkts.factory.createFunctionExpression( - this.signatureTransformer.visitor( - removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)) - ) + this.signatureTransformer.visitor( + removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)), + hasIntrinsic ), node.modifiers, false @@ -284,7 +293,7 @@ export class FunctionTransformer extends AbstractVisitor { node, node.kind, node.name, - arkts.factory.createFunctionExpression(this.signatureTransformer.visitor(node.scriptFunction)), + this.signatureTransformer.visitor(node.scriptFunction), node.modifiers, false ); @@ -292,6 +301,7 @@ export class FunctionTransformer extends AbstractVisitor { if (!!updateOverloads) { updateMethod.setOverloads(castOverloadsToMethods(updateOverloads)); } + this.modified ||= this.signatureTransformer.modified; return updateMethod; } @@ -309,6 +319,7 @@ export class FunctionTransformer extends AbstractVisitor { this.enterAnonymousScope(it.scriptFunction); const res = this.updateScriptFunction(it.scriptFunction); this.exitAnonymousScope(); + this.modified = true; return arkts.factory.updateArrowFunction(it, res); } return it; @@ -327,10 +338,12 @@ export class FunctionTransformer extends AbstractVisitor { if (parametrizedNodeHasReceiver(decl.scriptFunction) && isMemo) { updatedArguments = moveToFront(updatedArguments, 2); } + this.modified = true; return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, updatedArguments); } private updateDeclaredCallWithName(node: arkts.CallExpression, name: string): arkts.CallExpression { + this.modified = true; return factory.insertHiddenArgumentsToCall(node, this.positionalIdTracker.id(name)); } @@ -342,15 +355,18 @@ export class FunctionTransformer extends AbstractVisitor { this.signatureTransformer.visitor(node.expression.scriptFunction) ); } + const that = this; const updatedArguments: arkts.AstNode[] = node.arguments.map((it) => { if (arkts.isArrowFunctionExpression(it) && isMemoArrowFunction(it)) { - this.enterAnonymousScope(it.scriptFunction); - const res = this.updateScriptFunction(it.scriptFunction); - this.exitAnonymousScope(); + that.enterAnonymousScope(it.scriptFunction); + const res = that.updateScriptFunction(it.scriptFunction); + that.exitAnonymousScope(); + that.modified = true; return arkts.factory.updateArrowFunction(it, res); } return it; }); + this.modified ||= this.signatureTransformer.modified; return arkts.factory.updateCallExpression(node, newExpression, node.typeArguments, updatedArguments); } @@ -374,6 +390,7 @@ export class FunctionTransformer extends AbstractVisitor { this.exitAnonymousScope(); const newNode = this.updateAnonymousCallWithMemoParams(node); + this.modified = true; return arkts.factory.updateCallExpression( node, arkts.factory.updateArrowFunction(expression, res), @@ -442,6 +459,7 @@ export class FunctionTransformer extends AbstractVisitor { throw 'Invalid @memo usage'; } + this.modified = true; return arkts.factory.updateClassProperty( node, node.key, @@ -461,12 +479,14 @@ export class FunctionTransformer extends AbstractVisitor { this.exitAnonymousScope(); if (!scope.isMemo) { if (!!node.typeAnnotation) { - return arkts.factory.updateTSTypeAliasDeclaration( + const newNode = arkts.factory.updateTSTypeAliasDeclaration( node, node.id, node.typeParams, this.signatureTransformer.visitor(node.typeAnnotation) ); + this.modified ||= this.signatureTransformer.modified; + return newNode; } return node; } @@ -477,6 +497,7 @@ export class FunctionTransformer extends AbstractVisitor { throw 'Invalid @memo usage'; } + this.modified = true; return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation); } @@ -495,6 +516,7 @@ export class FunctionTransformer extends AbstractVisitor { const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); this.exitAnonymousScope(); + this.modified = true; return arkts.factory.updateArrowFunction(node, this.signatureTransformer.visitor(res)); } @@ -537,6 +559,7 @@ export class FunctionTransformer extends AbstractVisitor { initializer = arkts.factory.updateArrowFunction(initializer, res); } + this.modified = true; return arkts.factory.updateVariableDeclarator( node, node.flag, @@ -569,6 +592,7 @@ export class FunctionTransformer extends AbstractVisitor { throw 'Invalid @memo usage'; } + this.modified = true; return arkts.factory.updateTSAsExpression( node, arkts.factory.updateArrowFunction(expr, res), @@ -596,6 +620,7 @@ export class FunctionTransformer extends AbstractVisitor { const res = this.updateScriptFunction(value.scriptFunction, value.scriptFunction.id?.name); this.exitAnonymousScope(); + this.modified = true; return arkts.factory.updateProperty(node, key, arkts.factory.updateArrowFunction(value, res)); } @@ -618,6 +643,7 @@ export class FunctionTransformer extends AbstractVisitor { const res = this.updateScriptFunction(right.scriptFunction, right.scriptFunction.id?.name); this.exitAnonymousScope(); + this.modified = true; return arkts.factory.updateAssignmentExpression( node, node.left!, @@ -658,6 +684,9 @@ export class FunctionTransformer extends AbstractVisitor { const thisAttribute = findThisAttribute(node.left!)!; return this.updateThisAttributeAssignment(node, thisAttribute, node.right); } + if (arkts.isEtsScript(node) && this.modified) { + factory.createContextTypesImportDeclaration(this.program); + } return node; } } diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index 58f785dbd..aa5c2de65 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -29,7 +29,7 @@ export function unmemoizeTransform(): Plugins { name: 'memo-plugin', checked(this: PluginContext) { console.log('[MEMO PLUGIN] AFTER CHECKED ENTER'); - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; let script = program.astNode; @@ -41,7 +41,7 @@ export function unmemoizeTransform(): Plugins { getDumpFileName(0, 'SRC', 5, 'MEMO_AfterCheck_Begin'), true, cachePath, - program.programFileNameWithExtension + program.fileNameWithExtension ); arkts.Performance.getInstance().createEvent('memo-checked'); @@ -70,7 +70,7 @@ export function unmemoizeTransform(): Plugins { program = programVisitor.programVisitor(program); script = program.astNode; - arkts.Performance.getInstance().stopEvent('memo-checked', true); + arkts.Performance.getInstance().stopEvent('memo-checked', false); debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); debugDump( @@ -78,14 +78,17 @@ export function unmemoizeTransform(): Plugins { getDumpFileName(0, 'SRC', 6, 'MEMO_AfterCheck_End'), true, cachePath, - program.programFileNameWithExtension + program.fileNameWithExtension ); arkts.Performance.getInstance().createEvent('memo-recheck'); arkts.recheckSubtree(script); - arkts.Performance.getInstance().stopEvent('memo-recheck', true); + arkts.Performance.getInstance().stopEvent('memo-recheck', false); - arkts.Performance.getInstance().clearAllEvents(); + arkts.Performance.getInstance().clearAllEvents(true); + arkts.Performance.getInstance().visualizeEvents(true); + arkts.Performance.getInstance().clearHistory(); + arkts.Performance.getInstance().clearTotalDuration(); this.setArkTSAst(script); console.log('[MEMO PLUGIN] AFTER CHECKED EXIT'); diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index 3104fe592..37eed959b 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -40,9 +40,8 @@ export class factory { arkts.factory.createIdentifier(RuntimeNames.ID_TYPE) ); } - // TODO: Currently, import declaration can only be inserted at after-parsed stage. static createContextTypesImportDeclaration(program?: arkts.Program): void { - const source: arkts.StringLiteral = arkts.factory.createStringLiteral(RuntimeNames.CONTEXT_TYPE_DEFAULT_IMPORT); + const source: arkts.StringLiteral = arkts.factory.createStringLiteral(RuntimeNames.MEMO_IMPORT_NAME); const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, [factory.createContextTypeImportSpecifier(), factory.createIdTypeImportSpecifier()], diff --git a/arkui-plugins/memo-plugins/parameter-transformer.ts b/arkui-plugins/memo-plugins/parameter-transformer.ts index d5e615e99..061e5b80b 100644 --- a/arkui-plugins/memo-plugins/parameter-transformer.ts +++ b/arkui-plugins/memo-plugins/parameter-transformer.ts @@ -46,12 +46,14 @@ export class ParameterTransformer extends AbstractVisitor { private rewriteMemoInfos?: Map; private rewriteThis?: boolean; private skipNode?: arkts.VariableDeclaration; + private visited: Set; private positionalIdTracker: PositionalIdTracker; constructor(options: ParameterTransformerOptions) { super(options); this.positionalIdTracker = options.positionalIdTracker; + this.visited = new Set(); } reset(): void { @@ -60,6 +62,7 @@ export class ParameterTransformer extends AbstractVisitor { this.rewriteCalls = undefined; this.rewriteMemoInfos = undefined; this.skipNode = undefined; + this.visited.clear(); } withThis(flag: boolean): ParameterTransformer { @@ -79,7 +82,7 @@ export class ParameterTransformer extends AbstractVisitor { it.param.identifier.name.startsWith(RuntimeNames.GENSYM) ? it.ident.originalPeer : it.param.originalPeer, - (passArgs: arkts.Expression[]) => { + (passArgs: arkts.Expression[]): arkts.CallExpression => { return factory.createMemoParameterAccessCall(it.ident.name, passArgs); }, ]; @@ -91,7 +94,7 @@ export class ParameterTransformer extends AbstractVisitor { it.param.identifier.name.startsWith(RuntimeNames.GENSYM) ? it.ident.originalPeer : it.param.originalPeer, - () => { + (): arkts.MemberExpression => { return factory.createMemoParameterAccess(it.ident.name); }, ]; @@ -119,6 +122,16 @@ export class ParameterTransformer extends AbstractVisitor { return this; } + track(node: arkts.AstNode | undefined): void { + if (!!node?.peer) { + this.visited.add(node.peer); + } + } + + isTracked(node: arkts.AstNode | undefined): boolean { + return !!node?.peer && this.visited.has(node.peer); + } + private updateArrowFunctionFromVariableDeclareInit( initializer: arkts.ArrowFunctionExpression, returnType: arkts.TypeNode | undefined @@ -141,13 +154,15 @@ export class ParameterTransformer extends AbstractVisitor { returnTypeInfo, this.positionalIdTracker.id() ); - const afterParameterTransformer = new ParameterTransformer({ + const paramaterTransformer = new ParameterTransformer({ positionalIdTracker: this.positionalIdTracker, - }) + }); + const returnTransformer = new ReturnTransformer(); + const afterParameterTransformer = paramaterTransformer .withParameters(parameterIdentifiers) .skip(memoParametersDeclaration) .visitor(body); - const afterReturnTransformer = new ReturnTransformer() + const afterReturnTransformer = returnTransformer .skip(syntheticReturnStatement) .registerReturnTypeInfo(returnTypeInfo) .visitor(afterParameterTransformer); @@ -156,6 +171,9 @@ export class ParameterTransformer extends AbstractVisitor { afterReturnTransformer, returnTypeInfo.node ); + paramaterTransformer.reset(); + returnTransformer.reset(); + this.track(updateScriptFunction.body); return arkts.factory.updateArrowFunction(initializer, updateScriptFunction); } @@ -229,12 +247,12 @@ export class ParameterTransformer extends AbstractVisitor { } if (!!declarator.initializer && arkts.isIdentifier(declarator.initializer)) { const decl = arkts.getPeerDecl(declarator.initializer.originalPeer); - if (decl && that.rewriteIdentifiers?.has(decl.originalPeer)) { + if (decl && that.rewriteIdentifiers?.has(decl.peer)) { return arkts.factory.updateVariableDeclarator( declarator, declarator.flag, declarator.name, - that.rewriteIdentifiers.get(decl.originalPeer)!() + that.rewriteIdentifiers.get(decl.peer)!() ); } } @@ -266,12 +284,12 @@ export class ParameterTransformer extends AbstractVisitor { } if (arkts.isCallExpression(beforeChildren) && arkts.isIdentifier(beforeChildren.expression)) { const decl = arkts.getPeerDecl(beforeChildren.expression.originalPeer); - if (decl && this.rewriteCalls?.has(decl.originalPeer)) { - const updateCall = this.rewriteCalls.get(decl.originalPeer)!( + if (decl && this.rewriteCalls?.has(decl.peer)) { + const updateCall = this.rewriteCalls.get(decl.peer)!( beforeChildren.arguments.map((it) => this.visitor(it) as arkts.Expression) ); - if (this.rewriteMemoInfos?.has(decl.originalPeer)) { - const memoInfo = this.rewriteMemoInfos.get(decl.originalPeer)!; + if (this.rewriteMemoInfos?.has(decl.peer)) { + const memoInfo = this.rewriteMemoInfos.get(decl.peer)!; return this.updateCallReDeclare(updateCall, beforeChildren.expression, memoInfo); } return updateCall; @@ -280,8 +298,8 @@ export class ParameterTransformer extends AbstractVisitor { const node = this.visitEachChild(beforeChildren); if (arkts.isIdentifier(node)) { const decl = arkts.getPeerDecl(node.originalPeer); - if (decl && this.rewriteIdentifiers?.has(decl.originalPeer)) { - return this.rewriteIdentifiers.get(decl.originalPeer)!(); + if (decl && this.rewriteIdentifiers?.has(decl.peer)) { + return this.rewriteIdentifiers.get(decl.peer)!(); } } if (arkts.isThisExpression(node) && this.rewriteThis) { diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index 801d41fcc..b7fa8a62d 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -15,11 +15,18 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; -import { hasMemoAnnotation, hasMemoIntrinsicAnnotation, parametrizedNodeHasReceiver } from './utils'; +import { + hasMemoAnnotation, + hasMemoIntrinsicAnnotation, + parametrizedNodeHasReceiver, + isMemoTSTypeAliasDeclaration, +} from './utils'; import { AbstractVisitor } from '../common/abstract-visitor'; function isScriptFunctionFromGetter(node: arkts.ScriptFunction): boolean { return ( + !!node.parent && + !!node.parent.parent && arkts.isFunctionExpression(node.parent) && arkts.isMethodDefinition(node.parent.parent) && node.parent.parent.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET @@ -28,6 +35,8 @@ function isScriptFunctionFromGetter(node: arkts.ScriptFunction): boolean { function isScriptFunctionFromSetter(node: arkts.ScriptFunction): boolean { return ( + !!node.parent && + !!node.parent.parent && arkts.isFunctionExpression(node.parent) && arkts.isMethodDefinition(node.parent.parent) && node.parent.parent.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET @@ -35,6 +44,7 @@ function isScriptFunctionFromSetter(node: arkts.ScriptFunction): boolean { } export class SignatureTransformer extends AbstractVisitor { + /* Tracking whether should import `__memo_context_type` and `__memo_id_type` */ public modified = false; reset(): void { @@ -122,7 +132,7 @@ export class SignatureTransformer extends AbstractVisitor { console.error(`@memo parameter's type has not been declared`); throw 'Invalid @memo usage'; } - const memoDecl = hasMemoAnnotation(decl) || hasMemoIntrinsicAnnotation(decl); + const memoDecl = isMemoTSTypeAliasDeclaration(decl); if (memoDecl) { return node as any as T; } diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index 3e90dcfa8..51a17d032 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -24,10 +24,11 @@ export enum RuntimeNames { ANNOTATION_ENTRY = 'memo_entry', ANNOTATION_INTRINSIC = 'memo_intrinsic', ANNOTATION_STABLE = 'memo_stable', + ANNOTATION_SKIP = 'memo_skip', COMPUTE = 'compute', CONTEXT = '__memo_context', CONTEXT_TYPE = '__memo_context_type', - CONTEXT_TYPE_DEFAULT_IMPORT = '@ohos.arkui.StateManagement.runtime', + MEMO_IMPORT_NAME = 'arkui.stateManagement.runtime', GENSYM = 'gensym%%_', ID = '__memo_id', ID_TYPE = '__memo_id_type', @@ -126,18 +127,16 @@ export function hasMemoEntryAnnotation(node: T): boolean } export function hasMemoStableAnnotation(node: arkts.ClassDefinition): boolean { - return node.annotations.some( - (it) => it.expr !== undefined && arkts.isIdentifier(it.expr) && it.expr.name === RuntimeNames.ANNOTATION_STABLE - ); + return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE)); +} + +export function hasMemoSkipAnnotation(node: arkts.ETSParameterExpression): boolean { + return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_SKIP)); } export function removeMemoAnnotation(node: T): T { const newAnnotations: arkts.AnnotationUsage[] = node.annotations.filter( - (it) => - !isMemoAnnotation(it, RuntimeNames.ANNOTATION) && - !isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC) && - !isMemoAnnotation(it, RuntimeNames.ANNOTATION_ENTRY) && - !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) + (it) => !isMemoAnnotation(it, RuntimeNames.ANNOTATION) && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) ); if (arkts.isEtsParameterExpression(node)) { node.annotations = newAnnotations; @@ -266,9 +265,12 @@ export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.Ar if (!arkts.isArrowFunctionExpression(node)) return false; // handling anonymous arrow function call - if (arkts.isCallExpression(node.parent) && node.parent.expression.peer === node.peer) return true; + if (!!node.parent && arkts.isCallExpression(node.parent) && node.parent.expression.peer === node.peer) { + return true; + } return ( + !!node.parent && !arkts.isVariableDeclarator(node.parent) && !arkts.isClassProperty(node.parent) && !(arkts.isCallExpression(node.parent) && node.parent.expression) @@ -388,7 +390,7 @@ export function isMemoVariableDeclarator(node: arkts.VariableDeclarator): boolea if (!!node.initializer && arkts.isArrowFunctionExpression(node.initializer)) { isMemo ||= isMemoArrowFunction(node.initializer); } - if (arkts.isVariableDeclaration(node.parent)) { + if (!!node.parent && arkts.isVariableDeclaration(node.parent)) { isMemo ||= isMemoVariableDeclaration(node.parent); } return isMemo; @@ -416,7 +418,7 @@ export function isMemoDeclaredMethod(decl: arkts.MethodDefinition): boolean { ) { return true; } - return isMemoMethodDefinition(decl); + return !hasMemoEntryAnnotation(decl.scriptFunction) && isMemoMethodDefinition(decl); } export function isDeclaredMethodWithMemoParams(decl: arkts.MethodDefinition): boolean { @@ -432,7 +434,7 @@ export function isMemoDeclaredIdentifier(decl: arkts.Identifier): boolean { if (findMemoFromTypeAnnotation(decl.typeAnnotation)) { return true; } - if (arkts.isVariableDeclarator(decl.parent)) { + if (!!decl.parent && arkts.isVariableDeclarator(decl.parent)) { return isMemoVariableDeclarator(decl.parent); } return false; @@ -485,7 +487,7 @@ export function findReturnTypeFromTypeAnnotation( export function getDeclResolveAlias(node: arkts.AstNode): arkts.AstNode | undefined { const decl = arkts.getDecl(node); - if (!!decl && arkts.isIdentifier(decl) && arkts.isVariableDeclarator(decl.parent)) { + if (!!decl && !!decl.parent && arkts.isIdentifier(decl) && arkts.isVariableDeclarator(decl.parent)) { if (!!decl.parent.initializer && arkts.isIdentifier(decl.parent.initializer)) { return getDeclResolveAlias(decl.parent.initializer); } @@ -553,9 +555,11 @@ export function buildReturnTypeInfo( export function buildeParamInfos(parameters: readonly arkts.ETSParameterExpression[]): ParamInfo[] { return [ - ...parameters.map((it) => { - return { ident: it.identifier, param: it }; - }), + ...parameters + .filter((it) => !hasMemoSkipAnnotation(it)) + .map((it) => { + return { ident: it.identifier, param: it }; + }), ]; } diff --git a/arkui-plugins/package.json b/arkui-plugins/package.json index 0267fb00d..75420af81 100644 --- a/arkui-plugins/package.json +++ b/arkui-plugins/package.json @@ -12,7 +12,8 @@ "compile:clean": "rm -rf lib", "clean:test": "rm -rf dist && rm -rf coverage", "prepare:test": "cp -rf $INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/koala-wrapper/build/native/ ../koala-wrapper/build/", - "test": "npm run clean:test && npm run prepare:test && LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib jest --coverage --logHeapUsage --config ./jest-test.config.js --silent", + "test": "npm run clean:test && npm run prepare:test && LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib jest --coverage --logHeapUsage --config ./jest-test.config.js --maxWorkers=25% --silent", + "test:gdb": "LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib gdb --args node ./node_modules/.bin/jest --config ./jest-test.config.js", "compile": "npm run compile:clean && npm run compile:plugins && cp -rf ./lib $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/" }, "devDependencies": { diff --git a/arkui-plugins/test/demo/localtest/build_config_template.json b/arkui-plugins/test/demo/localtest/build_config_template.json index 3855891d1..0df152f9d 100755 --- a/arkui-plugins/test/demo/localtest/build_config_template.json +++ b/arkui-plugins/test/demo/localtest/build_config_template.json @@ -1,6 +1,5 @@ { "plugins": { - "ui-syntax-plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/ui-syntax-plugins/index", "ui_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/ui-plugins/index", "memo_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/memo-plugins/index" }, @@ -9,7 +8,13 @@ "./demo/localtest/entry/new.ets" ], + "entryFiles": [ + "./demo/localtest/entry/new.ets" + ], + "packageName" : "entry", + "moduleType": "shared", + "hasMainModule": true, "buildType": "build", "buildMode": "Debug", diff --git a/arkui-plugins/test/demo/localtest/entry/new.ets b/arkui-plugins/test/demo/localtest/entry/new.ets index acdb7c3c3..a66597507 100755 --- a/arkui-plugins/test/demo/localtest/entry/new.ets +++ b/arkui-plugins/test/demo/localtest/entry/new.ets @@ -13,60 +13,62 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins -import { Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickEvent, UserView } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins -import { State, Link, StateDecoratedVariable, LinkDecoratedVariable,MutableState, stateOf, observableProxy } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { Text, Column, Component, Entry, Button, ClickEvent } from "@ohos.arkui.component" +import { State, Link, Prop } from "@ohos.arkui.stateManagement" import hilog from '@ohos.hilog' -function ArkUICompatible(init:(elmtId: number, instance: ESObject) => void, update: ((elmtId: number, instance: ESObject) => void)) { - -} - +@Entry @Component struct MyStateSample { - @State stateVar: string = "Parent"; - message: string = "var"; + @State stateVar: string = "state var"; + message: string = `click to change state variable, add **`; changeValue() { - this.stateVar+="~"; + this.stateVar+="**" } build() { - Column(undefined) { - Button("ParentChange").backgroundColor("#FFFF00FF") + Column() { + Button("clean variable").onClick((e: ClickEvent) => { this.stateVar = "state var" }) + Text("Hello World").fontSize(20) + Button(this.message).backgroundColor("#FFFF00FF") .onClick((e: ClickEvent) => { hilog.info(0x0000, 'testTag', 'On Click'); - this.changeValue(); + this.changeValue() }) Text(this.stateVar).fontSize(20) - ChildLink({stateVar: this.stateVar, stateVar1: this.stateVar, stateVar2: ""} as __Options_ChildLink) - } + Child({linkVar: this.stateVar, propVar: this.stateVar}) + }.margin(10) } } @Component -struct ChildLink { - @Link stateVar: string = "Child"; - @State stateVar1: string = "Child"; - @Link stateVar2: string = "Child"; - changeValue() { - this.stateVar+="~"; +struct Child { + @Link linkVar: string = ""; // TODO: remove this + @Prop propVar: string = "Prop"; + + changeValue1() { + this.linkVar+="!!" } - build() { - Button("ChildChange").backgroundColor("#FFFF00FF") - .onClick((e: ClickEvent) => { - hilog.info(0x0000, 'testTag', 'On Click'); - this.changeValue(); - }) - Text(this.stateVar).fontSize(50) + + changeValue2() { + this.propVar+="~~" } -} -export class ComExampleTrivialApplication extends UserView { - getBuilder() { - hilog.info(0x0000, 'testTag', 'getBuilder'); - let wrapper = @memo () => { - hilog.info(0x0000, 'testTag', 'MyStateSample'); - MyStateSample(undefined); + build() { + Column() { + Button(`click to change Link variable, add symbol !!`) + .backgroundColor("#4169E1") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + this.changeValue1() + }) + Button(`click to change Prop variable, add symbol ~~`) + .backgroundColor("#3CB371") + .onClick((e: ClickEvent) => { + hilog.info(0x0000, 'testTag', 'On Click'); + this.changeValue2() + }) + Text(`Link variable in child: ${this.linkVar}`).fontSize(30) + Text(`Prop variable in child: ${this.propVar}`).fontSize(30) } - return wrapper; } } \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets b/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets index 4f0f3b5cf..50ef19686 100644 --- a/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets +++ b/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "@ohos.arkui.stateManagement" import { Column, UIColumnAttribute } from "arkui.component.column" class MyStateSample { diff --git a/arkui-plugins/test/local/@ohos.arkui.component.d.ets b/arkui-plugins/test/demo/mock/common-utils/annotation.ets similarity index 59% rename from arkui-plugins/test/local/@ohos.arkui.component.d.ets rename to arkui-plugins/test/demo/mock/common-utils/annotation.ets index 0f74a9db4..e8a78a587 100644 --- a/arkui-plugins/test/local/@ohos.arkui.component.d.ets +++ b/arkui-plugins/test/demo/mock/common-utils/annotation.ets @@ -1,5 +1,5 @@ /* - * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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 @@ -13,10 +13,20 @@ * limitations under the License. */ -export * from "@ohos.arkui.component.customComponent"; -export * from "@ohos.arkui.component.common"; -export * from "@ohos.arkui.component.column"; -export * from "@ohos.arkui.component.text"; -export * from "@ohos.arkui.component.styledString"; -export * from "@ohos.arkui.component.enums"; -export * from "@ohos.arkui.component.units"; \ No newline at end of file +@Retention({policy:"SOURCE"}) @interface TestAnno {} + +type TestType = number; + +() => {}; + +class A { + prop: number = 1; + + method(arg1: number): void { + const a: number = arg1; + } +} + +interface __A { + prop: number; +} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets b/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets index 755a647b3..bfbaaec54 100644 --- a/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets +++ b/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets @@ -1,5 +1,5 @@ import { Component, Reusable} from "@ohos.arkui.component" -import { State, Link } from "@ohos.arkui.stateManagement" +import { State, Prop } from "@ohos.arkui.stateManagement" @Component struct MyStateSample { @@ -11,7 +11,7 @@ struct MyStateSample { @Component @Reusable struct Child { - @Link num: number = 1 + @Prop num: number = 1 @State num1: number = 2 build() { diff --git a/arkui-plugins/test/local/@ohos.arkui.stateManagement.d.ets b/arkui-plugins/test/demo/mock/imports/import-struct.ets similarity index 67% rename from arkui-plugins/test/local/@ohos.arkui.stateManagement.d.ets rename to arkui-plugins/test/demo/mock/imports/import-struct.ets index 9cb01ec59..d7cf79b5e 100644 --- a/arkui-plugins/test/local/@ohos.arkui.stateManagement.d.ets +++ b/arkui-plugins/test/demo/mock/imports/import-struct.ets @@ -13,6 +13,16 @@ * limitations under the License. */ -export * from "@ohos.arkui.stateManagement.common"; -export * from "@ohos.arkui.stateManagement.runtime"; -export * from "@ohos.arkui.stateManagement.storage"; +import { Component, Text } from "@ohos.arkui.component" +import { SimpleStruct } from "./utils/simple-struct" + +@Component +struct ImportStruct { + build() { + SimpleStruct(); + SimpleStruct({ message: "str1" }); + SimpleStruct() { + Text("a"); + } + } +} \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.external.resource.d.ets b/arkui-plugins/test/demo/mock/imports/utils/simple-struct.ets similarity index 81% rename from arkui-plugins/test/local/@ohos.arkui.external.resource.d.ets rename to arkui-plugins/test/demo/mock/imports/utils/simple-struct.ets index 9cc3b09e0..053de876e 100644 --- a/arkui-plugins/test/local/@ohos.arkui.external.resource.d.ets +++ b/arkui-plugins/test/demo/mock/imports/utils/simple-struct.ets @@ -13,4 +13,11 @@ * limitations under the License. */ -export type Resource = boolean; \ No newline at end of file +import { Component } from "@ohos.arkui.component" + +@Component +export struct SimpleStruct { + message: string = "str"; + + build() {} +} diff --git a/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets b/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets index 54263a552..1db0074a7 100644 --- a/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets +++ b/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; @memo function memo_arg_call( arg1: number, diff --git a/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets b/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets index ac8324d22..6ab9e8d74 100644 --- a/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets +++ b/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; @memo declare function funcA(): void; diff --git a/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets b/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets index 313164b28..40759ede4 100644 --- a/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets +++ b/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; @memo function foo() { } diff --git a/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets b/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets index cc0f993ec..fca54fcc7 100644 --- a/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets +++ b/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; @memo function funcNum(): number { diff --git a/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets b/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets index be715df95..fb4e922ac 100644 --- a/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets +++ b/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; @memo type ItemBuilder = (item: Item) => void; diff --git a/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets b/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets index 840c84aaf..5605e2b68 100644 --- a/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets +++ b/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; @memo function func(): void { diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets b/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets index def28807a..455fb6843 100644 --- a/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets +++ b/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; (arg: (()=>void)) => {}(() => {}); diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets b/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets index 36bc7d82f..4ade068c9 100644 --- a/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets +++ b/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; class B { @memo internal_call(): B { diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets b/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets index 08d252f58..1bfdb18b9 100644 --- a/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets +++ b/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; class A { @memo foo(p?: ()=>void): void {} diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets b/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets index fb757d8b6..2f5afae38 100644 --- a/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets +++ b/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; @memo (): void => { diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets b/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets index b54c9c6c2..b767256cc 100644 --- a/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets +++ b/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets @@ -13,7 +13,7 @@ * limitations under the License. */ - import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; class Person { constructor() {} diff --git a/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets b/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets index 5f799140f..25903f043 100644 --- a/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets +++ b/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; class Test { @memo lambda_arg(@memo arg: () => void) { diff --git a/arkui-plugins/test/demo/mock/memo/methods/callable.ets b/arkui-plugins/test/demo/mock/memo/methods/callable.ets index 2f4e2a401..bebbb7501 100644 --- a/arkui-plugins/test/demo/mock/memo/methods/callable.ets +++ b/arkui-plugins/test/demo/mock/memo/methods/callable.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; class A { @memo diff --git a/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets b/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets index e28c85361..121e1568d 100644 --- a/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets +++ b/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; declare abstract class A { @memo diff --git a/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets b/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets index 7ef4cdb0e..5dcd4c292 100644 --- a/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets +++ b/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo, __memo_context_type, __memo_id_type } from "arkui.stateManagement.runtime"; export declare function __context(): __memo_context_type export declare function __id(): __memo_id_type diff --git a/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets b/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets index 06df30297..fb3868ecc 100644 --- a/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets +++ b/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo, __memo_context_type, __memo_id_type } from "arkui.stateManagement.runtime"; @Retention({policy:"SOURCE"}) @interface memo_intrinsic {} @Retention({policy:"SOURCE"}) @interface memo_entry {} diff --git a/arkui-plugins/test/demo/mock/memo/methods/void-method.ets b/arkui-plugins/test/demo/mock/memo/methods/void-method.ets index ed3339dd1..d2ee07cd7 100644 --- a/arkui-plugins/test/demo/mock/memo/methods/void-method.ets +++ b/arkui-plugins/test/demo/mock/memo/methods/void-method.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; class A { x: int diff --git a/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets b/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets index 725d2702b..a349e0450 100644 --- a/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets +++ b/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; interface A { @memo a: () => void diff --git a/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets b/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets index 9fe1e5dc4..79c72508b 100644 --- a/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets +++ b/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; class A { arg: () => void diff --git a/arkui-plugins/test/demo/mock/memo/properties/implements.ets b/arkui-plugins/test/demo/mock/memo/properties/implements.ets index ad61b2a7a..cdf8c6644 100644 --- a/arkui-plugins/test/demo/mock/memo/properties/implements.ets +++ b/arkui-plugins/test/demo/mock/memo/properties/implements.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; interface A { @memo prop: (() => void) | undefined diff --git a/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets b/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets index c46a181e5..80a9332fd 100644 --- a/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets +++ b/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" +import { memo } from "arkui.stateManagement.runtime"; interface A { arg: () => void diff --git a/arkui-plugins/test/local/@ohos.arkui.component.text.d.ets b/arkui-plugins/test/local/@ohos.arkui.component.text.d.ets deleted file mode 100644 index 5ba7ef754..000000000 --- a/arkui-plugins/test/local/@ohos.arkui.component.text.d.ets +++ /dev/null @@ -1,132 +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. - */ - -import { Resource } from "@ohos.arkui.external.resource"; -import { StyledString } from "@ohos.arkui.component.styledString"; -import { ComponentBuilder, CommonMethod } from "@ohos.arkui.component.common"; -import { ResourceColor, Length } from "@ohos.arkui.component.units"; -import { memo } from '@ohos.arkui.stateManagement.runtime'; - -export declare class TextController { - closeSelectionMenu(): void; - setStyledString(value: StyledString): void; - - // getLayoutManager(): LayoutManager; -} - -export declare interface TextOptions { - controller: TextController; -} - -export declare interface TextAttribute extends CommonMethod { - // @memo - // font(value: Font, options?: FontSettingOptions): this; - @memo - fontColor(value: ResourceColor): this; - @memo - fontSize(value: number | string | Resource): this; - @memo - minFontSize(value: number | string | Resource): this; - @memo - maxFontSize(value: number | string | Resource): this; - @memo - minFontScale(scale: number | Resource): this; - @memo - maxFontScale(scale: number | Resource): this; - // @memo - // fontStyle(value: FontStyle): this; - // @memo - // fontWeight(value: number | FontWeight | string): this; - // @memo - // fontWeight(weight: number | FontWeight | string, options?: FontSettingOptions): this; - // @memo - // lineSpacing(value: LengthMetrics): this; - // @memo - // textAlign(value: TextAlign): this; - @memo - lineHeight(value: number | string | Resource): this; - // @memo - // textOverflow(options: TextOverflowOptions): this; - @memo - fontFamily(value: string | Resource): this; - @memo - maxLines(value: number): this; - // @memo - // decoration(value: DecorationStyleInterface): this; - @memo - letterSpacing(value: number | string): this; - // @memo - // textCase(value: TextCase): this; - @memo - baselineOffset(value: number | string): this; - // @memo - // copyOption(value: CopyOptions): this; - @memo - draggable(value: boolean): this; - // @memo - // textShadow(value: ShadowOptions | Array): this; - // @memo - // heightAdaptivePolicy(value: TextHeightAdaptivePolicy): this; - @memo - textIndent(value: Length): this; - // @memo - // wordBreak(value: WordBreak): this; - // @memo - // lineBreakStrategy(strategy: LineBreakStrategy): this; - @memo - onCopy(callback: (value: string) => void): this; - @memo - selection(selectionStart: number, selectionEnd: number): this; - @memo - caretColor(color: ResourceColor): this; - @memo - selectedBackgroundColor(color: ResourceColor): this; - // @memo - // ellipsisMode(value: EllipsisMode): this; - @memo - enableDataDetector(enable: boolean): this; - // @memo - // dataDetectorConfig(config: TextDataDetectorConfig): this; - // @memo - // bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType, - // options?: SelectionMenuOptions): this; - @memo - onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void): this; - @memo - fontFeature(value: string): this; - // @memo - // marqueeOptions(options: Optional): this; - // @memo - // onMarqueeStateChange(callback: Callback): this; - @memo - privacySensitive(supported: boolean): this; - // @memo - // textSelectable(mode: TextSelectableMode): this; - // @memo - // editMenuOptions(editMenu: EditMenuOptions): this; - @memo - halfLeading(halfLeading: boolean): this; - @memo - enableHapticFeedback(isEnabled: boolean): this; -} - -@memo -@ComponentBuilder -export declare function Text ( - value?: string | Resource, - options?: TextOptions, - @memo - content?: () => void -): TextAttribute; diff --git a/arkui-plugins/test/local/@ohos.arkui.stateManagement.common.d.ets b/arkui-plugins/test/local/@ohos.arkui.stateManagement.common.d.ets deleted file mode 100644 index 274947957..000000000 --- a/arkui-plugins/test/local/@ohos.arkui.stateManagement.common.d.ets +++ /dev/null @@ -1,61 +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. - */ - -@Retention({policy: "SOURCE"}) -export declare @interface State {}; - -@Retention({policy: "SOURCE"}) -export declare @interface Prop {}; - -@Retention({policy: "SOURCE"}) -export declare @interface Link {}; - -@Retention({policy: "SOURCE"}) -export declare @interface Observed {}; - -@Retention({policy: "SOURCE"}) -export declare @interface Track {}; - -@Retention({policy: "SOURCE"}) -export declare @interface ObjectLink {}; - -@Retention({policy: "SOURCE"}) -export declare @interface StorageProp { value: string }; - -@Retention({policy: "SOURCE"}) -export declare @interface StorageLink { value: string }; - -@Retention({policy: "SOURCE"}) -export declare @interface LocalStorageProp { value: string }; - -@Retention({policy: "SOURCE"}) -export declare @interface LocalStorageLink { value: string }; - -@Retention({policy: "SOURCE"}) -export declare @interface Provide { value: string }; - -@Retention({policy: "SOURCE"}) -export declare @interface Consume { value: string }; - -@Retention({policy: "SOURCE"}) -export declare @interface Watch { value: string }; - -@Retention({policy: "SOURCE"}) -export declare @interface Require {}; - -export declare class UIUtils { - static getTarget(source: T): T; - static makeObserved(source: T): T; -} \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.stateManagement.runtime.d.ets b/arkui-plugins/test/local/@ohos.arkui.stateManagement.runtime.d.ets deleted file mode 100644 index f70c0cb7f..000000000 --- a/arkui-plugins/test/local/@ohos.arkui.stateManagement.runtime.d.ets +++ /dev/null @@ -1,62 +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. - */ - -import { LocalStorage } from "@ohos.arkui.stateManagement.storage" - -// From incremental engine -@Retention({policy: "SOURCE"}) -export declare @interface memo {}; - -export type __memo_context_type = StateContext; -export type __memo_id_type = MemoCallSiteKey; - -export type MemoCallSiteKey = int; - -export declare interface Disposable { - readonly disposed: boolean; - dispose(): void; -} - -export declare interface State { - readonly modified: boolean; - readonly value: T; -} - -export declare interface MutableState extends Disposable, State { - value: T; -} - -export type Equivalent = (oldV: T, newV: T) => boolean; - -export declare interface InternalScope { - readonly unchanged: boolean; - readonly cached: Value; - recache(newValue?: Value): Value; - param(index: int, value: T, equivalent?: Equivalent, name?: string, contextLocal?: boolean): State; -} - -export declare interface StateContext { - scope(id: MemoCallSiteKey, paramCount?: int): InternalScope; -} - -// From Arkoala -export declare function propState(value?: T): MutableState; -export declare function objectLinkState(value?: T): MutableState; -export declare function stateOf(value: T): MutableState; -export declare function contextLocalStateOf(value: T, key: () => T): MutableState; -export declare function contextLocal(value: T): MutableState; -export declare function observableProxy(value: T): T; -export declare function StorageLinkState(storage: LocalStorage, name: string, value: T): MutableState -export declare function AppStorageLinkState(name: string, value: T): MutableState; \ No newline at end of file diff --git a/arkui-plugins/test/local/@ohos.arkui.stateManagement.storage.d.ets b/arkui-plugins/test/local/@ohos.arkui.stateManagement.storage.d.ets deleted file mode 100644 index a7257c839..000000000 --- a/arkui-plugins/test/local/@ohos.arkui.stateManagement.storage.d.ets +++ /dev/null @@ -1,119 +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. - */ - -export declare interface StorageProperty { - key: string; - defaultValue: number | string | boolean | Object; -} - -export type PersistPropsOptions = StorageProperty; - -export declare interface AbstractProperty { - info(): string; - get(): T; - set(newValue: T): void; -} - -export declare interface SubscribedAbstractProperty extends AbstractProperty { - aboutToBeDeleted(): void; -} - -export declare class LocalStorage { - static getShared(): LocalStorage | undefined; - - constructor(initializingProperties?: StorageProperty[]); - - has(propName: string): boolean; - - keys(): IterableIterator; - - size(): int; - - get(propName: string): T | undefined; - - set(propName: string, newValue: T): boolean; - - setOrCreate(propName: string, newValue?: T): boolean; - - ref(propName: string): AbstractProperty | undefined; - - setAndRef(propName: string, defaultValue: T): AbstractProperty; - - link(propName: string): SubscribedAbstractProperty | undefined; - - setAndLink(propName: string, defaultValue: T): SubscribedAbstractProperty; - - prop(propName: string): SubscribedAbstractProperty | undefined; - - setAndProp(propName: string, defaultValue: T): SubscribedAbstractProperty; - - delete(propName: string): boolean; - - clear(): boolean; -} - -export declare class AppStorage { - static has(propName: string): boolean; - - static keys(): IterableIterator; - - static size(): int; - - static get(propName: string): T | undefined; - - static set(propName: string, newValue: T): boolean; - - static setOrCreate(propName: string, newValue?: T): boolean; - - static ref(propName: string): AbstractProperty | undefined; - - static setAndRef(propName: string, defaultValue: T): AbstractProperty; - - static link(propName: string): SubscribedAbstractProperty | undefined; - - static setAndLink(propName: string, defaultValue: T): SubscribedAbstractProperty; - - static prop(propName: string): SubscribedAbstractProperty | undefined; - - static setAndProp(propName: string, defaultValue: T): SubscribedAbstractProperty; - - static delete(propName: string): boolean; - - static clear(): boolean; -} - -export declare class PersistentStorage { - - static persistProp(key: string, defaultValue: T): void; - - static deleteProp(key: string): void; - - static persistProps(props: PersistPropsOptions[]): void; - - static keys(): Array; -} - -export declare interface EnvPropsOptions { - key: string; - defaultValue: number | string | boolean; -} - -export declare class Environment { - static envProp(key: string, value: S): boolean; - - static envProps(props: EnvPropsOptions[]): void; - - static keys(): Array; -} \ No newline at end of file diff --git a/arkui-plugins/test/package.json b/arkui-plugins/test/package.json index 07123fbd7..34fcd06f2 100644 --- a/arkui-plugins/test/package.json +++ b/arkui-plugins/test/package.json @@ -11,6 +11,7 @@ "clean:test": "rm -rf generated", "clean:all": "npm run clean:localtest && npm run clean:test", "test": "npm run clean:all && npm run compile:plugins && cd .. && npm run test", + "test:gdb": "npm run clean:all && npm run compile:plugins && cd .. && npm run test:gdb", "localtest": "rm -rf dist && node localtest_config.js && npm run compile:plugins && LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_config.json", "localtest_gdb": "LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib gdb --args node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_config.json", "localtest_decl": "rm -rf dist && node localtest_decl_config.js && npm run compile:plugins && LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_decl_config.json", diff --git a/arkui-plugins/test/test.log b/arkui-plugins/test/test.log deleted file mode 100644 index 984a29adf..000000000 --- a/arkui-plugins/test/test.log +++ /dev/null @@ -1,372 +0,0 @@ - -> build_system_test@1.0.0 compile:ohos_sdk -> node /home/wuhaibin/newcode/oh/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/hello_world/build_config.json - -[ - '/home/wuhaibin/.nvm/versions/node/v23.8.0/bin/node', - '/home/wuhaibin/newcode/oh/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js', - './demo/hello_world/build_config.json' -] -Updated PATH: /home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/test/node_modules/.bin:/home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/node_modules/.bin:/home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/node_modules/.bin:/home/wuhaibin/newcode/oh/developtools/node_modules/.bin:/home/wuhaibin/newcode/oh/node_modules/.bin:/home/wuhaibin/newcode/node_modules/.bin:/home/wuhaibin/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/home/wuhaibin/.nvm/versions/node/v23.8.0/lib/node_modules/npm/node_modules/@npmcli/run-script/lib/node-gyp-bin:/home/wuhaibin/.local/bin:/home/wuhaibin/bin:/home/wuhaibin/.nvm/versions/node/v23.8.0/bin:/home/wuhaibin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/wsl/lib:/mnt/c/WINDOWS/system32:/mnt/c/WINDOWS:/mnt/c/WINDOWS/System32/Wbem:/mnt/c/WINDOWS/System32/WindowsPowerShell/v1.0/:/mnt/c/WINDOWS/System32/OpenSSH/:/mnt/c/Users/wuhaibin/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/wuhaibin/AppData/Local/Programs/Microsoft VS Code/bin:/snap/bin:/home/wuhaibin/newcode/oh/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib -Loaded plugin: ui-plugin { uiTransform: [Function: uiTransform] } [Function: uiTransform] -Loaded plugin: memo-plugin { unmemoizeTransform: [Function: unmemoizeTransform] } [Function: unmemoizeTransform] -ets2pandaCmd: _ --extension ets --arktsconfig /home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/test/dist/cache/entry/arktsconfig.json --output /home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/test/dist/cache/entry/a.abc --debug-info ./demo/hello_world/entry/a.ets -[TS WRAPPER] CREATE CONFIG -InitModule: es2panda - -[TS WRAPPER] PROCEED TO STATE: 1 -es2panda proceedToState parsed -[TS WRAPPER] GET AST FROM CONTEXT -executing plugin: ui-plugin -[UI PLUGIN] AFTER PARSED ENTER -[AFTER PARSED SCRIPT]: -import { StructBase } from "@koalaui.arkts-arkui.StructBase"; - -import { Text as Text } from "@koalaui.arkts-arkui.Text"; - -import { Column as Column } from "@koalaui.arkts-arkui.Column"; - -import { Button as Button } from "@koalaui.arkts-arkui.Button"; - -import { Component as Component, StorageLink as StorageLink, State as State } from "@koalaui.arkts-arkui.Common"; - -import { UserView as UserView, UserViewBuilder as UserViewBuilder } from "@koalaui.arkts-arkui.UserView"; - -import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.StateManagement.runtime"; - -import { memo as memo } from "@ohos.arkui.StateManagement.runtime"; - -function isTrue(): string { - return "aa"; -} - -final class MyStateSample extends StructBase { - public aaa: string = isTrue(); - - public build() { - Column(){ - Text("Hello World!"); - Text((this).aaa); - Button("change"); - }; - } - - public constructor() {} - -} - -class ComExampleTrivialApplication extends UserView { - public getBuilder(): UserViewBuilder { - let wrapper = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { - MyStateSample.instantiateImpl(undefined, ((): MyStateSample => new MyStateSample()), ({} as __Options_MyStateSample), undefined); - }); - return wrapper; - } - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - - -[UI PLUGIN] AFTER PARSED EXIT -plugin parsed finished -[TS WRAPPER] GET AST FROM CONTEXT -[TS WRAPPER] DESTROY AND RECREATE -[TS WRAPPER] PROCEED TO STATE: 4 -es2panda proceedToState checked -[TS WRAPPER] GET AST FROM CONTEXT -executing plugin: ui-plugin -[UI PLUGIN] AFTER CHECKED ENTER -[AFTER STRUCT SCRIPT] script: -import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; - -import { Text as Text } from "@koalaui.arkts-arkui.Text"; - -import { Column as Column } from "@koalaui.arkts-arkui.Column"; - -import { Button as Button } from "@koalaui.arkts-arkui.Button"; - -import { Component as Component, StorageLink as StorageLink, State as State } from "@koalaui.arkts-arkui.Common"; - -import { UserView as UserView, UserViewBuilder as UserViewBuilder } from "@koalaui.arkts-arkui.UserView"; - -import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.StateManagement.runtime"; - -import { memo as memo } from "@ohos.arkui.StateManagement.runtime"; - -abstract class ETSGLOBAL { - public static main() {} - - public static _$init$_() {} - - public static isTrue(): string { - return "aa"; - } - - -} - -class MyStateSample extends StructBase { - @memo()public __initializeStruct(initializers?: __Options_MyStateSample, @memo()content?: (()=> void)): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - public aaa: string = ETSGLOBAL.isTrue(); - - @memo()protected _build(@memo()style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo()content: (()=> void) | undefined, initializers?: __Options_MyStateSample): void { - Column.instantiateImpl(((instance: Column): Column => { - return instance; - }), ((): Column => { - return new Column(); - }), (() => { - Text.instantiateImpl(((instance: Text): Text => { - return instance; - }), ((): Text => { - return new Text(); - }), "Hello World!") - Text.instantiateImpl(((instance: Text): Text => { - return instance; - }), ((): Text => { - return new Text(); - }), (this).aaa) - Button.instantiateImpl(((instance: Button): Button => { - return instance; - }), ((): Button => { - return new Button(); - }), "change") - })); - } - - public constructor() {} - -} - -class ComExampleTrivialApplication extends UserView { - public getBuilder(): UserViewBuilder { - let wrapper = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { - MyStateSample.instantiateImpl(undefined, ((): MyStateSample => { - return new MyStateSample(); - }), ({} as __Options_MyStateSample), undefined); - }); - return wrapper; - } - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - - -[UI PLUGIN] AFTER CHECKED EXIT -executing plugin: memo-plugin -[MEMO PLUGIN] AFTER CHECKED ENTER -[BEFORE MEMO SCRIPT] script: -import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; - -import { Text as Text } from "@koalaui.arkts-arkui.Text"; - -import { Column as Column } from "@koalaui.arkts-arkui.Column"; - -import { Button as Button } from "@koalaui.arkts-arkui.Button"; - -import { Component as Component, StorageLink as StorageLink, State as State } from "@koalaui.arkts-arkui.Common"; - -import { UserView as UserView, UserViewBuilder as UserViewBuilder } from "@koalaui.arkts-arkui.UserView"; - -import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.StateManagement.runtime"; - -import { memo as memo } from "@ohos.arkui.StateManagement.runtime"; - -abstract class ETSGLOBAL { - public static main() {} - - public static _$init$_() {} - - public static isTrue(): string { - return "aa"; - } - - -} - -class MyStateSample extends StructBase { - @memo()public __initializeStruct(initializers?: __Options_MyStateSample, @memo()content?: (()=> void)): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - public aaa: string = ETSGLOBAL.isTrue(); - - @memo()protected _build(@memo()style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo()content: (()=> void) | undefined, initializers?: __Options_MyStateSample): void { - Column.instantiateImpl(((instance: Column): Column => { - return instance; - }), ((): Column => { - return new Column(); - }), (() => { - Text.instantiateImpl(((instance: Text): Text => { - return instance; - }), ((): Text => { - return new Text(); - }), "Hello World!") - Text.instantiateImpl(((instance: Text): Text => { - return instance; - }), ((): Text => { - return new Text(); - }), (this).aaa) - Button.instantiateImpl(((instance: Button): Button => { - return instance; - }), ((): Button => { - return new Button(); - }), "change") - })); - } - - public constructor() {} - -} - -class ComExampleTrivialApplication extends UserView { - public getBuilder(): UserViewBuilder { - let wrapper = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { - MyStateSample.instantiateImpl(undefined, ((): MyStateSample => { - return new MyStateSample(); - }), ({} as __Options_MyStateSample), undefined); - }); - return wrapper; - } - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - - -[AFTER MEMO SCRIPT] script: -import { StructBase as StructBase } from "@koalaui.arkts-arkui.StructBase"; - -import { Text as Text } from "@koalaui.arkts-arkui.Text"; - -import { Column as Column } from "@koalaui.arkts-arkui.Column"; - -import { Button as Button } from "@koalaui.arkts-arkui.Button"; - -import { Component as Component, StorageLink as StorageLink, State as State } from "@koalaui.arkts-arkui.Common"; - -import { UserView as UserView, UserViewBuilder as UserViewBuilder } from "@koalaui.arkts-arkui.UserView"; - -import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.StateManagement.runtime"; - -import { memo as memo } from "@ohos.arkui.StateManagement.runtime"; - -abstract class ETSGLOBAL { - public static main() {} - - public static _$init$_() {} - - public static isTrue(): string { - return "aa"; - } - - -} - -class MyStateSample extends StructBase { - public __initializeStruct(__memo_context: __memo_context_type, __memo_id: __memo_id_type, initializers?: __Options_MyStateSample, content?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + (168924120)), 2); - const __memo_parameter_initializers = __memo_scope.param(0, initializers), __memo_parameter_content = __memo_scope.param(1, content); - if (__memo_scope.unchanged) { - __memo_scope.recache(__memo_scope.cached) - return; - } - { - __memo_scope.recache() - return; - } - } - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - public aaa: string = ETSGLOBAL.isTrue(); - - protected _build(__memo_context: __memo_context_type, __memo_id: __memo_id_type, style: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: MyStateSample)=> MyStateSample) | undefined, content: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined, initializers?: __Options_MyStateSample): void { - const __memo_scope = __memo_context.scope(((__memo_id) + (168198604)), 3); - const __memo_parameter_style = __memo_scope.param(0, style), __memo_parameter_content = __memo_scope.param(1, content), __memo_parameter_initializers = __memo_scope.param(2, initializers); - if (__memo_scope.unchanged) { - __memo_scope.recache(__memo_scope.cached) - return; - } - Column.instantiateImpl(__memo_context, ((__memo_id) + (229216764)), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: Column): Column => { - return instance; - }), ((): Column => { - return new Column(); - }), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { - const __memo_scope = __memo_context.scope(((__memo_id) + (131080140)), 0); - if (__memo_scope.unchanged) { - __memo_scope.recache(__memo_scope.cached) - return; - } - Text.instantiateImpl(__memo_context, ((__memo_id) + (122349231)), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: Text): Text => { - return instance; - }), ((): Text => { - return new Text(); - }), "Hello World!") - Text.instantiateImpl(__memo_context, ((__memo_id) + (259830593)), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: Text): Text => { - return instance; - }), ((): Text => { - return new Text(); - }), (this).aaa) - Button.instantiateImpl(__memo_context, ((__memo_id) + (23671947)), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, instance: Button): Button => { - return instance; - }), ((): Button => { - return new Button(); - }), "change") - { - __memo_scope.recache() - return; - } - })); - { - __memo_scope.recache() - return; - } - } - - public constructor() {} - -} - -class ComExampleTrivialApplication extends UserView { - public getBuilder(): UserViewBuilder { - let wrapper = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type) => { - MyStateSample.instantiateImpl(__memo_context, ((__memo_id) + (44218244)), undefined, ((): MyStateSample => { - return new MyStateSample(); - }), ({} as __Options_MyStateSample), undefined); - }); - return wrapper; - } - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - - -[MEMO PLUGIN] AFTER CHECKED EXIT -plugin checked finished -[TS WRAPPER] GET AST FROM CONTEXT -[TS WRAPPER] DESTROY AND RECREATE -[TS WRAPPER] PROCEED TO STATE: 7 -es2panda bin generated -"/home/wuhaibin/newcode/oh/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/bin/ark_link" --output "/home/wuhaibin/newcode/oh/developtools/ace_ets2bundle/arkui-plugins/test/dist/modules_static.abc" -- @"dist/cache/fileInfo.txt" diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index cf9f7d191..d7640d7af 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -13,24 +13,195 @@ * limitations under the License. */ -import { PluginTestContext, PluginTester } from '../../utils/plugin-tester'; -import { annotation } from '../../../common/arkts-utils'; import * as arkts from '@koalaui/libarkts'; +import path from 'path'; +import { PluginTester } from '../../utils/plugin-tester'; +import { BuildConfig, PluginTestContext } from '../../utils/shared-types'; +import { recheck } from '../../utils/plugins'; +import { mockBuildConfig } from '../../utils/artkts-config'; +import { parseDumpSrc } from '../../utils/parse-string'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../utils/path-config'; +import { annotation } from '../../../common/arkts-utils'; +import { PluginContext, Plugins } from '../../../common/plugin-context'; +import { AbstractVisitor } from '../../../common/abstract-visitor'; + +const COMMON_UTILS_DIR_PATH: string = 'common-utils'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, COMMON_UTILS_DIR_PATH, 'annotation.ets')]; + +const pluginTester = new PluginTester('test arkts-utils', buildConfig); -const pluginTester = new PluginTester('test arkts-utils'); +type AnnotationAstNode = + | arkts.ClassDefinition + | arkts.ClassProperty + | arkts.ETSParameterExpression + | arkts.ArrowFunctionExpression + | arkts.MethodDefinition + | arkts.VariableDeclaration + | arkts.TSInterfaceDeclaration + | arkts.TSTypeAliasDeclaration; + +class AnnotationVisitor extends AbstractVisitor { + isRemover: boolean; + + constructor(isRemover?: boolean) { + super(); + this.isRemover = !!isRemover; + } + + private testAnnotation(): arkts.AnnotationUsage { + return annotation('TestAnno'); + } + + addTestAnnotation(node: AnnotationAstNode): void { + if (arkts.isEtsParameterExpression(node)) { + node.annotations = [this.testAnnotation()]; + } else if (arkts.isMethodDefinition(node)) { + node.scriptFunction.setAnnotations([this.testAnnotation()]); + node.setOverloads( + node.overloads.map((ov) => { + if (this.isAnnotationNode(ov)) { + this.addTestAnnotation(ov); + } + return ov; + }) + ); + } else { + node.setAnnotations([this.testAnnotation()]); + } + } + + removeTestAnnotation(node: AnnotationAstNode): void { + if (arkts.isEtsParameterExpression(node)) { + node.annotations = []; + } else if (arkts.isMethodDefinition(node)) { + node.scriptFunction.setAnnotations([]); + node.setOverloads( + node.overloads.map((ov) => { + if (this.isAnnotationNode(ov)) { + this.removeTestAnnotation(ov); + } + return ov; + }) + ); + } else { + node.setAnnotations([]); + } + } + + isAnnotationNode(node: arkts.AstNode): node is AnnotationAstNode { + return ( + arkts.isClassDefinition(node) || + arkts.isClassProperty(node) || + arkts.isMethodDefinition(node) || + arkts.isEtsParameterExpression(node) || + arkts.isArrowFunctionExpression(node) || + arkts.isMethodDefinition(node) || + arkts.isVariableDeclaration(node) || + arkts.isTSInterfaceDeclaration(node) || + arkts.isTSTypeAliasDeclaration(node) + ); + } + + visitor(node: arkts.AstNode): arkts.AstNode { + if (this.isAnnotationNode(node)) { + if (this.isRemover) { + this.removeTestAnnotation(node); + } else { + this.addTestAnnotation(node); + } + } + return this.visitEachChild(node); + } +} + +function addAnnotationTransform(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + const annotationAdder = new AnnotationVisitor(); + annotationAdder.visitor(program.astNode); + script = program.astNode; + return script; + } + return script; +} + +function removeAnnotationTransform(this: PluginContext): arkts.EtsScript | undefined { + let script: arkts.EtsScript | undefined; + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + const annotationAdder = new AnnotationVisitor(true); + annotationAdder.visitor(program.astNode); + script = program.astNode; + return script; + } + return script; +} + +const addAnnotation: Plugins = { + name: 'add-annotation', + parsed: addAnnotationTransform, + checked: addAnnotationTransform, +}; + +const removeAnnotation: Plugins = { + name: 'remove-annotation', + parsed: removeAnnotationTransform, + checked: removeAnnotationTransform, +}; + +const expectedParseSnapshot: string = ` +@Retention({policy:\"SOURCE\"}) @interface TestAnno {} +@TestAnno() type TestType = number; +@TestAnno() (() => {}) +@TestAnno() class A { + @TestAnno() public prop: number = 1; + @TestAnno() public method(@TestAnno() arg1: number): void { + @TestAnno() const a: number = arg1; + } + @TestAnno() public constructor() {} +} +@TestAnno() interface __A { + @TestAnno() prop: number; +} +`; + +function testParseAnnotation(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedParseSnapshot)); +} + +const expectedCheckSnapshot: string = ` +@TestAnno() function main() {} +@TestAnno() (() => {}); +@Retention({policy:\"SOURCE\"}) @interface TestAnno {} +@TestAnno() type TestType = number; +@TestAnno() class A { + @TestAnno() public prop: number = 1; + @TestAnno() public method(@TestAnno() arg1: number): void { + @TestAnno() const a: number = arg1; + } + @TestAnno() public constructor() {} +} +@TestAnno() interface __A { + @TestAnno() set prop(prop: number) + @TestAnno() get prop(): number +} +`; -function testAnnotation(this: PluginTestContext): void { - const anno: arkts.AnnotationUsage = annotation('State'); - expect(arkts.isAnnotationUsage(anno)).toBeTruthy(); - expect(anno.dumpSrc()).toBe('@State() '); +function testCheckAnnotation(this: PluginTestContext): void { + expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedCheckSnapshot)); } pluginTester.run( 'annotation', - [], + [addAnnotation, removeAnnotation, recheck], { - parsed: [testAnnotation], - checked: [testAnnotation], + 'parsed:add-annotation': [testParseAnnotation], + 'checked:add-annotation': [testCheckAnnotation], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts index a3d7d2909..4ff8099b2 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const FUNCTION_DIR_PATH: string = 'memo/functions'; @@ -28,7 +29,8 @@ buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUN const pluginTester = new PluginTester('test memo function', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @functions.OptionalParametersAnnotation({minArgCount:3}) function memo_arg_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg2: ((x: number)=> number), @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number), arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 5); @@ -99,7 +101,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform argument calls in functions', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts index db15946ae..23d779dfb 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const FUNCTION_DIR_PATH: string = 'memo/functions'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo function', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -80,7 +82,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform declare functions and calls', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts index 8e5494643..a921f408a 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const FUNCTION_DIR_PATH: string = 'memo/functions'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo function', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -102,7 +104,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform inner functions', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts index 19b061ad6..8d94ec992 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const FUNCTION_DIR_PATH: string = 'memo/functions'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo function', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} function funcNum(__memo_context: __memo_context_type, __memo_id: __memo_id_type): number { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -102,7 +104,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform functions with non-void return type', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts index 7db7cd676..541b48a72 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const FUNCTION_DIR_PATH: string = 'memo/functions'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo function', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() function A(__memo_context: __memo_context_type, __memo_id: __memo_id_type): Attribute function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): ItemBuilder { @@ -82,7 +84,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform functions with type reference', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts index 08c0eb3bd..b3e729785 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const FUNCTION_DIR_PATH: string = 'memo/functions'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo function', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -51,7 +53,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform functions with void return type', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts index f23a8d252..c94fe1dd9 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const LAMBDA_DIR_PATH: string = 'memo/lambdas'; @@ -28,7 +29,8 @@ buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAM const pluginTester = new PluginTester('test memo lambda', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} ((arg: (()=> void)) => {})((() => {})); @@ -163,7 +165,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform argument calls in lambdas', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts index be488294a..415423f6e 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; import { Plugins } from '../../../../common/plugin-context'; import { uiTransform } from '../../../../ui-plugins'; @@ -31,15 +32,14 @@ buildConfig.compileFiles = [ const parsedTransform: Plugins = { name: 'state-complex-type', - parsed: uiTransform().parsed + parsed: uiTransform().parsed, }; const pluginTester = new PluginTester('test memo lambda', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; +import { memo as memo } from "arkui.stateManagement.runtime"; function main() {} @@ -87,7 +87,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform lambdas about function with receiver feature', - [parsedTransform, memoNoRecheck], + [parsedTransform, memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts index f023fef13..311746f58 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const LAMBDA_DIR_PATH: string = 'memo/lambdas'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo lambda', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -159,7 +161,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform trailing lambdas', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts index 59b48a024..f49946e13 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const LAMBDA_DIR_PATH: string = 'memo/lambdas'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo lambda', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -63,7 +65,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform lambdas with void return type', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts index 4f6e3fa92..82f9f6a61 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const LAMBDA_DIR_PATH: string = 'memo/lambdas'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo lambda', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -115,7 +117,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform lambdas with receiver', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts index de72519e7..a4326ac1e 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const METHOD_DIR_PATH: string = 'memo/methods'; @@ -28,7 +29,8 @@ buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MET const pluginTester = new PluginTester('test memo method', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} class Test { public lambda_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { @@ -135,7 +137,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform argument calls in methods', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts index 7657e1dd0..249406cef 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const METHOD_DIR_PATH: string = 'memo/methods'; @@ -28,7 +29,8 @@ buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MET const pluginTester = new PluginTester('test memo method', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -102,7 +104,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform callable class', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts index 0a669b4c0..5a23c9b83 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const METHOD_DIR_PATH: string = 'memo/methods'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo method', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -73,7 +75,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform declare methods and calls', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts index 11dae0f7e..4064b0e65 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const METHOD_DIR_PATH: string = 'memo/methods'; @@ -28,7 +29,8 @@ buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MET const pluginTester = new PluginTester('test memo method', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; function main() {} function __context(): __memo_context_type function __id(): __memo_id_type @@ -176,7 +178,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform inner calls in methods', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts index a8ddef791..780080c9a 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const METHOD_DIR_PATH: string = 'memo/methods'; @@ -28,7 +29,8 @@ buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MET const pluginTester = new PluginTester('test memo method', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; function main() {} function __context(): __memo_context_type function __id(): __memo_id_type @@ -62,14 +64,14 @@ class Test { } return __memo_scope.recache(__memo_parameter_arg.value); } - public intrinsic_method(): int { + @memo_intrinsic() public intrinsic_method(__memo_context: __memo_context_type, __memo_id: __memo_id_type): int { return 0; } - public intrinsic_method_with_this(): int { + @memo_intrinsic() public intrinsic_method_with_this(__memo_context: __memo_context_type, __memo_id: __memo_id_type): int { this.void_method(__memo_context, ((__memo_id) + ())); return 0; } - public memoEntry(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() entry: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> R)): R { + @memo_entry() public memoEntry(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() entry: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> R)): R { const getContext = (() => { return __context(); }); @@ -109,7 +111,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform methods with non-void return type', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts index 953742b8a..e29eb8cc1 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const METHOD_DIR_PATH: string = 'memo/methods'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo method', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} class A { public x: int; @@ -141,7 +143,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform methods with void return type', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts index 28671e700..49a170e20 100644 --- a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const PROPERTY_DIR_PATH: string = 'memo/properties'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo property', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -91,7 +93,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform properties in class constructor', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts index c98720039..31092a975 100644 --- a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const PROPERTY_DIR_PATH: string = 'memo/properties'; @@ -30,7 +31,8 @@ buildConfig.compileFiles = [ const pluginTester = new PluginTester('test memo property', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} class A { public arg: (()=> void); @@ -96,7 +98,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform properties in class', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts index 99053d0ef..d58f3d7bc 100644 --- a/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const PROPERTY_DIR_PATH: string = 'memo/properties'; @@ -28,7 +29,8 @@ buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, PRO const pluginTester = new PluginTester('test memo property', buildConfig); const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); @@ -97,7 +99,7 @@ function testMemoTransformer(this: PluginTestContext): void { pluginTester.run( 'transform interface properties', - [memoNoRecheck], + [memoNoRecheck, recheck], { 'checked:memo-no-recheck': [testMemoTransformer], }, diff --git a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts index dd4678db6..3193402b8 100644 --- a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { uiNoRecheck } from '../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; import { uiTransform } from '../../../../ui-plugins'; import { Plugins } from '../../../../common/plugin-context'; @@ -37,22 +38,11 @@ const animationTransform: Plugins = { const pluginTester = new PluginTester('test basic animation transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; - import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; - import { EntryPoint as EntryPoint } from "arkui.UserView"; - import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Text as Text, Column as Column, Component as Component, Color as Color, Curve as Curve } from "@ohos.arkui.component"; - import { Entry as Entry } from "@ohos.arkui.component"; function main() {} @@ -65,7 +55,7 @@ function main() {} public __updateStruct(initializers: __Options_AnimatablePropertyExample | undefined): void {} @memo() public _build(@memo() style: ((instance: AnimatablePropertyExample)=> AnimatablePropertyExample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_AnimatablePropertyExample | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { Text(@memo() ((instance: UITextAttribute): void => { instance.animationStart({ duration: 2000, @@ -81,15 +71,15 @@ function main() {} curve: Curve.Ease, }).width("100%"); return; - }), "AnimatableProperty", undefined, undefined); + }), "AnimatableProperty"); })); } - public constructor() {} + private constructor() {} } -interface __Options_AnimatablePropertyExample { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_AnimatablePropertyExample { } @@ -97,7 +87,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { AnimatablePropertyExample._instantiateImpl(undefined, (() => { return new AnimatablePropertyExample(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -111,7 +101,7 @@ function testAnimationTransformer(this: PluginTestContext): void { pluginTester.run( 'test basic animation transform', - [animationTransform, uiNoRecheck], + [animationTransform, uiNoRecheck, recheck], { checked: [testAnimationTransformer], }, diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts index b9a0d5943..a7fb599c0 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -27,42 +28,43 @@ const CUSTOM_COMPONENT_DIR_PATH: string = 'custom-component'; const buildConfig: BuildConfig = mockBuildConfig(); buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, CUSTOM_COMPONENT_DIR_PATH, 'custom-component-call.ets'), + path.resolve( + getRootPath(), + MOCK_ENTRY_DIR_PATH, + BUILDER_LAMBDA_DIR_PATH, + CUSTOM_COMPONENT_DIR_PATH, + 'custom-component-call.ets' + ), ]; const pluginTester = new PluginTester('test custom component call transformation', buildConfig); const parsedTransform: Plugins = { name: 'custom-component-call', - parsed: uiTransform().parsed + parsed: uiTransform().parsed, }; const expectedParsedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Text as Text, Column as Column, Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; @Component() final class CustomContainer extends CustomComponent { @Builder() public closerBuilder() {} - @BuilderParam() public closer: (()=> void) = (this).closerBuilder; + @BuilderParam() public closer: (()=> void) = this.closerBuilder; public build() {} public constructor() {} } @Component() final class CustomContainerUser extends CustomComponent { public build() { - Column(undefined){ - CustomContainer(undefined){ - Column(undefined){ - Text("hello", undefined); + Column(){ + CustomContainer(){ + Column(){ + Text("hello"); }; }; CustomContainer(({} as __Options_CustomContainer)){ - Column(undefined){}; + Column(){}; }; CustomContainer(undefined){}; CustomContainer(); @@ -71,11 +73,11 @@ import { Text as Text, Column as Column, Component as Component, Builder as Buil public constructor() {} } -interface __Options_CustomContainer { - closer?: @memo() (()=> void); +@Component() export interface __Options_CustomContainer { + @BuilderParam() closer?: (()=> void); } -interface __Options_CustomContainerUser { +@Component() export interface __Options_CustomContainerUser { } `; @@ -86,26 +88,26 @@ function testParedTransformer(this: PluginTestContext): void { const expectedBuilderLambdaScript: string = ` import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Text as Text, Column as Column, Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; function main() {} @Component({freezeWhenInactive:false}) final class CustomContainer extends CustomComponent { public __initializeStruct(initializers: __Options_CustomContainer | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_closer = ((((({let gensym___38813563 = initializers; - (((gensym___38813563) == (null)) ? undefined : gensym___38813563.closer)})) ?? (content))) ?? ((this).closerBuilder)) + this.__backing_closer = ((((({let gensym___38813563 = initializers; + (((gensym___38813563) == (null)) ? undefined : gensym___38813563.closer)})) ?? (content))) ?? (this.closerBuilder)) } public __updateStruct(initializers: __Options_CustomContainer | undefined): void {} private __backing_closer?: @memo() (()=> void); public get closer(): @memo() (()=> void) { - return (this).__backing_closer!; + return this.__backing_closer!; } public set closer(@memo() value: (()=> void)) { - (this).__backing_closer = value; + this.__backing_closer = value; } @memo() public closerBuilder() {} @memo() public _build(@memo() style: ((instance: CustomContainer)=> CustomContainer) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CustomContainer | undefined): void {} @@ -116,22 +118,22 @@ function main() {} public __initializeStruct(initializers: __Options_CustomContainerUser | undefined, @memo() content: (()=> void) | undefined): void {} public __updateStruct(initializers: __Options_CustomContainerUser | undefined): void {} @memo() public _build(@memo() style: ((instance: CustomContainerUser)=> CustomContainerUser) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CustomContainerUser | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { CustomContainer._instantiateImpl(undefined, (() => { return new CustomContainer(); - }), undefined, (() => { - Column(undefined, undefined, (() => { + }), (() => { + Column(undefined, (() => { Text(undefined, "hello", undefined, undefined); })); }), undefined); CustomContainer._instantiateImpl(undefined, (() => { return new CustomContainer(); }), ({} as __Options_CustomContainer), (() => { - Column(undefined, undefined, (() => {})); + Column(undefined, (() => {})); }), undefined); CustomContainer._instantiateImpl(undefined, (() => { return new CustomContainer(); - }), undefined, (() => {}), undefined); + }), (() => {}), undefined); CustomContainer._instantiateImpl(undefined, (() => { return new CustomContainer(); }), undefined, undefined, undefined); @@ -155,7 +157,7 @@ function testCustomComponentTransformer(this: PluginTestContext): void { pluginTester.run( 'test custom component call transformation', - [parsedTransform, recheck, uiNoRecheck], + [parsedTransform, recheck, uiNoRecheck, recheck], { parsed: [testParedTransformer], 'checked:builder-lambda-no-recheck': [testCustomComponentTransformer], diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts index 37b4605ad..48996b891 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; import { builderLambdaNoRecheck, memoNoRecheck, recheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const BUILDER_LAMBDA_DIR_PATH: string = 'builder-lambda'; @@ -31,7 +32,7 @@ const pluginTester = new PluginTester('test builder-lambda simple component', bu function testBuilderLambdaTransformer(this: PluginTestContext): void { const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { memo as memo } from \"@ohos.arkui.stateManagement\"; import { Column as Column, UIColumnAttribute as UIColumnAttribute } from \"arkui.component.column\"; function main() {} class MyStateSample { @@ -46,7 +47,8 @@ class MyStateSample { function testMemoTransformer(this: PluginTestContext): void { const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; +import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; +import { memo as memo } from \"@ohos.arkui.stateManagement\"; import { Column as Column, UIColumnAttribute as UIColumnAttribute } from \"arkui.component.column\"; function main() {} class MyStateSample { @@ -80,7 +82,7 @@ class MyStateSample { pluginTester.run( 'transform simple component', - [builderLambdaNoRecheck, recheck, memoNoRecheck], + [builderLambdaNoRecheck, recheck, memoNoRecheck, recheck], { 'checked:builder-lambda-no-recheck': [testBuilderLambdaTransformer], 'checked:memo-no-recheck': [testMemoTransformer], diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts index 1c64f1cdb..52fe30ed6 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { builderLambdaNoRecheck, structNoRecheck, uiNoRecheck } from '../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; import { uiTransform } from '../../../../ui-plugins'; import { Plugins } from '../../../../common/plugin-context'; @@ -33,13 +34,11 @@ const pluginTester = new PluginTester('test function with receiver style transfo const parsedTransform: Plugins = { name: 'style-with-receiver', - parsed: uiTransform().parsed + parsed: uiTransform().parsed, }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { memo as memo } from "@ohos.arkui.stateManagement"; @@ -65,23 +64,23 @@ function main() {} public __updateStruct(initializers: __Options_MM | undefined): void {} @memo() public _build(@memo() style: ((instance: MM)=> MM) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MM | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { Text(@memo() ((instance: UITextAttribute): void => { style22(cardStyle(instance.height(200).fontColor("#000000"), 600, "#eeeeee").fontSize(60).fontWeight(400)).width(900); return; - }), "hello world", undefined, undefined); + }), "hello world"); Text(@memo() ((instance: UITextAttribute): void => { cardStyle(instance, 600, "#eeeeee"); return; - }), "hello world", undefined, undefined); + }), "hello world"); })); } - public constructor() {} + private constructor() {} } -interface __Options_MM { +@Component({freezeWhenInactive:false}) export interface __Options_MM { } `; @@ -92,9 +91,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test function with receiver style transformstion', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:ui-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts index ba63b9e2d..f8029becf 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -33,24 +34,20 @@ const pluginTester = new PluginTester('test builder param variable passing', bui const parsedTransform: Plugins = { name: 'builder-param-passing', - parsed: uiTransform().parsed + parsed: uiTransform().parsed, }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; +import { memo as memo } from "arkui.stateManagement.runtime"; +import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Builder as Builder, BuilderParam as BuilderParam, Column as Column, Text as Text } from "@ohos.arkui.component"; function main() {} @Component({freezeWhenInactive:false}) final class Child extends CustomComponent { public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; - (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? ((this).customBuilder)) + this.__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; + (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? (this.customBuilder)) } public __updateStruct(initializers: __Options_Child | undefined): void {} @@ -58,20 +55,20 @@ function main() {} private __backing_customBuilderParam?: @memo() (()=> void); public get customBuilderParam(): @memo() (()=> void) { - return (this).__backing_customBuilderParam!; + return this.__backing_customBuilderParam!; } public set customBuilderParam(@memo() value: (()=> void)) { - (this).__backing_customBuilderParam = value; + this.__backing_customBuilderParam = value; } @memo() public customBuilder() {} @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - (this).customBuilderParam(); + this.customBuilderParam(); } - public constructor() {} + private constructor() {} } @@ -81,39 +78,39 @@ function main() {} public __updateStruct(initializers: __Options_Parent | undefined): void {} @memo() public componentBuilder() { - Text(undefined, "Parent builder", undefined, undefined); + Text(undefined, "Parent builder"); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { Child._instantiateImpl(undefined, (() => { return new Child(); }), ({ - customBuilderParam: (this).componentBuilder, - } as __Options_Child), undefined, undefined); + customBuilderParam: this.componentBuilder, + } as __Options_Child)); Child._instantiateImpl(undefined, (() => { return new Child(); }), ({ customBuilderParam: @memo() (() => { - (this).componentBuilder(); + this.componentBuilder(); }), - } as __Options_Child), undefined, undefined); + } as __Options_Child)); Child._instantiateImpl(undefined, (() => { return new Child(); - }), undefined, (() => { - Text(undefined, "Parent builder", undefined, undefined); - }), undefined); + }), (() => { + Text(undefined, "Parent builder"); + })); })); } - public constructor() {} + private constructor() {} } -interface __Options_Child { - set customBuilderParam(customBuilderParam: @memo() (()=> void) | undefined) +@Component({freezeWhenInactive:false}) export interface __Options_Child { + set customBuilderParam(@memo() customBuilderParam: (()=> void) | undefined) get customBuilderParam(): @memo() (()=> void) | undefined } -interface __Options_Parent { +@Component({freezeWhenInactive:false}) export interface __Options_Parent { } `; @@ -123,7 +120,7 @@ function testCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test builder param variable passing', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { 'checked:ui-no-recheck': [testCheckedTransformer], }, diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts index 21e7f2bb4..9e7706330 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,8 +38,6 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; @@ -73,13 +72,13 @@ function main() {} this.customBuilderParam(); this.customBuilderParam2("hello"); } - public constructor() {} + private constructor() {} } -interface __Options_Child { - set customBuilderParam(customBuilderParam: @memo() (()=> void) | undefined) +@Component({freezeWhenInactive:false}) export interface __Options_Child { + set customBuilderParam(@memo() customBuilderParam: (()=> void) | undefined) get customBuilderParam(): @memo() (()=> void) | undefined - set customBuilderParam2(customBuilderParam2: @memo() ((str: string)=> void) | undefined) + set customBuilderParam2(@memo() customBuilderParam2: ((str: string)=> void) | undefined) get customBuilderParam2(): @memo() ((str: string)=> void) | undefined } `; @@ -90,7 +89,7 @@ function testCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test builder param init with local builder', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { 'checked:ui-no-recheck': [testCheckedTransformer], }, diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts index 95740a1d5..ca9507117 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts @@ -14,46 +14,41 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; const FUNCTION_DIR_PATH: string = 'decorators/builder'; const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'global-builder.ets'), -]; +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'global-builder.ets')]; const pluginTester = new PluginTester('test global builder', buildConfig); const parsedTransform: Plugins = { name: 'global-builder', - parsed: uiTransform().parsed + parsed: uiTransform().parsed, }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIRowAttribute as UIRowAttribute } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Row as Row, Builder as Builder, Text as Text } from "@ohos.arkui.component"; function main() {} @memo() function showTextBuilder() { - Text(undefined, "Hello World", undefined, undefined); + Text(undefined, "Hello World"); } @memo() function overBuilder(params: Tmp) { - Row(undefined, undefined, (() => { - Text(undefined, (("UseStateVarByReference: ") + (params.paramA1)), undefined, undefined); + Row(undefined, (() => { + Text(undefined, (("UseStateVarByReference: ") + (params.paramA1))); })); } @@ -66,17 +61,17 @@ class Tmp { public __initializeStruct(initializers: __Options_BuilderDemo | undefined, @memo() content: (()=> void) | undefined): void {} public __updateStruct(initializers: __Options_BuilderDemo | undefined): void {} @memo() public _build(@memo() style: ((instance: BuilderDemo)=> BuilderDemo) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_BuilderDemo | undefined): void { - Row(undefined, undefined, @memo() (() => { + Row(undefined, @memo() (() => { showTextBuilder(); overBuilder({ paramA1: "Hello", }); })); } - public constructor() {} + private constructor() {} } -interface __Options_BuilderDemo { +@Component({freezeWhenInactive:false}) export interface __Options_BuilderDemo { } `; @@ -87,7 +82,7 @@ function testCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'global builder', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { 'checked:ui-no-recheck': [testCheckedTransformer], }, diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts index 9769285c5..e991d3b2f 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts @@ -14,34 +14,30 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; const FUNCTION_DIR_PATH: string = 'decorators/builder'; const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'local-builder.ets'), -]; +buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'local-builder.ets')]; const pluginTester = new PluginTester('test local builder', buildConfig); const parsedTransform: Plugins = { name: 'local-builder', - parsed: uiTransform().parsed + parsed: uiTransform().parsed, }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, Builder as Builder, Text as Text } from "@ohos.arkui.component"; @@ -54,24 +50,24 @@ function main() {} Text(@memo() ((instance: UITextAttribute): void => { instance.fontSize(30); return; - }), "Hello World", undefined, undefined); + }), "Hello World"); } @memo() public showTextValueBuilder(param: string) { Text(@memo() ((instance: UITextAttribute): void => { instance.fontSize(30); return; - }), param, undefined, undefined); + }), param); } @memo() public _build(@memo() style: ((instance: BuilderDemo)=> BuilderDemo) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_BuilderDemo | undefined): void { - Column(undefined, undefined, @memo() (() => { + Column(undefined, @memo() (() => { this.showTextBuilder(); this.showTextValueBuilder("Hello @Builder"); })); } - public constructor() {} + private constructor() {} } -interface __Options_BuilderDemo { +@Component({freezeWhenInactive:false}) export interface __Options_BuilderDemo { } `; @@ -82,7 +78,7 @@ function testCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'local builder', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { 'checked:ui-no-recheck': [testCheckedTransformer], }, diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts index 340db6a9e..08c06f2bf 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,38 +38,34 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Link as Link } from "@ohos.arkui.stateManagement"; - +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from \"@ohos.arkui.stateManagement\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from \"@ohos.arkui.stateManagement\"; +import { CustomComponent as CustomComponent } from \"arkui.component.customComponent\"; +import { Component as Component } from \"@ohos.arkui.component\"; +import { Link as Link } from \"@ohos.arkui.stateManagement\"; function main() {} - @Component({freezeWhenInactive:false}) final class LinkParent extends CustomComponent { public __initializeStruct(initializers: __Options_LinkParent | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___11910109 = initializers; - (((gensym___11910109) == (null)) ? undefined : gensym___11910109.__backing_linkVar1)})) { - this.__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar1)})) { + this.__backing_linkVar1 = new LinkDecoratedVariable(\"linkVar1\", initializers!.__backing_linkVar1!); }; - if (({let gensym___181684045 = initializers; - (((gensym___181684045) == (null)) ? undefined : gensym___181684045.__backing_linkVar2)})) { - this.__backing_linkVar2 = new LinkDecoratedVariable("linkVar2", initializers!.__backing_linkVar2!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar2)})) { + this.__backing_linkVar2 = new LinkDecoratedVariable(\"linkVar2\", initializers!.__backing_linkVar2!); }; - if (({let gensym___24446313 = initializers; - (((gensym___24446313) == (null)) ? undefined : gensym___24446313.__backing_linkVar3)})) { - this.__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar3)})) { + this.__backing_linkVar3 = new LinkDecoratedVariable(\"linkVar3\", initializers!.__backing_linkVar3!); }; - if (({let gensym___167989826 = initializers; - (((gensym___167989826) == (null)) ? undefined : gensym___167989826.__backing_linkVar4)})) { - this.__backing_linkVar4 = new LinkDecoratedVariable("linkVar4", initializers!.__backing_linkVar4!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar4)})) { + this.__backing_linkVar4 = new LinkDecoratedVariable(\"linkVar4\", initializers!.__backing_linkVar4!); }; - if (({let gensym___157566097 = initializers; - (((gensym___157566097) == (null)) ? undefined : gensym___157566097.__backing_linkVar5)})) { - this.__backing_linkVar5 = new LinkDecoratedVariable("linkVar5", initializers!.__backing_linkVar5!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar5)})) { + this.__backing_linkVar5 = new LinkDecoratedVariable(\"linkVar5\", initializers!.__backing_linkVar5!); }; } public __updateStruct(initializers: __Options_LinkParent | undefined): void {} @@ -108,28 +105,30 @@ function main() {} this.__backing_linkVar5!.set(value); } @memo() public _build(@memo() style: ((instance: LinkParent)=> LinkParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_LinkParent | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_LinkParent { - set linkVar1(linkVar1: string | undefined) - get linkVar1(): string | undefined +@Retention({policy:\"SOURCE\"}) @interface __Link_intrinsic {} + +@Component({freezeWhenInactive:false}) export interface __Options_LinkParent { + @__Link_intrinsic() set linkVar1(linkVar1: string | undefined) + @__Link_intrinsic() get linkVar1(): string | undefined set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) get __backing_linkVar1(): DecoratedV1VariableBase | undefined - set linkVar2(linkVar2: number | undefined) - get linkVar2(): number | undefined + @__Link_intrinsic() set linkVar2(linkVar2: number | undefined) + @__Link_intrinsic() get linkVar2(): number | undefined set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase | undefined) get __backing_linkVar2(): DecoratedV1VariableBase | undefined - set linkVar3(linkVar3: boolean | undefined) - get linkVar3(): boolean | undefined + @__Link_intrinsic() set linkVar3(linkVar3: boolean | undefined) + @__Link_intrinsic() get linkVar3(): boolean | undefined set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) get __backing_linkVar3(): DecoratedV1VariableBase | undefined - set linkVar4(linkVar4: undefined | undefined) - get linkVar4(): undefined | undefined - set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase | undefined) - get __backing_linkVar4(): DecoratedV1VariableBase | undefined - set linkVar5(linkVar5: null | undefined) - get linkVar5(): null | undefined + @__Link_intrinsic() set linkVar4(linkVar4: undefined | undefined) + @__Link_intrinsic() get linkVar4(): undefined | undefined + set __backing_linkVar4(__backing_linkVar4: undefined | undefined) + get __backing_linkVar4(): undefined | undefined + @__Link_intrinsic() set linkVar5(linkVar5: null | undefined) + @__Link_intrinsic() get linkVar5(): null | undefined set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase | undefined) get __backing_linkVar5(): DecoratedV1VariableBase | undefined } @@ -141,9 +140,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test basic type @Link decorated variables transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts index 486097a84..1fb0b1918 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,14 +38,12 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Link as Link } from "@ohos.arkui.stateManagement"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from \"@ohos.arkui.stateManagement\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from \"@ohos.arkui.stateManagement\"; +import { CustomComponent as CustomComponent } from \"arkui.component.customComponent\"; +import { Component as Component } from \"@ohos.arkui.component\"; +import { Link as Link } from \"@ohos.arkui.stateManagement\"; function main() {} @@ -54,7 +53,7 @@ class Per { this.num = num; } } - + final class LinkType extends BaseEnum { private readonly #ordinal: int; private static () {} @@ -62,32 +61,35 @@ final class LinkType extends BaseEnum { super(value); this.#ordinal = ordinal; } + public static readonly TYPE1: LinkType = new LinkType(0, 0); public static readonly TYPE2: LinkType = new LinkType(1, 1); public static readonly TYPE3: LinkType = new LinkType(2, 3); - private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; + private static readonly #NamesArray: String[] = [\"TYPE1\", \"TYPE2\", \"TYPE3\"]; private static readonly #ValuesArray: int[] = [0, 1, 3]; - private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; + private static readonly #StringValuesArray: String[] = [\"0\", \"1\", \"3\"]; private static readonly #ItemsArray: LinkType[] = [LinkType.TYPE1, LinkType.TYPE2, LinkType.TYPE3]; + public getName(): String { return LinkType.#NamesArray[this.#ordinal]; } + public static getValueOf(name: String): LinkType { for (let i = 0;((i) < (LinkType.#NamesArray.length));(++i)) { if (((name) == (LinkType.#NamesArray[i]))) { return LinkType.#ItemsArray[i]; } } - throw new Error((("No enum constant LinkType.") + (name))); + throw new Error(((\"No enum constant LinkType.\") + (name))); } - + public static fromValue(value: int): LinkType { for (let i = 0;((i) < (LinkType.#ValuesArray.length));(++i)) { if (((value) == (LinkType.#ValuesArray[i]))) { return LinkType.#ItemsArray[i]; } } - throw new Error((("No enum LinkType with value ") + (value))); + throw new Error(((\"No enum LinkType with value \") + (value))); } public valueOf(): int { return LinkType.#ValuesArray[this.#ordinal]; @@ -108,53 +110,53 @@ final class LinkType extends BaseEnum { @Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___11910109 = initializers; - (((gensym___11910109) == (null)) ? undefined : gensym___11910109.__backing_linkVar1)})) { - this.__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar1)})) { + this.__backing_linkVar1 = new LinkDecoratedVariable(\"linkVar1\", initializers!.__backing_linkVar1!); }; - if (({let gensym___181684045 = initializers; - (((gensym___181684045) == (null)) ? undefined : gensym___181684045.__backing_linkVar2)})) { - this.__backing_linkVar2 = new LinkDecoratedVariable>("linkVar2", initializers!.__backing_linkVar2!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar2)})) { + this.__backing_linkVar2 = new LinkDecoratedVariable>(\"linkVar2\", initializers!.__backing_linkVar2!); }; - if (({let gensym___24446313 = initializers; - (((gensym___24446313) == (null)) ? undefined : gensym___24446313.__backing_linkVar3)})) { - this.__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar3)})) { + this.__backing_linkVar3 = new LinkDecoratedVariable(\"linkVar3\", initializers!.__backing_linkVar3!); }; - if (({let gensym___167989826 = initializers; - (((gensym___167989826) == (null)) ? undefined : gensym___167989826.__backing_linkVar4)})) { - this.__backing_linkVar4 = new LinkDecoratedVariable>("linkVar4", initializers!.__backing_linkVar4!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar4)})) { + this.__backing_linkVar4 = new LinkDecoratedVariable>(\"linkVar4\", initializers!.__backing_linkVar4!); }; - if (({let gensym___157566097 = initializers; - (((gensym___157566097) == (null)) ? undefined : gensym___157566097.__backing_linkVar5)})) { - this.__backing_linkVar5 = new LinkDecoratedVariable>("linkVar5", initializers!.__backing_linkVar5!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar5)})) { + this.__backing_linkVar5 = new LinkDecoratedVariable>(\"linkVar5\", initializers!.__backing_linkVar5!); }; - if (({let gensym___60105491 = initializers; - (((gensym___60105491) == (null)) ? undefined : gensym___60105491.__backing_linkVar6)})) { - this.__backing_linkVar6 = new LinkDecoratedVariable>("linkVar6", initializers!.__backing_linkVar6!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar6)})) { + this.__backing_linkVar6 = new LinkDecoratedVariable>(\"linkVar6\", initializers!.__backing_linkVar6!); }; - if (({let gensym___3429048 = initializers; - (((gensym___3429048) == (null)) ? undefined : gensym___3429048.__backing_linkVar7)})) { - this.__backing_linkVar7 = new LinkDecoratedVariable>("linkVar7", initializers!.__backing_linkVar7!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar7)})) { + this.__backing_linkVar7 = new LinkDecoratedVariable>(\"linkVar7\", initializers!.__backing_linkVar7!); }; - if (({let gensym___139916435 = initializers; - (((gensym___139916435) == (null)) ? undefined : gensym___139916435.__backing_linkVar8)})) { - this.__backing_linkVar8 = new LinkDecoratedVariable<((sr: string)=> void)>("linkVar8", initializers!.__backing_linkVar8!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar8)})) { + this.__backing_linkVar8 = new LinkDecoratedVariable<((sr: string)=> void)>(\"linkVar8\", initializers!.__backing_linkVar8!); }; - if (({let gensym___145003260 = initializers; - (((gensym___145003260) == (null)) ? undefined : gensym___145003260.__backing_linkVar9)})) { - this.__backing_linkVar9 = new LinkDecoratedVariable("linkVar9", initializers!.__backing_linkVar9!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar9)})) { + this.__backing_linkVar9 = new LinkDecoratedVariable(\"linkVar9\", initializers!.__backing_linkVar9!); }; - if (({let gensym___122643185 = initializers; - (((gensym___122643185) == (null)) ? undefined : gensym___122643185.__backing_linkVar10)})) { - this.__backing_linkVar10 = new LinkDecoratedVariable>("linkVar10", initializers!.__backing_linkVar10!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar10)})) { + this.__backing_linkVar10 = new LinkDecoratedVariable>(\"linkVar10\", initializers!.__backing_linkVar10!); }; - if (({let gensym___222468503 = initializers; - (((gensym___222468503) == (null)) ? undefined : gensym___222468503.__backing_linkVar11)})) { - this.__backing_linkVar11 = new LinkDecoratedVariable("linkVar11", initializers!.__backing_linkVar11!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar11)})) { + this.__backing_linkVar11 = new LinkDecoratedVariable(\"linkVar11\", initializers!.__backing_linkVar11!); }; - if (({let gensym___243301539 = initializers; - (((gensym___243301539) == (null)) ? undefined : gensym___243301539.__backing_linkVar12)})) { - this.__backing_linkVar12 = new LinkDecoratedVariable | Per>("linkVar12", initializers!.__backing_linkVar12!); + if (({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.__backing_linkVar12)})) { + this.__backing_linkVar12 = new LinkDecoratedVariable | Per>(\"linkVar12\", initializers!.__backing_linkVar12!); }; } public __updateStruct(initializers: __Options_Parent | undefined): void {} @@ -243,58 +245,60 @@ final class LinkType extends BaseEnum { this.__backing_linkVar12!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_Parent { - set linkVar1(linkVar1: Per | undefined) - get linkVar1(): Per | undefined +@Retention({policy:\"SOURCE\"}) @interface __Link_intrinsic {} + +@Component({freezeWhenInactive:false}) export interface __Options_Parent { + @__Link_intrinsic() set linkVar1(linkVar1: Per | undefined) + @__Link_intrinsic() get linkVar1(): Per | undefined set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) get __backing_linkVar1(): DecoratedV1VariableBase | undefined - set linkVar2(linkVar2: Array | undefined) - get linkVar2(): Array | undefined + @__Link_intrinsic() set linkVar2(linkVar2: Array | undefined) + @__Link_intrinsic() get linkVar2(): Array | undefined set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase> | undefined) get __backing_linkVar2(): DecoratedV1VariableBase> | undefined - set linkVar3(linkVar3: LinkType | undefined) - get linkVar3(): LinkType | undefined + @__Link_intrinsic() set linkVar3(linkVar3: LinkType | undefined) + @__Link_intrinsic() get linkVar3(): LinkType | undefined set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) get __backing_linkVar3(): DecoratedV1VariableBase | undefined - set linkVar4(linkVar4: Set | undefined) - get linkVar4(): Set | undefined + @__Link_intrinsic() set linkVar4(linkVar4: Set | undefined) + @__Link_intrinsic() get linkVar4(): Set | undefined set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase> | undefined) get __backing_linkVar4(): DecoratedV1VariableBase> | undefined - set linkVar5(linkVar5: Array | undefined) - get linkVar5(): Array | undefined + @__Link_intrinsic() set linkVar5(linkVar5: Array | undefined) + @__Link_intrinsic() get linkVar5(): Array | undefined set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase> | undefined) get __backing_linkVar5(): DecoratedV1VariableBase> | undefined - set linkVar6(linkVar6: Array | undefined) - get linkVar6(): Array | undefined + @__Link_intrinsic() set linkVar6(linkVar6: Array | undefined) + @__Link_intrinsic() get linkVar6(): Array | undefined set __backing_linkVar6(__backing_linkVar6: DecoratedV1VariableBase> | undefined) get __backing_linkVar6(): DecoratedV1VariableBase> | undefined - set linkVar7(linkVar7: Array | undefined) - get linkVar7(): Array | undefined + @__Link_intrinsic() set linkVar7(linkVar7: Array | undefined) + @__Link_intrinsic() get linkVar7(): Array | undefined set __backing_linkVar7(__backing_linkVar7: DecoratedV1VariableBase> | undefined) get __backing_linkVar7(): DecoratedV1VariableBase> | undefined - set linkVar8(linkVar8: ((sr: string)=> void) | undefined) - get linkVar8(): ((sr: string)=> void) | undefined + @__Link_intrinsic() set linkVar8(linkVar8: ((sr: string)=> void) | undefined) + @__Link_intrinsic() get linkVar8(): ((sr: string)=> void) | undefined set __backing_linkVar8(__backing_linkVar8: DecoratedV1VariableBase<((sr: string)=> void)> | undefined) get __backing_linkVar8(): DecoratedV1VariableBase<((sr: string)=> void)> | undefined - set linkVar9(linkVar9: Date | undefined) - get linkVar9(): Date | undefined + @__Link_intrinsic() set linkVar9(linkVar9: Date | undefined) + @__Link_intrinsic() get linkVar9(): Date | undefined set __backing_linkVar9(__backing_linkVar9: DecoratedV1VariableBase | undefined) get __backing_linkVar9(): DecoratedV1VariableBase | undefined - set linkVar10(linkVar10: Map | undefined) - get linkVar10(): Map | undefined + @__Link_intrinsic() set linkVar10(linkVar10: Map | undefined) + @__Link_intrinsic() get linkVar10(): Map | undefined set __backing_linkVar10(__backing_linkVar10: DecoratedV1VariableBase> | undefined) get __backing_linkVar10(): DecoratedV1VariableBase> | undefined - set linkVar11(linkVar11: string | number | undefined) - get linkVar11(): string | number | undefined - set __backing_linkVar11(__backing_linkVar11: DecoratedV1VariableBase | undefined) - get __backing_linkVar11(): DecoratedV1VariableBase | undefined - set linkVar12(linkVar12: Set | Per | undefined) - get linkVar12(): Set | Per | undefined - set __backing_linkVar12(__backing_linkVar12: DecoratedV1VariableBase | Per> | undefined) - get __backing_linkVar12(): DecoratedV1VariableBase | Per> | undefined + @__Link_intrinsic() set linkVar11(linkVar11: string | number | undefined) + @__Link_intrinsic() get linkVar11(): string | number | undefined + set __backing_linkVar11(__backing_linkVar11: DecoratedV1VariableBase | DecoratedV1VariableBase | undefined) + get __backing_linkVar11(): DecoratedV1VariableBase | DecoratedV1VariableBase | undefined + @__Link_intrinsic() set linkVar12(linkVar12: Set | Per | undefined) + @__Link_intrinsic() get linkVar12(): Set | Per | undefined + set __backing_linkVar12(__backing_linkVar12: DecoratedV1VariableBase> | DecoratedV1VariableBase | undefined) + get __backing_linkVar12(): DecoratedV1VariableBase> | DecoratedV1VariableBase | undefined } `; @@ -304,9 +308,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test complex type @Link decorated variables transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts index 01a8275f9..30cfecbd8 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,15 +38,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { UITextInputAttribute as UITextInputAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, TextInput as TextInput } from "@ohos.arkui.component"; import { Link as Link, State as State, Prop as Prop } from "@ohos.arkui.stateManagement"; @@ -68,10 +65,10 @@ function main() {} this.__backing_text1!.set(value); } @memo() public _build(@memo() style: ((instance: Parant)=> Parant) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parant | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { TextInput(undefined, { text: this.text1, - }, undefined); + }); Child._instantiateImpl(undefined, (() => { return new Child(); }), ({ @@ -79,10 +76,10 @@ function main() {} childText2: this.text1, childText3: this.text1, childText4: this.text1, - } as __Options_Child), undefined, undefined); + } as __Options_Child)); })); } - public constructor() {} + private constructor() {} } @Component({freezeWhenInactive:false}) final class Child extends CustomComponent { @@ -138,21 +135,23 @@ function main() {} @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { TextInput(undefined, { text: this.childText, - }, undefined); + }); } - public constructor() {} + private constructor() {} } -interface __Options_Parant { - set text1(text1: string | undefined) - get text1(): string | undefined +@Retention({policy:"SOURCE"}) @interface __Link_intrinsic {} + +@Component({freezeWhenInactive:false}) export interface __Options_Parant { + @__Link_intrinsic() set text1(text1: string | undefined) + @__Link_intrinsic() get text1(): string | undefined set __backing_text1(__backing_text1: DecoratedV1VariableBase | undefined) get __backing_text1(): DecoratedV1VariableBase | undefined } -interface __Options_Child { - set childText(childText: string | undefined) - get childText(): string | undefined +@Component({freezeWhenInactive:false}) export interface __Options_Child { + @__Link_intrinsic() set childText(childText: string | undefined) + @__Link_intrinsic() get childText(): string | undefined set __backing_childText(__backing_childText: DecoratedV1VariableBase | undefined) get __backing_childText(): DecoratedV1VariableBase | undefined set childText2(childText2: string | undefined) @@ -176,9 +175,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test @Link decorated variables passing to other variables', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:ui-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts index cd9424e90..614d946c1 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,15 +38,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { UIDatePickerAttribute as UIDatePickerAttribute } from "@ohos.arkui.component"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Column as Column, Button as Button, DatePicker as DatePicker, ClickEvent as ClickEvent } from "@ohos.arkui.component"; @@ -69,27 +66,27 @@ function main() {} this.__backing_selectedDate!.set(value); } @memo() public _build(@memo() style: ((instance: DateComponent)=> DateComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_DateComponent | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { Button(@memo() ((instance: UIButtonAttribute): void => { instance.onClick(((e: ClickEvent) => { this.selectedDate.setFullYear(((this.selectedDate.getFullYear()) + (1))); })); return; - }), "child increase the year by 1", undefined, undefined); + }), "child increase the year by 1"); Button(@memo() ((instance: UIButtonAttribute): void => { instance.margin(10).onClick(((e: ClickEvent) => { this.selectedDate = new Date("2023-09-09"); })); return; - }), "child update the new date", undefined, undefined); + }), "child update the new date"); DatePicker(undefined, { start: new Date("1970-1-1"), end: new Date("2100-1-1"), selected: this.selectedDate, - }, undefined); + }); })); } - public constructor() {} + private constructor() {} } @@ -107,42 +104,44 @@ function main() {} this.__backing_parentSelectedDate!.set(value); } @memo() public _build(@memo() style: ((instance: ParentComponent)=> ParentComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ParentComponent | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { Button(@memo() ((instance: UIButtonAttribute): void => { instance.margin(10).onClick(((e: ClickEvent) => { this.parentSelectedDate.setMonth(((this.parentSelectedDate.getMonth()) + (1))); })); return; - }), "parent increase the month by 1", undefined, undefined); + }), "parent increase the month by 1"); Button(@memo() ((instance: UIButtonAttribute): void => { instance.margin(10).onClick(((e: ClickEvent) => { this.parentSelectedDate = new Date("2023-07-07"); })); return; - }), "parent update the new date", undefined, undefined); + }), "parent update the new date"); DatePicker(undefined, { start: new Date("1970-1-1"), end: new Date("2100-1-1"), selected: this.parentSelectedDate, - }, undefined); + }); DateComponent._instantiateImpl(undefined, (() => { return new DateComponent(); }), ({ __backing_selectedDate: this.__backing_parentSelectedDate, - } as __Options_DateComponent), undefined, undefined); + } as __Options_DateComponent)); })); } - public constructor() {} + private constructor() {} } -interface __Options_DateComponent { - set selectedDate(selectedDate: Date | undefined) - get selectedDate(): Date | undefined +@Retention({policy:"SOURCE"}) @interface __Link_intrinsic {} + +@Component({freezeWhenInactive:false}) export interface __Options_DateComponent { + @__Link_intrinsic() set selectedDate(selectedDate: Date | undefined) + @__Link_intrinsic() get selectedDate(): Date | undefined set __backing_selectedDate(__backing_selectedDate: DecoratedV1VariableBase | undefined) get __backing_selectedDate(): DecoratedV1VariableBase | undefined } -interface __Options_ParentComponent { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_ParentComponent { set parentSelectedDate(parentSelectedDate: Date | undefined) get parentSelectedDate(): Date | undefined set __backing_parentSelectedDate(__backing_parentSelectedDate: StateDecoratedVariable | undefined) @@ -153,7 +152,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { ParentComponent._instantiateImpl(undefined, (() => { return new ParentComponent(); - }), undefined, undefined, undefined); + })); } public constructor() {} } @@ -165,9 +164,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test @Link decorated variables passing', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:ui-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts index 08e0ec65b..0398b5489 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,30 +38,14 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed only transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - +import { int32 as int32 } from "@koalaui.runtime.common"; +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component } from "@ohos.arkui.component"; - import { Observed as Observed } from "@ohos.arkui.stateManagement"; function main() {} @@ -131,11 +116,11 @@ function main() {} @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { } @@ -147,9 +132,9 @@ function testObservedOnlyTransformer(this: PluginTestContext): void { pluginTester.run( 'test observed only transform', - [observedTrackTransform, uiNoRecheck], + [observedTrackTransform, uiNoRecheck, recheck], { - checked: [testObservedOnlyTransformer], + 'checked:ui-no-recheck': [testObservedOnlyTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts index 5bd7f7551..f3e046dbb 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,30 +38,16 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed track transform with class property', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - +import { int32 as int32 } from "@koalaui.runtime.common"; +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component } from "@ohos.arkui.component"; - import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; function main() {} @@ -181,11 +168,11 @@ class E implements IObservedObject { @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { } `; @@ -196,9 +183,9 @@ function testObservedOnlyTransformer(this: PluginTestContext): void { pluginTester.run( 'test observed track transform with class property', - [observedTrackTransform, uiNoRecheck], + [observedTrackTransform, uiNoRecheck, recheck], { - checked: [testObservedOnlyTransformer], + 'checked:ui-no-recheck': [testObservedOnlyTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts index 371c48a6c..996b8fa73 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,32 +38,17 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed track transform with complex type', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - +import { int32 as int32 } from "@koalaui.runtime.common"; +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { EntryPoint as EntryPoint } from "arkui.UserView"; - import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; - import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; function main() {} @@ -862,11 +848,11 @@ class mixed3 implements IObservedObject { @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { } @@ -874,7 +860,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { MyStateSample._instantiateImpl(undefined, (() => { return new MyStateSample(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -888,9 +874,9 @@ function testObservedOnlyTransformer(this: PluginTestContext): void { pluginTester.run( 'test observed track transform with complex type', - [observedTrackTransform, uiNoRecheck], + [observedTrackTransform, uiNoRecheck, recheck], { - checked: [testObservedOnlyTransformer], + 'checked:ui-no-recheck': [testObservedOnlyTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts index f3f3a001e..ea59f29f9 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,30 +38,14 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed track transform with extends', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - +import { int32 as int32 } from "@koalaui.runtime.common"; +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component } from "@ohos.arkui.component"; - import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; function main() {} @@ -178,11 +163,11 @@ class G extends A { @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { } @@ -194,9 +179,9 @@ function testObservedOnlyTransformer(this: PluginTestContext): void { pluginTester.run( 'test observed track transform with extends', - [observedTrackTransform, uiNoRecheck], + [observedTrackTransform, uiNoRecheck, recheck], { - checked: [testObservedOnlyTransformer], + 'checked:ui-no-recheck': [testObservedOnlyTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts index f71a5e922..b8769ae20 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,30 +38,14 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed track transform with implements', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - +import { int32 as int32 } from "@koalaui.runtime.common"; +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component } from "@ohos.arkui.component"; - import { Observed as Observed } from "@ohos.arkui.stateManagement"; function main() {} @@ -145,11 +130,11 @@ interface trackInterface { @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { } @@ -161,9 +146,9 @@ function testObservedOnlyTransformer(this: PluginTestContext): void { pluginTester.run( 'test observed track transform with implements', - [observedTrackTransform, uiNoRecheck], + [observedTrackTransform, uiNoRecheck, recheck], { - checked: [testObservedOnlyTransformer], + 'checked:ui-no-recheck': [testObservedOnlyTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts index 9f28609dc..914e784d3 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,30 +38,14 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test observed with track transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - +import { int32 as int32 } from "@koalaui.runtime.common"; +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component } from "@ohos.arkui.component"; - import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; function main() {} @@ -116,11 +101,11 @@ function main() {} @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { } @@ -132,9 +117,9 @@ function testObservedOnlyTransformer(this: PluginTestContext): void { pluginTester.run( 'test observed with track transform', - [observedTrackTransform, uiNoRecheck], + [observedTrackTransform, uiNoRecheck, recheck], { - checked: [testObservedOnlyTransformer], + 'checked:ui-no-recheck': [testObservedOnlyTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts index a1e60b0fa..9ad6c2453 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,30 +38,14 @@ const observedTrackTransform: Plugins = { const pluginTester = new PluginTester('test track only transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - +import { int32 as int32 } from "@koalaui.runtime.common"; +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component } from "@ohos.arkui.component"; - import { Track as Track } from "@ohos.arkui.stateManagement"; function main() {} @@ -116,11 +101,11 @@ class C implements IObservedObject { @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { } @@ -132,9 +117,9 @@ function testObservedOnlyTransformer(this: PluginTestContext): void { pluginTester.run( 'test track only transform', - [observedTrackTransform, uiNoRecheck], + [observedTrackTransform, uiNoRecheck, recheck], { - checked: [testObservedOnlyTransformer], + 'checked:ui-no-recheck': [testObservedOnlyTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts index 9ed163723..783f36ca7 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,8 +38,6 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; @@ -118,10 +117,10 @@ function main() {} this.__backing_propVar5!.set(value); } @memo() public _build(@memo() style: ((instance: PropParent)=> PropParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_PropParent | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_PropParent { +@Component({freezeWhenInactive:false}) export interface __Options_PropParent { set propVar1(propVar1: string | undefined) get propVar1(): string | undefined set __backing_propVar1(__backing_propVar1: PropDecoratedVariable | undefined) @@ -136,8 +135,8 @@ interface __Options_PropParent { get __backing_propVar3(): PropDecoratedVariable | undefined set propVar4(propVar4: undefined | undefined) get propVar4(): undefined | undefined - set __backing_propVar4(__backing_propVar4: PropDecoratedVariable | undefined) - get __backing_propVar4(): PropDecoratedVariable | undefined + set __backing_propVar4(__backing_propVar4: undefined | undefined) + get __backing_propVar4(): undefined | undefined set propVar5(propVar5: null | undefined) get propVar5(): null | undefined set __backing_propVar5(__backing_propVar5: PropDecoratedVariable | undefined) @@ -151,9 +150,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test basic type @Prop decorated variables transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts index 7db445781..e269ddbad 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,8 +38,6 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; @@ -266,10 +265,10 @@ final class PropType extends BaseEnum { this.__backing_propVar12!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_Parent { +@Component({freezeWhenInactive:false}) export interface __Options_Parent { set propVar1(propVar1: Per | undefined) get propVar1(): Per | undefined set __backing_propVar1(__backing_propVar1: PropDecoratedVariable | undefined) @@ -312,12 +311,12 @@ interface __Options_Parent { get __backing_propVar10(): PropDecoratedVariable> | undefined set propVar11(propVar11: string | number | undefined) get propVar11(): string | number | undefined - set __backing_propVar11(__backing_propVar11: PropDecoratedVariable | undefined) - get __backing_propVar11(): PropDecoratedVariable | undefined + set __backing_propVar11(__backing_propVar11: PropDecoratedVariable | PropDecoratedVariable | undefined) + get __backing_propVar11(): PropDecoratedVariable | PropDecoratedVariable | undefined set propVar12(propVar12: Set | Per | undefined) get propVar12(): Set | Per | undefined - set __backing_propVar12(__backing_propVar12: PropDecoratedVariable | Per> | undefined) - get __backing_propVar12(): PropDecoratedVariable | Per> | undefined + set __backing_propVar12(__backing_propVar12: PropDecoratedVariable> | PropDecoratedVariable | undefined) + get __backing_propVar12(): PropDecoratedVariable> | PropDecoratedVariable | undefined } `; @@ -327,9 +326,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test complex type @Prop decorated variables transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts index 0809c2d46..967998dd2 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,14 +38,10 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Text as Text, Button as Button, Column as Column, ClickEvent as ClickEvent } from "@ohos.arkui.component"; import { Prop as Prop, State as State } from "@ohos.arkui.stateManagement"; @@ -80,21 +77,21 @@ function main() {} } @memo() public _build(@memo() style: ((instance: CountDownComponent)=> CountDownComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CountDownComponent | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { if (((this.count) > (0))) { - Text(undefined, (((("You have") + (this.count))) + ("Nuggets left")), undefined, undefined); + Text(undefined, (((("You have") + (this.count))) + ("Nuggets left"))); } else { - Text(undefined, "Game over!", undefined, undefined); + Text(undefined, "Game over!"); } Button(@memo() ((instance: UIButtonAttribute): void => { instance.onClick(((e: ClickEvent) => { this.count -= this.costOfOneAttempt; })); return; - }), "Try again", undefined, undefined); + }), "Try again"); })); } - public constructor() {} + private constructor() {} } @Component({freezeWhenInactive:false}) final class ParentComponent extends CustomComponent { @@ -111,32 +108,32 @@ function main() {} this.__backing_countDownStartValue!.set(value); } @memo() public _build(@memo() style: ((instance: ParentComponent)=> ParentComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ParentComponent | undefined): void { - Column(undefined, undefined, (() => { - Text(undefined, (((("Grant") + (this.countDownStartValue))) + ("nuggets to play.")), undefined, undefined); + Column(undefined, (() => { + Text(undefined, (((("Grant") + (this.countDownStartValue))) + ("nuggets to play."))); Button(@memo() ((instance: UIButtonAttribute): void => { instance.onClick(((e: ClickEvent) => { this.countDownStartValue += 1; })); return; - }), "+1 - Nuggets in New Game", undefined, undefined); + }), "+1 - Nuggets in New Game"); Button(@memo() ((instance: UIButtonAttribute): void => { instance.onClick(((e: ClickEvent) => { this.countDownStartValue -= 1; })); return; - }), "-1 - Nuggets in New Game", undefined, undefined); + }), "-1 - Nuggets in New Game"); CountDownComponent._instantiateImpl(undefined, (() => { return new CountDownComponent(); }), ({ count: this.countDownStartValue, costOfOneAttempt: 2, - } as __Options_CountDownComponent), undefined, undefined); + } as __Options_CountDownComponent)); })); } - public constructor() {} + private constructor() {} } -interface __Options_CountDownComponent { +@Component({freezeWhenInactive:false}) export interface __Options_CountDownComponent { set count(count: number | undefined) get count(): number | undefined set __backing_count(__backing_count: PropDecoratedVariable | undefined) @@ -145,7 +142,7 @@ interface __Options_CountDownComponent { get costOfOneAttempt(): number | undefined } -interface __Options_ParentComponent { +@Component({freezeWhenInactive:false}) export interface __Options_ParentComponent { set countDownStartValue(countDownStartValue: number | undefined) get countDownStartValue(): number | undefined set __backing_countDownStartValue(__backing_countDownStartValue: StateDecoratedVariable | undefined) @@ -159,9 +156,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test @Prop decorated variables passing', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:ui-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts index 9f5787762..22f589470 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,8 +38,6 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; @@ -124,42 +123,42 @@ function main() {} this.__backing_count7!.set(value); } @memo() public _build(@memo() style: ((instance: Ancestors)=> Ancestors) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Ancestors | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_Ancestors { +@Component({freezeWhenInactive:false}) export interface __Options_Ancestors { set count(count: string | undefined | undefined) get count(): string | undefined | undefined - set __backing_count(__backing_count: ProvideDecoratedVariable | undefined) - get __backing_count(): ProvideDecoratedVariable | undefined + set __backing_count(__backing_count: ProvideDecoratedVariable | undefined | undefined) + get __backing_count(): ProvideDecoratedVariable | undefined | undefined set count1(count1: string | undefined | undefined) get count1(): string | undefined | undefined - set __backing_count1(__backing_count1: ProvideDecoratedVariable | undefined) - get __backing_count1(): ProvideDecoratedVariable | undefined + set __backing_count1(__backing_count1: ProvideDecoratedVariable | undefined | undefined) + get __backing_count1(): ProvideDecoratedVariable | undefined | undefined set count2(count2: string | undefined | undefined) get count2(): string | undefined | undefined - set __backing_count2(__backing_count2: ProvideDecoratedVariable | undefined) - get __backing_count2(): ProvideDecoratedVariable | undefined + set __backing_count2(__backing_count2: ProvideDecoratedVariable | undefined | undefined) + get __backing_count2(): ProvideDecoratedVariable | undefined | undefined set count3(count3: string | undefined | undefined) get count3(): string | undefined | undefined - set __backing_count3(__backing_count3: ProvideDecoratedVariable | undefined) - get __backing_count3(): ProvideDecoratedVariable | undefined + set __backing_count3(__backing_count3: ProvideDecoratedVariable | undefined | undefined) + get __backing_count3(): ProvideDecoratedVariable | undefined | undefined set count4(count4: string | undefined | undefined) get count4(): string | undefined | undefined - set __backing_count4(__backing_count4: ProvideDecoratedVariable | undefined) - get __backing_count4(): ProvideDecoratedVariable | undefined + set __backing_count4(__backing_count4: ProvideDecoratedVariable | undefined | undefined) + get __backing_count4(): ProvideDecoratedVariable | undefined | undefined set count5(count5: string | undefined | undefined) get count5(): string | undefined | undefined - set __backing_count5(__backing_count5: ProvideDecoratedVariable | undefined) - get __backing_count5(): ProvideDecoratedVariable | undefined + set __backing_count5(__backing_count5: ProvideDecoratedVariable | undefined | undefined) + get __backing_count5(): ProvideDecoratedVariable | undefined | undefined set count6(count6: string | undefined | undefined) get count6(): string | undefined | undefined - set __backing_count6(__backing_count6: ProvideDecoratedVariable | undefined) - get __backing_count6(): ProvideDecoratedVariable | undefined + set __backing_count6(__backing_count6: ProvideDecoratedVariable | undefined | undefined) + get __backing_count6(): ProvideDecoratedVariable | undefined | undefined set count7(count7: string | undefined | undefined) get count7(): string | undefined | undefined - set __backing_count7(__backing_count7: ProvideDecoratedVariable | undefined) - get __backing_count7(): ProvideDecoratedVariable | undefined + set __backing_count7(__backing_count7: ProvideDecoratedVariable | undefined | undefined) + get __backing_count7(): ProvideDecoratedVariable | undefined | undefined } `; @@ -169,9 +168,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test different @Provide annotation usage transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts index dffbb429f..aecf110fb 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,8 +38,6 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; @@ -97,10 +96,10 @@ function main() {} this.__backing_provideVar5!.set(value); } @memo() public _build(@memo() style: ((instance: PropParent)=> PropParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_PropParent | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_PropParent { +@Component({freezeWhenInactive:false}) export interface __Options_PropParent { set provideVar1(provideVar1: string | undefined) get provideVar1(): string | undefined set __backing_provideVar1(__backing_provideVar1: ProvideDecoratedVariable | undefined) @@ -115,8 +114,8 @@ interface __Options_PropParent { get __backing_provideVar3(): ProvideDecoratedVariable | undefined set provideVar4(provideVar4: undefined | undefined) get provideVar4(): undefined | undefined - set __backing_provideVar4(__backing_provideVar4: ProvideDecoratedVariable | undefined) - get __backing_provideVar4(): ProvideDecoratedVariable | undefined + set __backing_provideVar4(__backing_provideVar4: undefined | undefined) + get __backing_provideVar4(): undefined | undefined set provideVar5(provideVar5: null | undefined) get provideVar5(): null | undefined set __backing_provideVar5(__backing_provideVar5: ProvideDecoratedVariable | undefined) @@ -130,9 +129,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test basic type @Provide decorated variables transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts index 6684a83fe..3aea5e1d8 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,8 +38,6 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; @@ -217,10 +216,10 @@ final class PropType extends BaseEnum { this.__backing_provideVar12!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_Parent { +@Component({freezeWhenInactive:false}) export interface __Options_Parent { set provideVar1(provideVar1: Per | undefined) get provideVar1(): Per | undefined set __backing_provideVar1(__backing_provideVar1: ProvideDecoratedVariable | undefined) @@ -263,12 +262,12 @@ interface __Options_Parent { get __backing_provideVar10(): ProvideDecoratedVariable> | undefined set provideVar11(provideVar11: string | number | undefined) get provideVar11(): string | number | undefined - set __backing_provideVar11(__backing_provideVar11: ProvideDecoratedVariable | undefined) - get __backing_provideVar11(): ProvideDecoratedVariable | undefined + set __backing_provideVar11(__backing_provideVar11: ProvideDecoratedVariable | ProvideDecoratedVariable | undefined) + get __backing_provideVar11(): ProvideDecoratedVariable | ProvideDecoratedVariable | undefined set provideVar12(provideVar12: Set | Per | undefined) get provideVar12(): Set | Per | undefined - set __backing_provideVar12(__backing_provideVar12: ProvideDecoratedVariable | Per> | undefined) - get __backing_provideVar12(): ProvideDecoratedVariable | Per> | undefined + set __backing_provideVar12(__backing_provideVar12: ProvideDecoratedVariable> | ProvideDecoratedVariable | undefined) + get __backing_provideVar12(): ProvideDecoratedVariable> | ProvideDecoratedVariable | undefined } `; @@ -278,9 +277,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test complex type @Provide decorated variables transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts index ad9e6798b..e17be814d 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -33,21 +34,15 @@ const pluginTester = new PluginTester('test resource transform in build method', const parsedTransform: Plugins = { name: 'resource-in-build', - parsed: uiTransform().parsed + parsed: uiTransform().parsed, }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIImageAnimatorAttribute as UIImageAnimatorAttribute } from "@ohos.arkui.component"; -import { UISelectAttribute as UISelectAttribute } from "@ohos.arkui.component"; -import { UITextInputAttribute as UITextInputAttribute } from "@ohos.arkui.component"; -import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { _rawfile as _rawfile } from "@ohos.arkui.component"; import { _r as _r } from "@ohos.arkui.component"; +import { UIImageAnimatorAttribute as UIImageAnimatorAttribute } from "@ohos.arkui.component"; +import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, TextInput as TextInput, Select as Select, SelectOption as SelectOption, Margin as Margin, ImageAnimator as ImageAnimator } from "@ohos.arkui.component"; @@ -77,14 +72,14 @@ function main() {} } @memo() public _build(@memo() style: ((instance: ResourceComponent)=> ResourceComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ResourceComponent | undefined): void { - Column(undefined, undefined, (() => { - Text(undefined, _r("", "", "app.string.app_name"), undefined, undefined); - Image(undefined, _rawfile("", "", "app.photo.png"), undefined, undefined); + Column(undefined, (() => { + Text(undefined, _r("", "", "app.string.app_name")); + Image(undefined, _rawfile("", "", "app.photo.png")); TextInput(undefined, { text: _r("", "", "app.string.input_content"), - }, undefined); - Text(undefined, _r("", "", this.str1), undefined, undefined); - Text(undefined, _r("", "", this.str2), undefined, undefined); + }); + Text(undefined, _r("", "", this.str1)); + Text(undefined, _r("", "", this.str2)); Select(undefined, new Array({ value: "aaa", icon: _r("", "", "app.media.selection"), @@ -97,14 +92,14 @@ function main() {} }, { value: "ddd", icon: _r("", "", "app.media.selection"), - }), undefined); + })); Image(@memo() ((instance: UIImageAttribute): void => { instance.margin(({ top: _r("", "", "app.float.elements_margin_horizontal_m"), bottom: _r("", "", "app.float.elements_margin_horizontal_l"), } as Margin)); return; - }), _r("", "", "app.media.app_icon"), undefined, undefined); + }), _r("", "", "app.media.app_icon")); ImageAnimator(@memo() ((instance: UIImageAnimatorAttribute): void => { instance.images([{ src: _r("", "", "app.media.aaa"), @@ -112,13 +107,13 @@ function main() {} src: _r("", "", "app.media.bbb"), }]); return; - }), undefined); + })); })); } - public constructor() {} + private constructor() {} } -interface __Options_ResourceComponent { +@Component({freezeWhenInactive:false}) export interface __Options_ResourceComponent { set str1(str1: string | undefined) get str1(): string | undefined set str2(str2: string | undefined) @@ -132,9 +127,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test resource transform in build method', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:ui-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts index 741751b9f..7b5dc45a3 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,12 +38,7 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { _rawfile as _rawfile } from "@ohos.arkui.component"; import { _r as _r } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; @@ -75,16 +71,16 @@ i = _r("", "", "app.string.app_name"); this.__backing_icon = value; } @memo() public _build(@memo() style: ((instance: ResourceComponent)=> ResourceComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ResourceComponent | undefined): void { - Column(undefined, undefined, (() => { - Text(undefined, this.str, undefined, undefined); - Text(undefined, i, undefined, undefined); - Image(undefined, this.icon, undefined, undefined); + Column(undefined, (() => { + Text(undefined, this.str); + Text(undefined, i); + Image(undefined, this.icon); })); } - public constructor() {} + private constructor() {} } -interface __Options_ResourceComponent { +@Component({freezeWhenInactive:false}) export interface __Options_ResourceComponent { set str(str: Resource | undefined) get str(): Resource | undefined set icon(icon: Resource | undefined) @@ -98,9 +94,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test resource transform in property', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:ui-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts index 0589b25ab..654108e4f 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,23 +38,12 @@ const reusableTransform: Plugins = { const pluginTester = new PluginTester('test basic reusable', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; - -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; - +import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { memo as memo } from "arkui.stateManagement.runtime"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component, Reusable as Reusable } from "@ohos.arkui.component"; - -import { State as State, Link as Link } from "@ohos.arkui.stateManagement"; +import { State as State, Prop as Prop } from "@ohos.arkui.stateManagement"; function main() {} @@ -69,24 +59,27 @@ function main() {} return new Child(); }), ({ num: 5, - } as __Options_Child), undefined, "Child"); + } as __Options_Child), "Child", undefined); } - public constructor() {} + private constructor() {} } @Component({freezeWhenInactive:false}) @Reusable() final class Child extends CustomComponent { public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___98468840 = initializers; - (((gensym___98468840) == (null)) ? undefined : gensym___98468840.__backing_num)})) { - this.__backing_num = new LinkDecoratedVariable("num", initializers!.__backing_num!); - }; + this.__backing_num = new PropDecoratedVariable("num", ((({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.num)})) ?? (1))); this.__backing_num1 = new StateDecoratedVariable("num1", ((({let gensym___33833641 = initializers; (((gensym___33833641) == (null)) ? undefined : gensym___33833641.num1)})) ?? (2))); } - public __updateStruct(initializers: __Options_Child | undefined): void {} + public __updateStruct(initializers: __Options_Child | undefined): void { + if (((({let gensym___108716469 = initializers; + (((gensym___108716469) == (null)) ? undefined : gensym___108716469.num)})) !== (undefined))) { + this.__backing_num!.update((initializers!.num as number)); + } + } public override __toRecord(params: Object): Record { const paramsCasted = (params as __Options_Child); @@ -96,7 +89,7 @@ function main() {} }; } - private __backing_num?: LinkDecoratedVariable; + private __backing_num?: PropDecoratedVariable; public get num(): number { return this.__backing_num!.get(); @@ -118,21 +111,21 @@ function main() {} @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { } -interface __Options_Child { +@Component({freezeWhenInactive:false}) @Reusable() export interface __Options_Child { set num(num: number | undefined) get num(): number | undefined - set __backing_num(__backing_num: DecoratedV1VariableBase | undefined) + set __backing_num(__backing_num: PropDecoratedVariable | undefined) - get __backing_num(): DecoratedV1VariableBase | undefined + get __backing_num(): PropDecoratedVariable | undefined set num1(num1: number | undefined) get num1(): number | undefined @@ -149,9 +142,9 @@ function testReusableTransformer(this: PluginTestContext): void { pluginTester.run( 'test basic reusable', - [reusableTransform, uiNoRecheck], + [reusableTransform, uiNoRecheck, recheck], { - checked: [testReusableTransformer], + 'checked:ui-no-recheck': [testReusableTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts index 873738ced..b4bee34c8 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,26 +38,14 @@ const reusableTransform: Plugins = { const pluginTester = new PluginTester('test complex reusable', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - +import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; - +import { memo as memo } from "arkui.stateManagement.runtime"; import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; - -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; - import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; - import { EntryPoint as EntryPoint } from "arkui.UserView"; - import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component, Entry as Entry, Reusable as Reusable, Column as Column, Text as Text, Button as Button, ClickEvent as ClickEvent, FontWeight as FontWeight } from "@ohos.arkui.component"; - import { State as State } from "@ohos.arkui.stateManagement"; function main() {} @@ -94,24 +83,24 @@ class Message { Column(@memo() ((instance: UIColumnAttribute): void => { instance.height("100%").width("100%"); return; - }), undefined, (() => { + }), (() => { Button(@memo() ((instance: UIButtonAttribute): void => { instance.fontSize(30).fontWeight(FontWeight.Bold).onClick(((e: ClickEvent) => { this.display = !(this.display); })); return; - }), "Hello", undefined, undefined); + }), "Hello"); if (this.display) { Child._instantiateImpl(undefined, (() => { return new Child(); }), ({ message: new Message("Child"), - } as __Options_Child), undefined, "Child"); + } as __Options_Child), "Child", undefined); } })); } - public constructor() {} + private constructor() {} } @@ -148,19 +137,19 @@ class Message { Column(@memo() ((instance: UIColumnAttribute): void => { instance.borderWidth(1).height(100); return; - }), undefined, (() => { + }), (() => { Text(@memo() ((instance: UITextAttribute): void => { instance.fontSize(30); return; - }), this.message.value, undefined, undefined); + }), this.message.value); })); } - public constructor() {} + private constructor() {} } -interface __Options_Index { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_Index { set display(display: boolean | undefined) get display(): boolean | undefined @@ -170,7 +159,7 @@ interface __Options_Index { } -interface __Options_Child { +@Reusable() @Component({freezeWhenInactive:false}) export interface __Options_Child { set message(message: Message | undefined) get message(): Message | undefined @@ -184,7 +173,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { Index._instantiateImpl(undefined, (() => { return new Index(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -199,9 +188,9 @@ function testReusableTransformer(this: PluginTestContext): void { pluginTester.run( 'test complex reusable', - [reusableTransform, uiNoRecheck], + [reusableTransform, uiNoRecheck, recheck], { - checked: [testReusableTransformer], + 'checked:ui-no-recheck': [testReusableTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts index 96d03ea4b..909569f6d 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,8 +38,6 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; @@ -97,10 +96,10 @@ function main() {} this.__backing_stateVar5!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_Parent { +@Component({freezeWhenInactive:false}) export interface __Options_Parent { set stateVar1(stateVar1: string | undefined) get stateVar1(): string | undefined set __backing_stateVar1(__backing_stateVar1: StateDecoratedVariable | undefined) @@ -115,8 +114,8 @@ interface __Options_Parent { get __backing_stateVar3(): StateDecoratedVariable | undefined set stateVar4(stateVar4: undefined | undefined) get stateVar4(): undefined | undefined - set __backing_stateVar4(__backing_stateVar4: StateDecoratedVariable | undefined) - get __backing_stateVar4(): StateDecoratedVariable | undefined + set __backing_stateVar4(__backing_stateVar4: undefined | undefined) + get __backing_stateVar4(): undefined | undefined set stateVar5(stateVar5: null | undefined) get stateVar5(): null | undefined set __backing_stateVar5(__backing_stateVar5: StateDecoratedVariable | undefined) @@ -130,9 +129,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test basic type @State decorated variables transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts index e42e34006..c139596d1 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; +import { structNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,8 +38,6 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; @@ -217,10 +216,10 @@ final class StateType extends BaseEnum { this.__backing_stateVar12!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_Parent { +@Component({freezeWhenInactive:false}) export interface __Options_Parent { set stateVar1(stateVar1: Per | undefined) get stateVar1(): Per | undefined set __backing_stateVar1(__backing_stateVar1: StateDecoratedVariable | undefined) @@ -263,12 +262,12 @@ interface __Options_Parent { get __backing_stateVar10(): StateDecoratedVariable> | undefined set stateVar11(stateVar11: string | number | undefined) get stateVar11(): string | number | undefined - set __backing_stateVar11(__backing_stateVar11: StateDecoratedVariable | undefined) - get __backing_stateVar11(): StateDecoratedVariable | undefined + set __backing_stateVar11(__backing_stateVar11: StateDecoratedVariable | StateDecoratedVariable | undefined) + get __backing_stateVar11(): StateDecoratedVariable | StateDecoratedVariable | undefined set stateVar12(stateVar12: Set | Per | undefined) get stateVar12(): Set | Per | undefined - set __backing_stateVar12(__backing_stateVar12: StateDecoratedVariable | Per> | undefined) - get __backing_stateVar12(): StateDecoratedVariable | Per> | undefined + set __backing_stateVar12(__backing_stateVar12: StateDecoratedVariable> | StateDecoratedVariable | undefined) + get __backing_stateVar12(): StateDecoratedVariable> | StateDecoratedVariable | undefined } `; @@ -278,9 +277,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test complex type @State decorated variables transformation', - [parsedTransform, structNoRecheck], + [parsedTransform, structNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:struct-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts index 52a438991..48b2fb849 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,12 +38,8 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; import { memo as memo } from "arkui.stateManagement.runtime"; import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, Text as Text } from "@ohos.arkui.component"; import { State as State } from "@ohos.arkui.stateManagement"; @@ -70,15 +67,15 @@ class Per { this.__backing_parentVar1!.set(value); } @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { Child._instantiateImpl(undefined, (() => { return new Child(); }), ({ childVar1: this.parentVar1, - } as __Options_Child), undefined, undefined); + } as __Options_Child)); })); } - public constructor() {} + private constructor() {} } @Component({freezeWhenInactive:false}) final class Child extends CustomComponent { @@ -95,20 +92,20 @@ class Per { this.__backing_childVar1!.set(value); } @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - Text(undefined, this.childVar1.str, undefined, undefined); + Text(undefined, this.childVar1.str); } - public constructor() {} + private constructor() {} } -interface __Options_Parent { +@Component({freezeWhenInactive:false}) export interface __Options_Parent { set parentVar1(parentVar1: Per | undefined) get parentVar1(): Per | undefined set __backing_parentVar1(__backing_parentVar1: StateDecoratedVariable | undefined) get __backing_parentVar1(): StateDecoratedVariable | undefined } -interface __Options_Child { +@Component({freezeWhenInactive:false}) export interface __Options_Child { set childVar1(childVar1: Per | undefined) get childVar1(): Per | undefined set __backing_childVar1(__backing_childVar1: StateDecoratedVariable | undefined) @@ -122,9 +119,9 @@ function testParsedAndCheckedTransformer(this: PluginTestContext): void { pluginTester.run( 'test @State decorated variables passing', - [parsedTransform, uiNoRecheck], + [parsedTransform, uiNoRecheck, recheck], { - checked: [testParsedAndCheckedTransformer], + 'checked:ui-no-recheck': [testParsedAndCheckedTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts index 7f4460286..23778c902 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,24 +38,12 @@ const storageLinkTransform: Plugins = { const pluginTester = new PluginTester('test storagelink with appstorage', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - +import { memo as memo } from "arkui.stateManagement.runtime"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; - -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; - import { EntryPoint as EntryPoint } from "arkui.UserView"; - import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; - import { StorageLink as StorageLink, AppStorage as AppStorage } from "@ohos.arkui.stateManagement"; function main() {} @@ -100,27 +89,27 @@ class Data { } @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { Text(@memo() ((instance: UITextAttribute): void => { instance.onClick(((e: ClickEvent) => { this.storageLink += 1; })); return; - }), \`From AppStorage \${this.storageLink}\`, undefined, undefined); + }), \`From AppStorage \${this.storageLink}\`); Text(@memo() ((instance: UITextAttribute): void => { instance.onClick(((e: ClickEvent) => { this.storageLinkObject.code += 1; })); return; - }), \`From AppStorage \${this.storageLinkObject.code}\`, undefined, undefined); + }), \`From AppStorage \${this.storageLinkObject.code}\`); })); } - public constructor() {} + private constructor() {} } -interface __Options_Index { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_Index { set storageLink(storageLink: number | undefined) get storageLink(): number | undefined @@ -140,7 +129,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { Index._instantiateImpl(undefined, (() => { return new Index(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -154,9 +143,9 @@ function testStorageLinkTransformer(this: PluginTestContext): void { pluginTester.run( 'test storagelink with appstorage', - [storageLinkTransform, uiNoRecheck], + [storageLinkTransform, uiNoRecheck, recheck], { - checked: [testStorageLinkTransformer], + 'checked:ui-no-recheck': [testStorageLinkTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts index dba913594..f4f881a92 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,10 +38,6 @@ const storageLinkTransform: Plugins = { const pluginTester = new PluginTester('test storagelink complex type transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; @@ -228,11 +225,11 @@ final class Status extends BaseEnum { @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { set arrayA(arrayA: Array | undefined) get arrayA(): Array | undefined @@ -266,9 +263,9 @@ interface __Options_MyStateSample { set unionA(unionA: string | undefined | undefined) get unionA(): string | undefined | undefined - set __backing_unionA(__backing_unionA: StorageLinkDecoratedVariable | undefined) + set __backing_unionA(__backing_unionA: StorageLinkDecoratedVariable | undefined | undefined) - get __backing_unionA(): StorageLinkDecoratedVariable | undefined + get __backing_unionA(): StorageLinkDecoratedVariable | undefined | undefined set classA(classA: Person | undefined) get classA(): Person | undefined @@ -288,7 +285,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { MyStateSample._instantiateImpl(undefined, (() => { return new MyStateSample(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -303,9 +300,9 @@ function testStorageLinkTransformer(this: PluginTestContext): void { pluginTester.run( 'test storagelink complex type transform', - [storageLinkTransform, uiNoRecheck], + [storageLinkTransform, uiNoRecheck, recheck], { - checked: [testStorageLinkTransformer], + 'checked:ui-no-recheck': [testStorageLinkTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts index 27a78307e..8a63c5ccd 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,10 +38,6 @@ const storageLinkTransform: Plugins = { const pluginTester = new PluginTester('test storagelink primitive type transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; @@ -98,11 +95,11 @@ function main() {} @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { set numA(numA: number | undefined) get numA(): number | undefined @@ -128,7 +125,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { MyStateSample._instantiateImpl(undefined, (() => { return new MyStateSample(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -143,9 +140,9 @@ function testStorageLinkTransformer(this: PluginTestContext): void { pluginTester.run( 'test storagelink primitive type transform', - [storageLinkTransform, uiNoRecheck], + [storageLinkTransform, uiNoRecheck, recheck], { - checked: [testStorageLinkTransformer], + 'checked:ui-no-recheck': [testStorageLinkTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts index e00d66d86..859fcfd48 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,24 +38,12 @@ const storagePropTransform: Plugins = { const pluginTester = new PluginTester('test storageprop with appstorage', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; - +import { memo as memo } from "arkui.stateManagement.runtime"; import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; - -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; - import { EntryPoint as EntryPoint } from "arkui.UserView"; - import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; - import { StorageProp as StorageProp, AppStorage as AppStorage } from "@ohos.arkui.stateManagement"; function main() {} @@ -100,27 +89,27 @@ class Data { } @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { - Column(undefined, undefined, (() => { + Column(undefined, (() => { Text(@memo() ((instance: UITextAttribute): void => { instance.onClick(((e: ClickEvent) => { this.storageProp += 1; })); return; - }), \`From AppStorage \${this.storageProp}\`, undefined, undefined); + }), \`From AppStorage \${this.storageProp}\`); Text(@memo() ((instance: UITextAttribute): void => { instance.onClick(((e: ClickEvent) => { this.storagePropObject.code += 1; })); return; - }), \`From AppStorage \${this.storagePropObject.code}\`, undefined, undefined); + }), \`From AppStorage \${this.storagePropObject.code}\`); })); } - public constructor() {} + private constructor() {} } -interface __Options_Index { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_Index { set storageProp(storageProp: number | undefined) get storageProp(): number | undefined @@ -140,7 +129,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { Index._instantiateImpl(undefined, (() => { return new Index(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -155,9 +144,9 @@ function testStoragePropTransformer(this: PluginTestContext): void { pluginTester.run( 'test storageprop with appstorage', - [storagePropTransform, uiNoRecheck], + [storagePropTransform, uiNoRecheck, recheck], { - checked: [testStoragePropTransformer], + 'checked:ui-no-recheck': [testStoragePropTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts index ca212c7ca..de771b3ec 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,10 +38,6 @@ const storagePropTransform: Plugins = { const pluginTester = new PluginTester('test storageprop complex type transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; @@ -228,11 +225,11 @@ final class Status extends BaseEnum { @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { set arrayB(arrayB: Array | undefined) get arrayB(): Array | undefined @@ -266,9 +263,9 @@ interface __Options_MyStateSample { set unionB(unionB: string | undefined | undefined) get unionB(): string | undefined | undefined - set __backing_unionB(__backing_unionB: StoragePropDecoratedVariable | undefined) + set __backing_unionB(__backing_unionB: StoragePropDecoratedVariable | undefined | undefined) - get __backing_unionB(): StoragePropDecoratedVariable | undefined + get __backing_unionB(): StoragePropDecoratedVariable | undefined | undefined set classB(classB: Person | undefined) get classB(): Person | undefined @@ -288,7 +285,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { MyStateSample._instantiateImpl(undefined, (() => { return new MyStateSample(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -302,9 +299,9 @@ function testStoragePropTransformer(this: PluginTestContext): void { pluginTester.run( 'test storageprop complex type transform', - [storagePropTransform, uiNoRecheck], + [storagePropTransform, uiNoRecheck, recheck], { - checked: [testStoragePropTransformer], + 'checked:ui-no-recheck': [testStoragePropTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts index d6247f205..248becda0 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,10 +38,6 @@ const storagePropTransform: Plugins = { const pluginTester = new PluginTester('test storageprop primitive type transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; @@ -98,11 +95,11 @@ function main() {} @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { set numB(numB: number | undefined) get numB(): number | undefined @@ -128,7 +125,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { MyStateSample._instantiateImpl(undefined, (() => { return new MyStateSample(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -142,9 +139,9 @@ function testStoragePropTransformer(this: PluginTestContext): void { pluginTester.run( 'test storageprop primitive type transform', - [storagePropTransform, uiNoRecheck], + [storagePropTransform, uiNoRecheck, recheck], { - checked: [testStoragePropTransformer], + 'checked:ui-no-recheck': [testStoragePropTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts index fbb612c70..609d89725 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; +import { PluginTester } from '../../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; +import { uiNoRecheck, recheck } from '../../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../../utils/shared-types'; import { uiTransform } from '../../../../../ui-plugins'; import { Plugins } from '../../../../../common/plugin-context'; @@ -37,50 +38,20 @@ const watchTransform: Plugins = { const pluginTester = new PluginTester('test basic watch transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { ConsumeDecoratedVariable as ConsumeDecoratedVariable } from "@ohos.arkui.stateManagement"; - import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { ObjectLinkDecoratedVariable as ObjectLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; - -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; - import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; - import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; - +import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; +import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { int32 as int32 } from "@koalaui.runtime.common"; +import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; +import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; import { EntryPoint as EntryPoint } from "arkui.UserView"; - import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; - import { State as State, Prop as Prop, StorageLink as StorageLink, StorageProp as StorageProp, Link as Link, Watch as Watch, ObjectLink as ObjectLink, Observed as Observed, Track as Track, Provide as Provide, Consume as Consume } from "@ohos.arkui.stateManagement"; function main() {} @@ -221,10 +192,10 @@ function main() {} @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void { Child._instantiateImpl(undefined, (() => { return new Child(); - }), undefined, undefined, undefined); + })); } - public constructor() {} + private constructor() {} } @@ -235,11 +206,11 @@ function main() {} @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void {} - public constructor() {} + private constructor() {} } -interface __Options_MyStateSample { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_MyStateSample { set statevar(statevar: string | undefined) get statevar(): string | undefined @@ -273,7 +244,7 @@ interface __Options_MyStateSample { } -interface __Options_Child { +@Component({freezeWhenInactive:false}) export interface __Options_Child { } @@ -281,7 +252,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { MyStateSample._instantiateImpl(undefined, (() => { return new MyStateSample(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -296,9 +267,9 @@ function testWatchTransformer(this: PluginTestContext): void { pluginTester.run( 'test basic watch transform', - [watchTransform, uiNoRecheck], + [watchTransform, uiNoRecheck, recheck], { - checked: [testWatchTransformer], + 'checked:ui-no-recheck': [testWatchTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/ut/ui-plugins/imports/import-struct.test.ts b/arkui-plugins/test/ut/ui-plugins/imports/import-struct.test.ts new file mode 100644 index 000000000..9a0601eeb --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/imports/import-struct.test.ts @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { recheck, uiNoRecheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; +import { uiTransform } from '../../../../ui-plugins'; +import { Plugins } from '../../../../common/plugin-context'; + +const IMPORT_DIR_PATH: string = 'imports'; +const IMPORT_UTILS_DIR_PATH: string = 'imports/utils'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, IMPORT_DIR_PATH, 'import-struct.ets'), + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, IMPORT_UTILS_DIR_PATH, 'simple-struct.ets') +]; + +const importParsed: Plugins = { + name: 'import-parsed', + parsed: uiTransform().parsed, +}; + +const pluginTester = new PluginTester('test import transform', buildConfig); + +const expectedParsedScript: string = ` +import { __Options_SimpleStruct as __Options_SimpleStruct } from \"./utils/simple-struct\"; +import { CustomComponent as CustomComponent } from \"arkui.component.customComponent\"; +import { Component as Component, Text as Text } from \"@ohos.arkui.component\"; +import { SimpleStruct as SimpleStruct } from \"./utils/simple-struct\"; + +@Component() final class ImportStruct extends CustomComponent { + public build() { + SimpleStruct(); + SimpleStruct(({ + message: \"str1\", + } as __Options_SimpleStruct)); + SimpleStruct(){ + Text(\"a\"); + }; + } + public constructor() {} +} +@Component() export interface __Options_ImportStruct { +} +`; + +const expectedCheckedScript: string = ` +import { memo as memo } from \"arkui.stateManagement.runtime\"; +import { __Options_SimpleStruct as __Options_SimpleStruct } from \"./utils/simple-struct\"; +import { CustomComponent as CustomComponent } from \"arkui.component.customComponent\"; +import { Component as Component, Text as Text } from \"@ohos.arkui.component\"; +import { SimpleStruct as SimpleStruct } from \"./utils/simple-struct\"; + +function main() {} + +@Component({freezeWhenInactive:false}) final class ImportStruct extends CustomComponent { + public __initializeStruct(initializers: __Options_ImportStruct | undefined, @memo() content: (()=> void) | undefined): void {} + public __updateStruct(initializers: __Options_ImportStruct | undefined): void {} + @memo() public _build(@memo() style: ((instance: ImportStruct)=> ImportStruct) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ImportStruct | undefined): void { + SimpleStruct._instantiateImpl(undefined, (() => { + return new SimpleStruct(); + })); + SimpleStruct._instantiateImpl(undefined, (() => { + return new SimpleStruct(); + }), ({ + message: \"str1\", + } as __Options_SimpleStruct)); + SimpleStruct._instantiateImpl(undefined, (() => { + return new SimpleStruct(); + }), (() => { + Text(undefined, \"a\"); + })); + } + private constructor() {} +} +@Component({freezeWhenInactive:false}) export interface __Options_ImportStruct { +} +`; + +function testImportParsed(this: PluginTestContext): void { + expect(parseDumpSrc(this?.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedParsedScript)); +} + +function testImportChecked(this: PluginTestContext): void { + expect(parseDumpSrc(this?.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedCheckedScript)); +} + +pluginTester.run( + 'test import struct from another file', + [importParsed, uiNoRecheck, recheck], + { + 'parsed:import-struct': [testImportParsed], + 'checked:ui-no-recheck:import-struct': [testImportChecked], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts index fc5ee09c6..d73385ec4 100644 --- a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts @@ -14,11 +14,12 @@ */ import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { uiNoRecheck } from '../../../utils/plugins'; +import { recheck, uiNoRecheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; import { uiTransform } from '../../../../ui-plugins'; import { Plugins } from '../../../../common/plugin-context'; @@ -32,25 +33,15 @@ buildConfig.compileFiles = [ const xcomponentTransform: Plugins = { name: 'xcomponent', parsed: uiTransform().parsed, -} +}; const pluginTester = new PluginTester('test basic XComponent transform', buildConfig); const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - import { memo as memo } from "arkui.stateManagement.runtime"; - -import { UIXComponentAttribute as UIXComponentAttribute } from "@ohos.arkui.component"; - import { UIFlexAttribute as UIFlexAttribute } from "@ohos.arkui.component"; - import { EntryPoint as EntryPoint } from "arkui.UserView"; - import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - import { Component as Component, Flex as Flex, XComponent as XComponent, FlexDirection as FlexDirection, XComponentType as XComponentType, Entry as Entry, XComponentController as XComponentController, ItemAlign as ItemAlign, FlexAlign as FlexAlign, XComponentParameter as XComponentParameter } from "@ohos.arkui.component"; function main() {} @@ -89,15 +80,15 @@ function main() {} type: XComponentType.TEXTURE, libraryname: "nativerender", controller: this.myXComponentController, - } as XComponentParameter), "", undefined); + } as XComponentParameter), ""); })); } - public constructor() {} + private constructor() {} } -interface __Options_Index { +@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) export interface __Options_Index { set myXComponentController(myXComponentController: XComponentController | undefined) get myXComponentController(): XComponentController | undefined @@ -108,7 +99,7 @@ class __EntryWrapper extends EntryPoint { @memo() public entry(): void { Index._instantiateImpl(undefined, (() => { return new Index(); - }), undefined, undefined, undefined); + })); } public constructor() {} @@ -122,9 +113,9 @@ function testXComponentTransformer(this: PluginTestContext): void { pluginTester.run( 'test basic XComponent transform', - [xcomponentTransform, uiNoRecheck], + [xcomponentTransform, uiNoRecheck, recheck], { - checked: [testXComponentTransformer], + 'checked:ui-no-recheck': [testXComponentTransformer], }, { stopAfter: 'checked', diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index 3474c59a2..0eab2241e 100644 --- a/arkui-plugins/test/utils/artkts-config.ts +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -22,18 +22,19 @@ import { ensurePathExists, getFileName, getRootPath, + MOCK_DEP_ANALYZER_PATH, MOCK_ENTRY_DIR_PATH, MOCK_ENTRY_FILE_NAME, - MOCK_LOCAL_SDK_DIR_PATH, MOCK_OUTPUT_CACHE_PATH, MOCK_OUTPUT_DIR_PATH, MOCK_OUTPUT_FILE_NAME, PANDA_SDK_STDLIB_PATH, - RUNTIME_API_PATH, STDLIB_ESCOMPAT_PATH, STDLIB_PATH, STDLIB_STD_PATH, } from './path-config'; +import { ArkTSConfigContextCache } from './cache'; +import { BuildConfig, CompileFileInfo, DependentModule } from './shared-types'; export interface ArkTSConfigObject { compilerOptions: { @@ -45,15 +46,6 @@ export interface ArkTSConfigObject { }; } -export interface CompileFileInfo { - fileName: string; - filePath: string; - dependentFiles: string[]; - abcFilePath: string; - arktsConfigFile: string; - stdLibPath: string; -} - export interface ModuleInfo { isMainModule: boolean; packageName: string; @@ -65,41 +57,10 @@ export interface ModuleInfo { dependencies?: string[]; } -export interface DependentModule { - packageName: string; - moduleName: string; - moduleType: string; - modulePath: string; - sourceRoots: string[]; - entryFile: string; -} - -export type ModuleType = 'har' | string; // TODO: module type unclear - -export interface DependentModule { - packageName: string; - moduleName: string; - moduleType: ModuleType; - modulePath: string; - sourceRoots: string[]; - entryFile: string; -} - -export interface BuildConfig { - packageName: string; - compileFiles: string[]; - loaderOutPath: string; - cachePath: string; - pandaSdkPath: string; - buildSdkPath: string; - sourceRoots: string[]; - moduleRootPath: string; - dependentModuleList: DependentModule[]; -} - export interface ArktsConfigBuilder { buildConfig: BuildConfig; entryFiles: Set; + compileFiles: Map; outputDir: string; cacheDir: string; pandaSdkPath: string; @@ -112,6 +73,8 @@ export interface ArktsConfigBuilder { mergedAbcFile: string; // logger: Logger; // TODO isDebug: boolean; + + clear(): void; } function writeArkTSConfigFile( @@ -158,21 +121,6 @@ function getDependentModules(moduleInfo: ModuleInfo, moduleInfoMap: Map) { - const items = fs.readdirSync(currentDir); - for (const item of items) { - const itemPath = path.join(currentDir, item); - const stat = fs.statSync(itemPath); - - if (stat.isFile()) { - const basename = path.basename(item, '.d.ets'); - pathSection[basename] = [changeFileExtension(itemPath, '', '.d.ets')]; - } else if (stat.isDirectory()) { - traverse(itemPath, pathSection); - } - } -} - function traverseSDK(currentDir: string, pathSection: Record, prefix?: string) { const items = fs.readdirSync(currentDir); @@ -204,6 +152,7 @@ function mockBuildConfig(): BuildConfig { cachePath: path.resolve(getRootPath(), MOCK_OUTPUT_CACHE_PATH), pandaSdkPath: global.PANDA_SDK_PATH, buildSdkPath: global.API_PATH, + depAnalyzerPath: path.resolve(global.PANDA_SDK_PATH, MOCK_DEP_ANALYZER_PATH), sourceRoots: [getRootPath()], moduleRootPath: path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH), dependentModuleList: [], @@ -211,8 +160,10 @@ function mockBuildConfig(): BuildConfig { } class MockArktsConfigBuilder implements ArktsConfigBuilder { + hashId: string; buildConfig: BuildConfig; entryFiles: Set; + compileFiles: Map; outputDir: string; cacheDir: string; pandaSdkPath: string; @@ -225,7 +176,9 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { mergedAbcFile: string; isDebug: boolean; - constructor(buildConfig?: BuildConfig) { + constructor(hashId: string, buildConfig?: BuildConfig) { + this.hashId = hashId; + const _buildConfig: BuildConfig = buildConfig ?? mockBuildConfig(); this.buildConfig = _buildConfig; this.entryFiles = new Set(_buildConfig.compileFiles as string[]); @@ -239,11 +192,50 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { this.dependentModuleList = _buildConfig.dependentModuleList as DependentModule[]; this.isDebug = true; + this.compileFiles = new Map(); this.moduleInfos = new Map(); this.mergedAbcFile = path.resolve(this.outputDir, MOCK_OUTPUT_FILE_NAME); this.generateModuleInfos(); this.generateArkTSConfigForModules(); + this.cacheArkTSConfig(); + } + + private cacheArkTSConfig(): void { + const mainModuleInfo: ModuleInfo = this.moduleInfos.get(this.moduleRootPath)!; + const arktsConfigFile: string = mainModuleInfo.arktsConfigFile; + const compileFiles: Map = this.compileFiles; + ArkTSConfigContextCache.getInstance().set(this.hashId, { arktsConfigFile, compileFiles }); + } + + private generateModuleInfosInEntryFile(file: string): void { + const _file = path.resolve(file); + for (const [modulePath, moduleInfo] of this.moduleInfos) { + if (!_file.startsWith(modulePath)) { + throw new Error('Entry File does not belong to any module in moduleInfos.'); + } + const filePathFromModuleRoot: string = path.relative(modulePath, _file); + const filePathInCache: string = path.join( + this.cacheDir, + this.hashId, + moduleInfo.packageName, + filePathFromModuleRoot + ); + const abcFilePath: string = path.resolve(changeFileExtension(filePathInCache, ABC_SUFFIX)); + + const fileInfo: CompileFileInfo = { + fileName: getFileName(_file), + filePath: _file, + dependentFiles: [], + abcFilePath: abcFilePath, + arktsConfigFile: moduleInfo.arktsConfigFile, + stdLibPath: path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_PATH), + }; + moduleInfo.compileFileInfos.push(fileInfo); + if (!this.compileFiles.has(_file)) { + this.compileFiles.set(_file, fileInfo); + } + } } private generateModuleInfos(): void { @@ -256,7 +248,7 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { moduleRootPath: this.moduleRootPath, sourceRoots: this.sourceRoots, entryFile: '', - arktsConfigFile: path.resolve(this.cacheDir, this.packageName, ARKTS_CONFIG_FILE_PATH), + arktsConfigFile: path.resolve(this.cacheDir, this.hashId, this.packageName, ARKTS_CONFIG_FILE_PATH), compileFileInfos: [], }; this.moduleInfos.set(this.moduleRootPath, mainModuleInfo); @@ -270,36 +262,13 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { moduleRootPath: module.modulePath, sourceRoots: module.sourceRoots, entryFile: module.entryFile, - arktsConfigFile: path.resolve(this.cacheDir, module.packageName, ARKTS_CONFIG_FILE_PATH), + arktsConfigFile: path.resolve(this.cacheDir, this.hashId, module.packageName, ARKTS_CONFIG_FILE_PATH), compileFileInfos: [], }; this.moduleInfos.set(module.modulePath, moduleInfo); }); this.entryFiles.forEach((file: string) => { - const _file = path.resolve(file); - for (const [modulePath, moduleInfo] of this.moduleInfos) { - if (_file.startsWith(modulePath)) { - const filePathFromModuleRoot: string = path.relative(modulePath, _file); - const filePathInCache: string = path.join( - this.cacheDir, - moduleInfo.packageName, - filePathFromModuleRoot - ); - const abcFilePath: string = path.resolve(changeFileExtension(filePathInCache, ABC_SUFFIX)); - - const fileInfo: CompileFileInfo = { - fileName: getFileName(_file), - filePath: _file, - dependentFiles: [], - abcFilePath: abcFilePath, - arktsConfigFile: moduleInfo.arktsConfigFile, - stdLibPath: path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_PATH), - }; - moduleInfo.compileFileInfos.push(fileInfo); - return; - } - } - throw new Error('Entry File does not belong to any module in moduleInfos.'); + this.generateModuleInfosInEntryFile(file); }); } @@ -329,6 +298,10 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { dependenciesSection.push(depModuleInfo.arktsConfigFile); }); } + + clear(): void { + ArkTSConfigContextCache.getInstance().delete(this.hashId); + } } export { mockBuildConfig, MockArktsConfigBuilder }; diff --git a/arkui-plugins/test/utils/cache.ts b/arkui-plugins/test/utils/cache.ts index b24fcdf64..06942d1c4 100644 --- a/arkui-plugins/test/utils/cache.ts +++ b/arkui-plugins/test/utils/cache.ts @@ -13,21 +13,15 @@ * limitations under the License. */ +import { ArkTSConfigContext, FileDependencyContext, PluginTestContext } from './shared-types'; + class TesterCache { private cacheInfo: Map; - private static instance: TesterCache; - private constructor() { + constructor() { this.cacheInfo = new Map(); } - static getInstance(): TesterCache { - if (!this.instance) { - this.instance = new TesterCache(); - } - return this.instance; - } - public delete(key: string) { if (this.cacheInfo.has(key)) { this.cacheInfo.delete(key); @@ -56,4 +50,37 @@ class TesterCache { } } -export { TesterCache }; +class PluginTestContextCache extends TesterCache { + private static _instance: TesterCache; + + static getInstance(): TesterCache { + if (!this._instance) { + this._instance = new PluginTestContextCache(); + } + return this._instance; + } +} + +class ArkTSConfigContextCache extends TesterCache { + private static _instance: TesterCache; + + static getInstance(): TesterCache { + if (!this._instance) { + this._instance = new ArkTSConfigContextCache(); + } + return this._instance; + } +} + +class FileDependencyContextCache extends TesterCache { + private static _instance: TesterCache; + + static getInstance(): TesterCache { + if (!this._instance) { + this._instance = new FileDependencyContextCache(); + } + return this._instance; + } +} + +export { TesterCache, PluginTestContextCache, ArkTSConfigContextCache, FileDependencyContextCache }; diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index f893dae3b..1c9640de4 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -13,48 +13,190 @@ * limitations under the License. */ -import { PluginDriver } from './plugin-driver'; -import { PluginContext, PluginExecutor } from '../../common/plugin-context'; -import { EtsglobalRemover } from '../../common/etsglobal-remover'; import * as arkts from '@koalaui/libarkts'; +import EventEmitter from 'events'; +import type { JobInfo, PluginTestContext, ProcessEvent, SingleProgramContext, TraceOptions } from './shared-types'; +import { MockPluginDriver, stateName } from './plugin-driver'; +import { createCacheContextFromFile, destroyContext, resetConfig } from './global'; +import { PluginDriver } from './plugin-driver'; +import { PluginState, PluginContext, PluginExecutor } from '../../common/plugin-context'; -function restartCompilerUptoState(state: arkts.Es2pandaContextState, restart: boolean): boolean { - try { - const ast: arkts.EtsScript | undefined = arkts.EtsScript.fromContext(); - if (!ast) { - return false; - } +function insertPlugin(driver: PluginDriver, plugin: PluginExecutor | undefined): boolean { + const pluginContext: PluginContext = driver.getPluginContext(); + if (plugin) { + plugin.handler.apply(pluginContext); + } + return true; +} - if (restart) { - const srcText = new EtsglobalRemover().visitor(ast).dumpSrc(); - arkts.arktsGlobal.es2panda._DestroyContext(arkts.arktsGlobal.context); - arkts.arktsGlobal.compilerContext = arkts.Context.createFromString(srcText); +function collectPluginTestContext( + context: arkts.Context, + isExternal: boolean, + tracing: TraceOptions +): PluginTestContext { + const pluginTestContext: PluginTestContext = {}; + try { + const program: arkts.Program = arkts.getOrUpdateGlobalContext(context.peer).program; + // TODO: add error/warning handling after plugin + if (!isExternal) { + const script: arkts.EtsScript = program.astNode; + pluginTestContext.scriptSnapshot = script.dumpSrc(); + } else { + const declContexts: Record = {}; + const externalSources: arkts.ExternalSource[] = program.externalSources; + externalSources + .filter((source) => { + const sourceProgram: arkts.Program = source.programs[0]; + return ( + tracing.externalSourceNames.includes(source.getName()) && + sourceProgram && + sourceProgram.isASTLowered() + ); + }) + .forEach((source) => { + const sourceProgram: arkts.Program = source.programs[0]; + const sourceTestContext: SingleProgramContext = {}; + const name: string = source.getName(); + const script: arkts.EtsScript = sourceProgram.astNode; + const scriptSnapshot = script.dumpSrc(); + sourceTestContext.scriptSnapshot = scriptSnapshot; + declContexts[name] = sourceTestContext; + }); + pluginTestContext.declContexts = declContexts; } - - arkts.proceedToState(state); - return true; } catch (e) { - return false; + // Do nothing + } finally { + return pluginTestContext; } } -function insertPlugin( - driver: PluginDriver, - plugin: PluginExecutor | undefined, - state: arkts.Es2pandaContextState +/** + * @param emitter event emitter. + * @param jobInfo job info. + * @param state the current state. + * @param context context for the single file. + * @param isExternal boolean indicates if plugin is compiling external sources. + * @param stopAfter state that should stop after running plugins. + * @returns boolean indicates whether should proceed to the next state. + */ +function runPluginsAtState( + emitter: EventEmitter, + jobInfo: JobInfo, + state: arkts.Es2pandaContextState, + context: arkts.Context, + isExternal: boolean, + tracing: TraceOptions, + stopAfter?: PluginState ): boolean { - arkts.proceedToState(state); - const pluginContext: PluginContext = driver.getPluginContext(); - const ast: arkts.EtsScript | undefined = arkts.EtsScript.fromContext(); - - if (!ast) { - return false; + const stateStr = stateName(state); + const plugins = MockPluginDriver.getInstance().getSortedPlugins(state); + const fileName = jobInfo.compileFileInfo!.fileName; + if (plugins && plugins.length > 0) { + plugins.forEach((plugin) => { + insertPlugin(MockPluginDriver.getInstance(), plugin); + const pluginName: string = plugin.name; + const pluginStateId: `${PluginState}:${string}` = `${stateStr}:${pluginName}`; + const pluginTestContext = collectPluginTestContext(context, isExternal, tracing); + emitter.emit('TASK_COLLECT', { + jobId: jobInfo.id, + pluginStateId, + pluginTestContext: pluginTestContext, + fileName, + }); + }); } + const pluginStateId: PluginState = `${stateStr}`; + const pluginTestContext = collectPluginTestContext(context, isExternal, tracing); + emitter.emit('TASK_COLLECT', { + jobId: jobInfo.id, + pluginStateId, + pluginTestContext: pluginTestContext, + fileName, + }); + return !!stopAfter && stopAfter === stateStr; +} - if (plugin) { - plugin.handler.apply(pluginContext); +function createContextForAbcCompilation(jobInfo: JobInfo): arkts.Context { + const fileInfo = jobInfo.compileFileInfo!; + const globalContextPtr = jobInfo.globalContextPtr!; + const ets2pandaCmd = [ + '_', + '--extension', + 'ets', + '--arktsconfig', + fileInfo.arktsConfigFile, + '--output', + fileInfo.abcFilePath, + ]; + ets2pandaCmd.push(fileInfo.filePath); + const config = resetConfig(ets2pandaCmd); + const context = createCacheContextFromFile(config, fileInfo.filePath, globalContextPtr, false); + return context; +} + +function createContextForExternalCompilation(jobInfo: JobInfo): arkts.Context { + const fileInfo = jobInfo.compileFileInfo!; + const globalContextPtr = jobInfo.globalContextPtr!; + const ets2pandaCmd = ['-', '--extension', 'ets', '--arktsconfig', fileInfo.arktsConfigFile]; + ets2pandaCmd.push(fileInfo.filePath); + const config = resetConfig(ets2pandaCmd); + const context = createCacheContextFromFile(config, fileInfo.filePath, globalContextPtr, true); + return context; +} + +function compileAbc(emitter: EventEmitter, jobInfo: JobInfo, tracing: TraceOptions): void { + MockPluginDriver.getInstance().initPlugins(jobInfo.plugins ?? []); + const context = createContextForAbcCompilation(jobInfo); + MockPluginDriver.getInstance().getPluginContext().setContextPtr(context.peer); + const stopAfter = jobInfo.stopAfter!; + let shouldStop = false; + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context.peer); + shouldStop = runPluginsAtState( + emitter, + jobInfo, + arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + context, + false, + tracing, + stopAfter + ); + if (shouldStop) { + destroyContext(context); + MockPluginDriver.getInstance().clear(); + return; } - return true; + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context.peer); + shouldStop = runPluginsAtState( + emitter, + jobInfo, + arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + context, + false, + tracing, + stopAfter + ); + if (shouldStop) { + destroyContext(context); + MockPluginDriver.getInstance().clear(); + return; + } + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED, context.peer); + destroyContext(context); + MockPluginDriver.getInstance().clear(); +} + +function compileExternalProgram(emitter: EventEmitter, jobInfo: JobInfo, tracing: TraceOptions): void { + MockPluginDriver.getInstance().initPlugins(jobInfo.plugins ?? []); + const context = createContextForExternalCompilation(jobInfo); + MockPluginDriver.getInstance().getPluginContext().setContextPtr(context.peer); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context.peer); + runPluginsAtState(emitter, jobInfo, arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context, true, tracing); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context.peer); + runPluginsAtState(emitter, jobInfo, arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context, true, tracing); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_LOWERED, context.peer); + destroyContext(context); + MockPluginDriver.getInstance().clear(); } -export { restartCompilerUptoState, insertPlugin }; +export { compileAbc, compileExternalProgram }; diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index cbccd4afa..99ac287e3 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -13,11 +13,10 @@ * limitations under the License. */ -import * as fs from 'fs'; -import { CompileFileInfo } from './artkts-config'; import * as arkts from '@koalaui/libarkts'; +import { CompileFileInfo } from './shared-types'; -function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { +function createGlobalConfig(fileInfo: CompileFileInfo, isDebug: boolean = true): arkts.Config { const config = [ '_', '--extension', @@ -33,11 +32,31 @@ function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { } config.push(fileInfo.filePath); + arkts.MemInitialize(); arkts.arktsGlobal.filePath = fileInfo.filePath; - resetConfig(config); + return resetConfig(config); +} + +function destroyGlobalConfig(config: arkts.Config): void { + destroyConfig(config); + arkts.MemFinalize(); +} + +function createGlobalContextPtr(config: arkts.Config, files: string[]): number { + return arkts.CreateGlobalContext(config.peer, files, files.length, false); +} + +function destroyGlobalContextPtr(globalContextPtr: number): void { + arkts.DestroyGlobalContext(globalContextPtr); +} - const source: string = fs.readFileSync(fileInfo.filePath).toString(); - resetContext(source); +function createCacheContextFromFile( + config: arkts.Config, + filePath: string, + globalContextPtr: number, + isExternal: boolean +): arkts.Context { + return arkts.Context.createCacheContextFromFile(config.peer, filePath, globalContextPtr, isExternal); } function resetContext(source: string): void { @@ -51,48 +70,43 @@ function resetContext(source: string): void { } } -function resetConfig(cmd: string[]): void { +function resetConfig(cmd: string[]): arkts.Config { try { arkts.arktsGlobal.config; - destroyConfig(); + destroyConfig(arkts.arktsGlobal.config); } catch (e) { // Do nothing } finally { - const arkTSConfig: arkts.Config = arkts.Config.create(cmd); - arkts.arktsGlobal.config = arkTSConfig.peer; + const config = arkts.Config.create(cmd); + arkts.arktsGlobal.config = config.peer; + return config; } } -function destroyContext(): void { +function destroyContext(context: arkts.Context): void { try { - arkts.arktsGlobal.clearContext(); + arkts.arktsGlobal.es2panda._DestroyContext(context.peer); } catch (e) { // Do nothing } } -function destroyConfig(): void { +function destroyConfig(config: arkts.Config): void { try { - arkts.destroyConfig(arkts.arktsGlobal.config); + arkts.destroyConfig(config); } catch (e) { // Do nothing } } -function canProceedToState(state: arkts.Es2pandaContextState): boolean { - const stateToSkip: arkts.Es2pandaContextState[] = [ - arkts.Es2pandaContextState.ES2PANDA_STATE_SCOPE_INITED, - arkts.Es2pandaContextState.ES2PANDA_STATE_BOUND, - arkts.Es2pandaContextState.ES2PANDA_STATE_LOWERED, - arkts.Es2pandaContextState.ES2PANDA_STATE_ASM_GENERATED, - arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR, - ]; - if (state in stateToSkip) { - return false; - } - - const currState = arkts.arktsGlobal.es2panda._ContextState(arkts.arktsGlobal.context); - return currState < state; -} - -export { initGlobal, resetContext, resetConfig, destroyContext, destroyConfig, canProceedToState }; +export { + createGlobalConfig, + destroyGlobalConfig, + createGlobalContextPtr, + destroyGlobalContextPtr, + createCacheContextFromFile, + resetContext, + resetConfig, + destroyContext, + destroyConfig, +}; diff --git a/arkui-plugins/test/local/@ohos.arkui.component.styledString.d.ets b/arkui-plugins/test/utils/hash-generator.ts similarity index 36% rename from arkui-plugins/test/local/@ohos.arkui.component.styledString.d.ets rename to arkui-plugins/test/utils/hash-generator.ts index 4a0e94d6f..09e0b6d45 100644 --- a/arkui-plugins/test/local/@ohos.arkui.component.styledString.d.ets +++ b/arkui-plugins/test/utils/hash-generator.ts @@ -1,5 +1,5 @@ /* - * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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 @@ -13,20 +13,36 @@ * limitations under the License. */ -export declare class StyledString { - constructor(value: string /*| ImageAttachment | CustomSpan, styles?: Array*/); +import { randomBytes } from 'crypto'; +import { getCommonPath } from '../../path'; +const common = require(getCommonPath()); +const UniqueId = common.UniqueId; - readonly length: number; +export class HashGenerator { + static instance: HashGenerator; - getString(): string; - // getStyles(start: number, length: number, styledKey?: StyledStringKey): Array; - equals(other: StyledString): boolean; - subStyledString(start: number, length?: number): StyledString; + private constructor() {} - static fromHtml(html: string): Promise; - static toHtml(styledString: StyledString): string; - // static marshalling(styledString: StyledString, callback: StyledStringMarshallCallback): ArrayBuffer; - // static unmarshalling(buffer: ArrayBuffer, callback: StyledStringUnmarshallCallback): Promise; - // static marshalling(styledString: StyledString): ArrayBuffer; - // static unmarshalling(buffer: ArrayBuffer): Promise; -} \ No newline at end of file + static getInstance(): HashGenerator { + if (!this.instance) { + this.instance = new HashGenerator(); + } + + return this.instance; + } + + dynamicSha1Id(id: string, length: number = 7): string { + const uniqId = new UniqueId(); + uniqId.addString('hashId'); + uniqId.addString(id); + uniqId.addString(randomBytes(length).toString('hex')); + return uniqId.compute().substring(0, length); + } + + staticSha1Id(id: string, length: number = 7): string { + const uniqId = new UniqueId(); + uniqId.addString('hashId'); + uniqId.addString(id); + return uniqId.compute().substring(0, length); + } +} diff --git a/arkui-plugins/test/utils/path-config.ts b/arkui-plugins/test/utils/path-config.ts index 608df6dee..4712832cf 100644 --- a/arkui-plugins/test/utils/path-config.ts +++ b/arkui-plugins/test/utils/path-config.ts @@ -16,24 +16,25 @@ import * as fs from 'fs'; import * as path from 'path'; -export const ARKTS_CONFIG_FILE_PATH: string = 'arktsconfig.json'; -export const PANDA_SDK_PATH: string = 'node_modules/@panda/sdk'; +export const ARKTS_CONFIG_FILE_PATH: string = 'arktsconfig.json';; export const PANDA_SDK_STDLIB_PATH: string = 'lib'; export const STDLIB_PATH: string = 'stdlib'; export const STDLIB_STD_PATH: string = 'stdlib/std'; export const STDLIB_ESCOMPAT_PATH: string = 'stdlib/escompat'; -export const RUNTIME_API_PATH: string = 'demo/runtime-api'; export const MOCK_ENTRY_DIR_PATH: string = 'demo/mock'; export const MOCK_ENTRY_FILE_NAME: string = 'entry.ets'; export const MOCK_OUTPUT_CACHE_PATH: string = 'generated/cache'; export const MOCK_OUTPUT_DIR_PATH: string = 'generated/abc'; export const MOCK_OUTPUT_FILE_NAME: string = 'entry.abc'; -export const MOCK_LOCAL_SDK_DIR_PATH: string = 'local'; +export const MOCK_DEP_ANALYZER_PATH: string = 'bin/dependency_analyzer'; +export const MOCK_FILE_DEP_FILE_NAME: string = 'file_dependencies.json'; +export const MOCK_DEP_INPUT_FILE_NAME: string = 'depInput.txt'; export const ETS_SUFFIX: string = '.ets'; export const ABC_SUFFIX: string = '.abc'; +export const DECL_ETS_SUFFIX: string = '.d.ets'; function getRootPath(): string { - return path.resolve(__dirname, '..'); + return path.resolve(__dirname, '..', '..', 'test'); } function changeFileExtension(file: string, targetExt: string, originExt = ''): string { diff --git a/arkui-plugins/test/utils/plugin-driver.ts b/arkui-plugins/test/utils/plugin-driver.ts index 46ce7f562..ef64a91bf 100644 --- a/arkui-plugins/test/utils/plugin-driver.ts +++ b/arkui-plugins/test/utils/plugin-driver.ts @@ -15,12 +15,15 @@ import { isNumber } from './safe-types'; import { Plugins, PluginContext, PluginHandler, PluginState, PluginExecutor } from '../../common/plugin-context'; +import { PluginStateId } from './shared-types'; import * as arkts from '@koalaui/libarkts'; export interface PluginDriver { initPlugins(plugins: Plugins[]): void; getSortedPlugins(state: arkts.Es2pandaContextState): PluginExecutor[] | undefined; getPluginContext(): PluginContext; + getPluginHistory(): PluginStateId[]; + clear(): void; } function toCamelCase(str: string): string { @@ -71,25 +74,45 @@ function selectPlugins(plugins: Plugins[], stage: PluginState): PluginExecutor[] class MockPluginDriver implements PluginDriver { private sortedPlugins: Map; - private context: PluginContext; + private history: Set; + private context: PluginContext | undefined; + + private static instance: PluginDriver | undefined; constructor() { this.sortedPlugins = new Map(); + this.history = new Set(); this.context = new PluginContext(); } + public static getInstance(): PluginDriver { + if (!this.instance) { + this.instance = new MockPluginDriver(); + } + return this.instance; + } + + private collectHistory(state: PluginState, plugins: PluginExecutor[]) { + for (const plugin of plugins) { + this.history.add(`${state}:${plugin.name}`); + } + this.history.add(state); + } + public initPlugins(plugins: Plugins[]): void { const pluginsByState = new Map(); Object.values(arkts.Es2pandaContextState) .filter(isNumber) .forEach((it) => { - const selected = selectPlugins(plugins, stateName(it)); + const state = stateName(it); + const selected = selectPlugins(plugins, state); if (selected.length > 0) { pluginsByState.set(it, selected); } else { pluginsByState.set(it, undefined); } + this.collectHistory(state, selected); }); this.sortedPlugins = pluginsByState; @@ -100,8 +123,20 @@ class MockPluginDriver implements PluginDriver { } public getPluginContext(): PluginContext { + if (!this.context) { + this.context = new PluginContext(); + } return this.context; } + + public getPluginHistory(): PluginStateId[] { + return Array.from(this.history); + } + + public clear(): void { + this.sortedPlugins.clear(); + this.context = undefined; + } } export { stateName, MockPluginDriver }; diff --git a/arkui-plugins/test/utils/plugin-tester.ts b/arkui-plugins/test/utils/plugin-tester.ts index 710456e21..8a64da3fc 100644 --- a/arkui-plugins/test/utils/plugin-tester.ts +++ b/arkui-plugins/test/utils/plugin-tester.ts @@ -13,29 +13,28 @@ * limitations under the License. */ -import { ArktsConfigBuilder, BuildConfig, CompileFileInfo, MockArktsConfigBuilder, ModuleInfo } from './artkts-config'; -import { MockPluginDriver, PluginDriver, stateName } from './plugin-driver'; -import { isNumber } from './safe-types'; +import { ArktsConfigBuilder, MockArktsConfigBuilder } from './artkts-config'; +import { MockPluginDriver } from './plugin-driver'; import { - canProceedToState, - destroyConfig, - destroyContext, - initGlobal, - resetConfig, - resetContext, -} from './global'; -import { insertPlugin } from './compile'; -import { PluginExecutor, Plugins, PluginState } from '../../common/plugin-context'; -import { TesterCache } from './cache'; -import * as arkts from '@koalaui/libarkts'; -import * as fs from 'fs'; + BuildConfig, + CompileFileInfo, + PluginStateId, + PluginTestContext, + SingleProgramContext, + TraceOptions, +} from './shared-types'; +import { HashGenerator } from './hash-generator'; +import { TaskProcessor } from './task-processor'; +import { PluginTestContextCache } from './cache'; +import { Plugins, PluginState } from '../../common/plugin-context'; +import { concatObject } from './serializable'; type TestParams = Parameters; type SkipFirstParam = T extends [unknown, ...infer Rest] ? Rest : never; type PluginTestHooks = { - [K in PluginState | `${PluginState}:${string}`]?: SkipFirstParam; + [K in PluginStateId]?: SkipFirstParam; }; type TestHooks = { @@ -44,134 +43,132 @@ type TestHooks = { afterEach?: Parameters; }; -export interface PluginTestContext { - scriptSnapshot?: string; - errors?: string[]; - warnings?: string[]; -} - export interface PluginTesterOptions { stopAfter: PluginState; buildConfig?: BuildConfig; + tracing?: TraceOptions; } class PluginTester { - private configBuilder: ArktsConfigBuilder; - private pluginDriver: PluginDriver; + private hashId: string; private describe: string; - private cache: TesterCache; + private configBuilder: ArktsConfigBuilder; + private taskProcessor?: TaskProcessor; + private resolve?: Promise; constructor(describe: string, buildConfig?: BuildConfig) { this.describe = describe; - this.configBuilder = new MockArktsConfigBuilder(buildConfig); - this.pluginDriver = new MockPluginDriver(); - this.cache = TesterCache.getInstance(); + this.hashId = HashGenerator.getInstance().dynamicSha1Id(describe, 13); + this.configBuilder = new MockArktsConfigBuilder(this.hashId, buildConfig); } - private loadPluginDriver(plugins: Plugins[]): void { - this.pluginDriver.initPlugins(plugins); + private clear(): void { + this.clearCache(); + this.configBuilder.clear(); + this.taskProcessor?.clear(); + MockPluginDriver.getInstance().clear(); } - private test( - key: PluginState | `${PluginState}:${string}`, - index: arkts.Es2pandaContextState, - testName: string, - pluginHooks: PluginTestHooks, - plugin?: PluginExecutor - ): void { - let cached: boolean = false; - const cacheKey: string = `${testName}-${key}`; - if (index > arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) { - return; - } - if (canProceedToState(index)) { - arkts.proceedToState(index); - } - if (plugin) { - insertPlugin(this.pluginDriver, plugin, index); - this.captureContext(cacheKey); - cached = true; - } - const hook: SkipFirstParam | undefined = pluginHooks[key]; - if (!!hook) { - if (!cached) this.captureContext(cacheKey); - test(testName, hook[0]?.bind(this.cache.get(cacheKey)), hook[1]); + private clearCache(): void { + const moduleInfo = this.configBuilder.moduleInfos.get(this.configBuilder.moduleRootPath)!; + const fileHistory = moduleInfo.compileFileInfos.map((fileInfo) => fileInfo.fileName) ?? []; + const pluginHistory = MockPluginDriver.getInstance().getPluginHistory(); + for (const pluginStateId of pluginHistory) { + const abcKey = this.getCacheKey(pluginStateId); + const externalKey = this.getCacheKey(pluginStateId, true); + for (const fileName of fileHistory) { + PluginTestContextCache.getInstance().delete(`${abcKey}:${fileName}`); + PluginTestContextCache.getInstance().delete(`${externalKey}:${fileName}`); + } } } - private captureContext(cacheKey: string): void { - try { - // TODO: add error/warning handling after plugin - const context: PluginTestContext = this.cache.get(cacheKey) ?? {}; - const script: arkts.EtsScript = arkts.EtsScript.fromContext(); - context.scriptSnapshot = script.dumpSrc(); - this.cache.set(cacheKey, context); - } catch (e) { - // Do nothing + private getCacheKey(pluginStateId: PluginStateId, isExternal?: boolean) { + return [this.hashId, !!isExternal ? 'external' : 'abc', pluginStateId].join(':'); + } + + private prepareContext(pluginStateId: PluginStateId, fileInfos: CompileFileInfo[]): PluginTestContext { + const fileNames: string[] = fileInfos.map((fileInfo) => fileInfo.fileName); + + const abcKey = this.getCacheKey(pluginStateId); + const externalKey = this.getCacheKey(pluginStateId, true); + + const sourceContexts: Record = {}; + let declContexts: Record = {}; + fileNames.forEach((fileName) => { + const sourceKey = `${abcKey}:${fileName}`; + const sourceContext = PluginTestContextCache.getInstance().get(sourceKey)!; + sourceContexts[fileName] = sourceContext; + + const declKey = `${externalKey}:${fileName}`; + const declContext = PluginTestContextCache.getInstance().get(declKey)!; + declContexts = concatObject(declContexts, declContext.declContexts); + }); + + return { sourceContexts, declContexts }; + } + + private findContext(testContext: PluginTestContext | undefined, fileName?: string): PluginTestContext | undefined { + if (!testContext) { + return undefined; } + if (!testContext.sourceContexts) { + return { declContexts: testContext.declContexts }; + } + const sourceContext = fileName + ? testContext.sourceContexts[fileName] + : Object.values(testContext.sourceContexts)[Symbol.iterator]().next().value; + return { ...sourceContext, declContexts: testContext.declContexts }; } - private proceedToState( - state: PluginState, - index: arkts.Es2pandaContextState, + private test( + pluginStateId: PluginStateId, testName: string, - pluginHooks: PluginTestHooks, - plugins?: PluginExecutor[] + hook: SkipFirstParam | undefined, + compileFiles: CompileFileInfo[], + fileName?: string ): void { - if (plugins && plugins.length > 0) { - plugins.forEach((plugin) => { - const pluginName: string = plugin.name; - const key: `${PluginState}:${string}` = `${state}:${pluginName}`; - this.test(key, index, `[${key}] ${testName}`, pluginHooks, plugin); - }); + if (!!hook) { + const that = this; + test( + testName, + async () => { + let context: PluginTestContext | undefined; + await that.resolve?.then(async () => { + const testContext = this.prepareContext(pluginStateId, compileFiles ?? []); + context = this.findContext(testContext, fileName); + }); + hook[0]?.bind(context)(undefined as any); + }, + hook[1] + ); } - this.test(state, index, `[${state}] ${testName}`, pluginHooks); } - private singleFileCompile( - fileInfo: CompileFileInfo, - moduleInfo: ModuleInfo, - testName: string, - pluginHooks: PluginTestHooks, - stopAfter: PluginState - ): void { - let shouldStop: boolean = false; - - Object.values(arkts.Es2pandaContextState) - .filter(isNumber) - .forEach((it) => { - if (shouldStop) { - return; - } - const state: PluginState = stateName(it); - const plugins: PluginExecutor[] | undefined = this.pluginDriver.getSortedPlugins(it); - this.proceedToState( - state, - it, - `${moduleInfo.packageName} - ${fileInfo.fileName}: ${testName}`, - pluginHooks, - plugins - ); - shouldStop = state === stopAfter; - }); + private pluginTests(key: PluginStateId, testName: string, pluginHooks: PluginTestHooks): void { + const moduleInfo = this.configBuilder.moduleInfos.get(this.configBuilder.moduleRootPath)!; + const compileFiles = moduleInfo.compileFileInfos; + compileFiles?.forEach((fileInfo) => { + const fileName = fileInfo.fileName; + const name: string = `[${key}] ${moduleInfo.packageName} - ${fileName}: ${testName}`; + this.test(key, name, pluginHooks[`${key}:${fileName}`], compileFiles, fileName); + }); + const name: string = `[${key}] ${moduleInfo.packageName}: ${testName}`; + this.test(key, name, pluginHooks[key], compileFiles); } - private traverseFile(testName: string, pluginHooks: PluginTestHooks, stopAfter: PluginState): void { - let once: boolean = false; - this.configBuilder.moduleInfos.forEach((moduleInfo) => { - moduleInfo.compileFileInfos.forEach((fileInfo) => { - if (!once) { - initGlobal(fileInfo, this.configBuilder.isDebug); - once = true; - } else { - const source: string = fs.readFileSync(fileInfo.filePath).toString(); - resetContext(source); - } - this.singleFileCompile(fileInfo, moduleInfo, testName, pluginHooks, stopAfter); - }); + private compileTests(testName: string, pluginHooks: PluginTestHooks): void { + const history = MockPluginDriver.getInstance().getPluginHistory(); + history.forEach((key) => { + this.pluginTests(key, testName, pluginHooks); }); } + private async compile(plugins: Plugins[], stopAfter?: PluginState, tracing?: TraceOptions): Promise { + this.taskProcessor = new TaskProcessor(this.hashId, this.configBuilder.buildConfig); + return this.taskProcessor.invokeWorkers(plugins, stopAfter); + } + run( testName: string, plugins: Plugins[], @@ -180,12 +177,9 @@ class PluginTester { testHooks?: TestHooks ): void { if (!!options.buildConfig) { - this.configBuilder = new MockArktsConfigBuilder(options.buildConfig); + this.configBuilder = new MockArktsConfigBuilder(this.hashId, options.buildConfig); } - this.cache.clear(); - this.loadPluginDriver(plugins); - const that = this; describe(this.describe, () => { if (testHooks?.beforeAll) { @@ -197,11 +191,13 @@ class PluginTester { if (testHooks?.afterEach) { afterEach(...testHooks.afterEach); } + afterAll(() => { - destroyContext(); - destroyConfig(); + that.clear(); }); - that.traverseFile(testName, pluginHooks, options.stopAfter); + + that.resolve = that.compile(plugins, options.stopAfter); + that.compileTests(testName, pluginHooks); }); } } diff --git a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts index 69e2b23ad..f7d060b9f 100644 --- a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts @@ -26,7 +26,7 @@ export const builderLambdaNoRecheck: Plugins = { name: 'builder-lambda-no-recheck', checked(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; @@ -40,7 +40,6 @@ export const builderLambdaNoRecheck: Plugins = { }); program = programVisitor.programVisitor(program); script = program.astNode; - arkts.GlobalInfo.getInfoInstance().reset(); return script; } return script; diff --git a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts index ff018cec5..c953249a1 100644 --- a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts @@ -29,7 +29,7 @@ import { FunctionTransformer } from '../../../memo-plugins/function-transformer' export const memoNoRecheck: Plugins = { name: 'memo-no-recheck', checked(this: PluginContext): arkts.EtsScript | undefined { - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; let script = program.astNode; diff --git a/arkui-plugins/test/utils/plugins/recheck.ts b/arkui-plugins/test/utils/plugins/recheck.ts index 085d3731e..2c3559df4 100644 --- a/arkui-plugins/test/utils/plugins/recheck.ts +++ b/arkui-plugins/test/utils/plugins/recheck.ts @@ -23,7 +23,7 @@ export const recheck: Plugins = { name: 'recheck', checked(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; diff --git a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts index c564b71c7..87a7bdbd0 100644 --- a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts @@ -26,7 +26,7 @@ export const structNoRecheck: Plugins = { name: 'struct-no-recheck', checked(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; @@ -40,7 +40,6 @@ export const structNoRecheck: Plugins = { }); program = programVisitor.programVisitor(program); script = program.astNode; - arkts.GlobalInfo.getInfoInstance().reset(); return script; } return script; diff --git a/arkui-plugins/test/utils/plugins/struct-to-component.ts b/arkui-plugins/test/utils/plugins/struct-to-component.ts index 14d494c05..79c4d6c2e 100644 --- a/arkui-plugins/test/utils/plugins/struct-to-component.ts +++ b/arkui-plugins/test/utils/plugins/struct-to-component.ts @@ -26,7 +26,7 @@ export const structToComponent: Plugins = { name: 'struct-to-component', parsed(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; diff --git a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts index dec4b5296..5fbc6c3fb 100644 --- a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts @@ -26,7 +26,7 @@ export const uiNoRecheck: Plugins = { name: 'ui-no-recheck', checked(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; @@ -40,7 +40,6 @@ export const uiNoRecheck: Plugins = { }); program = programVisitor.programVisitor(program); script = program.astNode; - arkts.GlobalInfo.getInfoInstance().reset(); return script; } return script; diff --git a/arkui-plugins/test/utils/safe-types.ts b/arkui-plugins/test/utils/safe-types.ts index 728c06501..e622c5081 100644 --- a/arkui-plugins/test/utils/safe-types.ts +++ b/arkui-plugins/test/utils/safe-types.ts @@ -17,4 +17,12 @@ function isNumber(value: any): value is number { return typeof value === `number`; } -export { isNumber }; +function isString(value: any): value is string { + return typeof value === 'string'; +} + +function isBitInt(value: any): value is bigint { + return typeof value === 'bigint'; +} + +export { isNumber, isString, isBitInt }; diff --git a/arkui-plugins/test/local/@ohos.arkui.component.customComponent.d.ets b/arkui-plugins/test/utils/serializable.ts similarity index 30% rename from arkui-plugins/test/local/@ohos.arkui.component.customComponent.d.ets rename to arkui-plugins/test/utils/serializable.ts index 728c949e7..7747d78ab 100644 --- a/arkui-plugins/test/local/@ohos.arkui.component.customComponent.d.ets +++ b/arkui-plugins/test/utils/serializable.ts @@ -1,5 +1,5 @@ /* - * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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 @@ -13,45 +13,46 @@ * limitations under the License. */ -import { memo } from "@ohos.arkui.stateManagement.runtime"; -import { ComponentBuilder, CommonMethod } from "@ohos.arkui.component.common"; -import { Length, ResourceColor } from "@ohos.arkui.component.units"; - -@Retention({policy: "SOURCE"}) -export declare @interface Component {}; - -@Retention({policy: "SOURCE"}) -export declare @interface Entry { routeName: string }; - -@Retention({policy: "SOURCE"}) -export declare @interface Reusable {}; - -export declare abstract class CustomComponent, T_Options> implements - CommonMethod { - - @memo - @ComponentBuilder - static $_instantiate, S_Options>( - factory: () => S, - initializers?: S_Options, - @memo - content?: () => void - ): S; - - // Life cycle for custom component - aboutToAppear(): void; - aboutToDisappear(): void; - aboutToReuse(): void; - aboutToRecycle(): void; - - @memo - build(): void; - - // Implementation of common method - @memo - width(w: Length): this; - @memo - height(h: Length): this; - @memo - backgroundColor(color: ResourceColor): this; -} \ No newline at end of file +import { isBitInt } from './safe-types'; + +function serializable(object: T, ignoreKeys?: string[]): T { + const jsonStr = JSON.stringify(object, (key, value) => { + if (isBitInt(value)) { + return undefined; + } + if (ignoreKeys?.includes(key)) { + return undefined; + } + return value; + }); + return JSON.parse(jsonStr); +} + +type JSONObject = { [key: string]: any }; + +function concatObject(obj1: T | undefined, obj2: T | undefined): T { + const _obj1: JSONObject = obj1 ?? {}; + const _obj2: JSONObject = obj2 ?? {}; + const result: JSONObject = { ..._obj1 }; + + Object.keys(_obj2).forEach((key) => { + if (result.hasOwnProperty(key)) { + if ( + typeof _obj2[key] === 'object' && + typeof result[key] === 'object' && + _obj2[key] !== null && + result[key] !== null + ) { + result[key] = concatObject(result[key], _obj2[key]); + } else { + result[key] = _obj2[key]; + } + } else { + result[key] = _obj2[key]; + } + }); + + return result as T; +} + +export { serializable, concatObject }; diff --git a/arkui-plugins/test/utils/shared-types.ts b/arkui-plugins/test/utils/shared-types.ts new file mode 100644 index 000000000..b795e9c79 --- /dev/null +++ b/arkui-plugins/test/utils/shared-types.ts @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Plugins, PluginState } from '../../common/plugin-context'; + +export type PluginTesterId = string | `${string}:${string}`; + +export type PluginStateId = PluginState | `${PluginState}:${PluginTesterId}`; + +export interface SingleProgramContext { + scriptSnapshot?: string; + errors?: string[]; + warnings?: string[]; +} + +export interface PluginTestContext extends SingleProgramContext { + declContexts?: Record; + sourceContexts?: Record; +} + +export interface ArkTSConfigContext { + arktsConfigFile: string; + compileFiles: Map; +} + +export interface FileDependencyContext { + depInputFile: string; + fileDepsInfoJson: string; +} + +export interface CompileFileInfo { + fileName: string; + filePath: string; + dependentFiles: string[]; + abcFilePath: string; + arktsConfigFile: string; + stdLibPath: string; +} + +export interface BuildConfig { + packageName: string; + compileFiles: string[]; + loaderOutPath: string; + cachePath: string; + pandaSdkPath: string; + buildSdkPath: string; + depAnalyzerPath: string; + sourceRoots: string[]; + moduleRootPath: string; + dependentModuleList: DependentModule[]; +} + +export type ModuleType = 'har' | string; // TODO: module type unclear + +export interface DependentModule { + packageName: string; + moduleName: string; + moduleType: ModuleType; + modulePath: string; + sourceRoots: string[]; + entryFile: string; +} + +export interface JobInfo { + id: string; + isCompileAbc: boolean; // TODO: change to enum + compileFileInfo?: CompileFileInfo; + buildConfig?: BuildConfig; + plugins?: Plugins[]; + globalContextPtr?: number; + stopAfter?: PluginState; +} + +export interface TraceOptions { + externalSourceNames: string[]; +} + +export interface ProcessTaskFinishEvent { + type: 'TASK_FINISH'; + jobId: string; +} + +export interface ProcessExitEvent { + type: 'EXIT'; +} + +export interface ProcessAssignTaskEvent { + type: 'ASSIGN_TASK'; + jobInfo: JobInfo; +} + +export interface ProcessTaskCollectEvent { + type: 'TASK_COLLECT'; + jobId: string; + pluginStateId: PluginStateId; + pluginTestContext: PluginTestContext; + fileName: string; +} + +export type ProcessEvents = + | ProcessAssignTaskEvent + | ProcessTaskFinishEvent + | ProcessTaskCollectEvent + | ProcessExitEvent; + +export type ProcessEvent = { + [E in ProcessEvents as E['type']]: Omit[]; +}; diff --git a/arkui-plugins/test/utils/task-processor.ts b/arkui-plugins/test/utils/task-processor.ts new file mode 100644 index 000000000..afaa98fc9 --- /dev/null +++ b/arkui-plugins/test/utils/task-processor.ts @@ -0,0 +1,548 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as os from 'os'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as child_process from 'child_process'; +import EventEmitter from 'events'; +import type { + BuildConfig, + CompileFileInfo, + JobInfo, + PluginTestContext, + ProcessEvent, + TraceOptions, +} from './shared-types'; +import { mockBuildConfig } from './artkts-config'; +import { + DECL_ETS_SUFFIX, + ensurePathExists, + getFileName, + MOCK_DEP_INPUT_FILE_NAME, + MOCK_FILE_DEP_FILE_NAME, +} from './path-config'; +import { ArkTSConfigContextCache, FileDependencyContextCache, PluginTestContextCache } from './cache'; +import { HashGenerator } from './hash-generator'; +import { createGlobalConfig, createGlobalContextPtr, destroyGlobalConfig, destroyGlobalContextPtr } from './global'; +import { Plugins, PluginState } from '../../common/plugin-context'; +import { concatObject, serializable } from './serializable'; +import { compileAbc, compileExternalProgram } from './compile'; + +interface Job { + id: string; + isDeclFile: boolean; + isInCycle?: boolean; + fileList: string[]; + dependencies: string[]; + dependants: string[]; + isAbcJob: boolean; +} + +interface Queues { + externalProgramQueue: Job[]; + abcQueue: Job[]; +} + +interface FileDepsInfo { + dependencies: Record; + dependants: Record; +} + +interface WorkerInfo { + isIdle: boolean; +} + +function getDepAnalyzerCmd( + depAnalyzerPath: string, + depInputFile: string, + entryFiles: Set, + outputFile: string, + arktsConfigFile: string +): string[] { + const depAnalyzerCmd: string[] = [`"${depAnalyzerPath}"`]; + + let depInputContent = ''; + entryFiles.forEach((file: string) => { + depInputContent += file + os.EOL; + }); + fs.writeFileSync(depInputFile, depInputContent); + + depAnalyzerCmd.push(`@"${depInputFile}"`); + depAnalyzerCmd.push(`--output=${outputFile}`); + depAnalyzerCmd.push(`--arktsconfig=${arktsConfigFile}`); + + return depAnalyzerCmd; +} + +function dfs(node: string, visited: Set, adjacencyList: Record, order: string[]) { + visited.add(node); + for (const neighbor of adjacencyList[node]) { + if (!visited.has(neighbor)) { + dfs(neighbor, visited, adjacencyList, order); + } + } + order.push(node); +} + +function reverseDfs( + node: string, + component: Set, + visited: Set, + reverseAdjacencyList: Record +) { + visited.add(node); + component.add(node); + for (const neighbor of reverseAdjacencyList[node]) { + if (!visited.has(neighbor)) { + reverseDfs(neighbor, component, visited, reverseAdjacencyList); + } + } +} + +function findStronglyConnectedComponents(graph: FileDepsInfo): Map> { + const adjacencyList: Record = {}; + const reverseAdjacencyList: Record = {}; + const allNodes = new Set(); + for (const node in graph.dependencies) { + allNodes.add(node); + graph.dependencies[node].forEach((dep) => allNodes.add(dep)); + } + for (const node in graph.dependants) { + allNodes.add(node); + graph.dependants[node].forEach((dep) => allNodes.add(dep)); + } + Array.from(allNodes).forEach((node) => { + adjacencyList[node] = graph.dependencies[node] || []; + reverseAdjacencyList[node] = graph.dependants[node] || []; + }); + const visited = new Set(); + const order: string[] = []; + Array.from(allNodes).forEach((node) => { + if (!visited.has(node)) { + dfs(node, visited, adjacencyList, order); + } + }); + visited.clear(); + const components = new Map>(); + for (let i = order.length - 1; i >= 0; i--) { + const node = order[i]; + if (!visited.has(node)) { + const component = new Set(); + reverseDfs(node, component, visited, reverseAdjacencyList); + if (component.size > 1) { + const sortedFiles = Array.from(component).sort(); + const hashKey = HashGenerator.getInstance().staticSha1Id(sortedFiles.join('|'), 13); + components.set(hashKey, component); + } + } + } + return components; +} + +function getJobDependencies(fileDeps: string[], cycleFiles: Map): Set { + const depJobList: Set = new Set(); + fileDeps.forEach((file) => { + if (!cycleFiles.has(file)) { + depJobList.add('0' + file); + } else { + cycleFiles.get(file)?.forEach((f) => { + depJobList.add(f); + }); + } + }); + + return depJobList; +} + +function getJobDependants(fileDeps: string[], cycleFiles: Map): Set { + let depJobList: Set = new Set(); + fileDeps.forEach((file) => { + if (!file.endsWith(DECL_ETS_SUFFIX)) { + depJobList.add('1' + file); + } + if (cycleFiles.has(file)) { + cycleFiles.get(file)?.forEach((f) => { + depJobList.add(f); + }); + } else { + depJobList.add('0' + file); + } + }); + + return depJobList; +} + +function insertJobDependantsButSelf(jobMap: Record, id: string, dependants: Set): Set { + jobMap[id].dependants.forEach((dep) => { + dependants.add(dep); + }); + if (dependants.has(id)) { + dependants.delete(id); + } + return dependants; +} + +function createExternalProgramJob(id: string, fileList: string[], dependencies: Set, isInCycle?: boolean): Job { + return { + id, + fileList, + isDeclFile: true, + isInCycle, + isAbcJob: false, + dependencies: Array.from(dependencies), + dependants: [], + }; +} + +function createAbcJob(id: string, fileList: string[], dependencies: Set, isInCycle?: boolean): Job { + return { + id, + isDeclFile: false, + isInCycle, + isAbcJob: true, + fileList, + dependencies: Array.from(dependencies), + dependants: [], + }; +} + +function addJobToQueues(job: Job, queues: Queues): void { + if (queues.externalProgramQueue.some((j) => j.id === job.id) || queues.abcQueue.some((j) => j.id === job.id)) { + return; + } + if (!job.isAbcJob) { + queues.externalProgramQueue.push(job); + } else { + queues.abcQueue.push(job); + } +} + +class TaskProcessor { + hashId: string; + buildConfig: BuildConfig; + tracing: TraceOptions; + cacheDir: string; + entryFiles: Set; + depAnalyzerPath: string; + depInputFile: string; + fileDepsInfoJson: string; + arktsConfigFile: string; + compileFiles: Map; + jobMap: Record; + jobQueues: Queues; + + readonly emitter: EventEmitter = new EventEmitter(); + private worker!: WorkerInfo; + + constructor(hashId: string, buildConfig?: BuildConfig, tracing?: TraceOptions) { + this.hashId = hashId; + this.tracing = tracing ?? { externalSourceNames: [] }; + + const _buildConfig: BuildConfig = buildConfig ?? mockBuildConfig(); + this.buildConfig = _buildConfig; + this.cacheDir = _buildConfig.cachePath; + this.entryFiles = new Set(_buildConfig.compileFiles as string[]); + this.depAnalyzerPath = _buildConfig.depAnalyzerPath; + this.depInputFile = path.resolve(_buildConfig.cachePath, this.hashId, MOCK_DEP_INPUT_FILE_NAME); + this.fileDepsInfoJson = path.resolve(_buildConfig.cachePath, this.hashId, MOCK_FILE_DEP_FILE_NAME); + this.arktsConfigFile = this.getArktsConfigFile(); + this.compileFiles = this.getCompileFiles(); + + this.generateFileDependencies(); + this.cacheFileDependencies(); + this.jobMap = this.collectCompileJobs(); + this.jobQueues = this.initCompileQueues(); + } + + private cacheFileDependencies(): void { + const depInputFile: string = this.arktsConfigFile; + const fileDepsInfoJson: string = this.fileDepsInfoJson; + FileDependencyContextCache.getInstance().set(this.hashId, { depInputFile, fileDepsInfoJson }); + } + + private getArktsConfigFile(): string { + const arktsConfigFile = ArkTSConfigContextCache.getInstance().get(this.hashId)?.arktsConfigFile; + if (!arktsConfigFile) { + const err = `[${this.hashId}] TaskProcessor cannot get arktsConfigFile`; + console.error(err); + throw new Error(err); + } + return arktsConfigFile; + } + + private getCompileFiles(): Map { + const compileFiles = ArkTSConfigContextCache.getInstance().get(this.hashId)?.compileFiles; + if (!compileFiles) { + const err = `[${this.hashId}] TaskProcessor cannot get compileFiles`; + console.error(err); + throw new Error(err); + } + return compileFiles; + } + + private generateFileDependencies(): void { + ensurePathExists(this.depInputFile); + ensurePathExists(this.fileDepsInfoJson); + const depAnalyzerCmd: string[] = getDepAnalyzerCmd( + this.depAnalyzerPath, + this.depInputFile, + this.entryFiles, + this.fileDepsInfoJson, + this.arktsConfigFile + ); + const depAnalyzerCmdStr: string = depAnalyzerCmd.join(' '); + try { + child_process.execSync(depAnalyzerCmdStr).toString(); + } catch (error) { + const err = `[${this.hashId}] TaskProcessor generateFileDependencies failed: ${error}`; + console.error(err); + throw new Error(err); + } + } + + private collectJobsInDependants( + jobMap: Record, + cycleFiles: Map, + dependantMap: [string, string[]] + ): void { + const [key, value] = dependantMap; + const dependants = getJobDependants(value, cycleFiles); + if (cycleFiles.has(key)) { + const externalProgramJobIds = cycleFiles.get(key)!; + externalProgramJobIds.forEach((id) => { + jobMap[id].dependants = Array.from(insertJobDependantsButSelf(jobMap, id, dependants)); + }); + } else { + const id = '0' + key; + jobMap[id].dependants = Array.from(insertJobDependantsButSelf(jobMap, id, dependants)); + } + } + + private collectJobsInDependencies( + jobMap: Record, + cycleFiles: Map, + cycleGroups: Map>, + dependencyMap: [string, string[]] + ): void { + const [key, value] = dependencyMap; + const dependencies = getJobDependencies(value, cycleFiles); + // Create generate abc job + if (!key.endsWith(DECL_ETS_SUFFIX)) { + const abcJobId: string = '1' + key; + jobMap[abcJobId] = createAbcJob(abcJobId, [key], dependencies, cycleFiles.has(key)); + } + // Create cache external job + if (cycleFiles.has(key)) { + const externalProgramJobIds = cycleFiles.get(key)!; + externalProgramJobIds.forEach((id) => { + const fileList: string[] = Array.from(cycleGroups.get(id)!); + if (dependencies.has(id)) { + dependencies.delete(id); + } + jobMap[id] = createExternalProgramJob(id, fileList, dependencies, true); + }); + } else { + const id = '0' + key; + const fileList: string[] = [key]; + if (dependencies.has(id)) { + dependencies.delete(id); + } + jobMap[id] = createExternalProgramJob(id, fileList, dependencies); + } + // register compileFiles for declaration files + if (key.endsWith(DECL_ETS_SUFFIX)) { + const fileInfo: CompileFileInfo = { + filePath: key, + dependentFiles: [], + abcFilePath: '', + arktsConfigFile: this.arktsConfigFile, + fileName: getFileName(key), + stdLibPath: '', + }; + + if (!this.compileFiles.has(key)) { + this.compileFiles.set(key, fileInfo); + } + } + } + + private collectCompileJobs(): Record { + const data = fs.readFileSync(this.fileDepsInfoJson, 'utf-8'); + if (data.length === 0) { + const err = `[${this.hashId}] TaskProcessor cannot read fileDepsInfoJson`; + console.error(err); + throw new Error(err); + } + const fileDepsInfo: FileDepsInfo = JSON.parse(data) as FileDepsInfo; + Object.keys(fileDepsInfo.dependants).forEach((file) => { + if (!(file in fileDepsInfo.dependencies)) { + fileDepsInfo.dependencies[file] = []; + } + }); + const cycleGroups = findStronglyConnectedComponents(fileDepsInfo); + const cycleFiles: Map = new Map(); + cycleGroups.forEach((value: Set, key: string) => { + value.forEach((file) => { + cycleFiles.set(file, [key]); + }); + }); + const jobMap: Record = {}; + Object.entries(fileDepsInfo.dependencies).forEach((dependencyMap) => { + this.collectJobsInDependencies(jobMap, cycleFiles, cycleGroups, dependencyMap); + }); + Object.entries(fileDepsInfo.dependants).forEach((dependantMap) => { + this.collectJobsInDependants(jobMap, cycleFiles, dependantMap); + }); + return jobMap; + } + + private initCompileQueues(): Queues { + const queues: Queues = { externalProgramQueue: [], abcQueue: [] }; + Object.values(this.jobMap).forEach((job) => { + if (job.dependencies.length === 0) { + addJobToQueues(job, queues); + } + }); + return queues; + } + + private assignTaskToIdleWorker( + processingJobs: Set, + globalContextPtr: number, + plugins: Plugins[], + stopAfter?: PluginState + ) { + let job: Job | undefined; + let jobInfo: JobInfo | undefined; + if (this.jobQueues.externalProgramQueue.length > 0) { + job = this.jobQueues.externalProgramQueue.shift()!; + jobInfo = { + id: job.id, + isCompileAbc: false, + }; + } else if (this.jobQueues.abcQueue.length > 0) { + job = this.jobQueues.abcQueue.shift()!; + jobInfo = { + id: job.id, + isCompileAbc: true, + }; + } + + if (!!job && !!jobInfo) { + processingJobs.add(job.id); + jobInfo.compileFileInfo = this.compileFiles.get(job.fileList[0]); + jobInfo.buildConfig = serializable(this.buildConfig); + jobInfo.plugins = plugins; + jobInfo.globalContextPtr = globalContextPtr; + jobInfo.stopAfter = stopAfter; + + this.worker.isIdle = false; + this.emitter.emit('ASSIGN_TASK', { jobInfo }); + } + } + + private checkAllTasksDone(): boolean { + return this.jobQueues.externalProgramQueue.length === 0 && this.worker.isIdle; + } + + private addDependantJobToQueues(jobId: string): void { + const completedJob = this.jobMap[jobId]; + completedJob.dependants.forEach((depJobId) => { + const depJob = this.jobMap[depJobId]; + const depIndex = depJob.dependencies.indexOf(jobId); + if (depIndex !== -1) { + depJob.dependencies.splice(depIndex, 1); + if (depJob.dependencies.length === 0) { + addJobToQueues(depJob, this.jobQueues); + } + } + }); + } + + private subscribe() { + this.emitter.on('ASSIGN_TASK', (msg) => { + const job = msg.jobInfo; + if (job.isCompileAbc) { + compileAbc(this.emitter, job, this.tracing); + } else { + compileExternalProgram(this.emitter, job, this.tracing); + } + this.emitter.emit('TASK_FINISH', { jobId: job.id }); + }); + this.emitter.on('EXIT', () => { + this.worker.isIdle = true; + console.log(`worker exiting...`); + }); + this.emitter.on('TASK_COLLECT', (msg) => { + const jobId = msg.jobId; + const job = this.jobMap[jobId]; + const sourceType = job.isAbcJob ? 'abc' : 'external'; + const pluginStateId = msg.pluginStateId; + const fileName = msg.fileName; + const pluginTestContext = msg.pluginTestContext as PluginTestContext; + const key = `${this.hashId}:${sourceType}:${pluginStateId}:${fileName}`; + let currentPluginTestContext; + if (PluginTestContextCache.getInstance().has(key)) { + const oldContext = PluginTestContextCache.getInstance().get(key)!; + currentPluginTestContext = concatObject(oldContext, pluginTestContext); + } else { + currentPluginTestContext = pluginTestContext; + } + PluginTestContextCache.getInstance().set(key, currentPluginTestContext); + }); + } + + async invokeWorkers(plugins: Plugins[], stopAfter?: PluginState): Promise { + const processingJobs = new Set(); + return new Promise((resolve) => { + const files: string[] = []; + Object.values(this.jobMap).forEach((job) => { + for (let i = 0; i < job.fileList.length; i++) { + files.push(job.fileList[i]); + } + }); + const fileInfo: CompileFileInfo = this.compileFiles.values().next().value!; + const config = createGlobalConfig(fileInfo); + const globalContextPtr = createGlobalContextPtr(config, files); + this.subscribe(); + this.emitter.on('TASK_FINISH', (msg) => { + this.worker.isIdle = true; + const jobId = msg.jobId; + processingJobs.delete(jobId); + this.addDependantJobToQueues(jobId); + const hasRemainingTask = + this.jobQueues.externalProgramQueue.length > 0 || this.jobQueues.abcQueue.length > 0; + if (hasRemainingTask) { + this.assignTaskToIdleWorker(processingJobs, globalContextPtr, plugins, stopAfter); + } else if (this.checkAllTasksDone()) { + console.log('All tasks completed. Exiting...'); + this.emitter.emit('EXIT'); + destroyGlobalContextPtr(globalContextPtr); + destroyGlobalConfig(config); + resolve(); + } + }); + this.worker = { isIdle: true }; + this.assignTaskToIdleWorker(processingJobs, globalContextPtr, plugins, stopAfter); + }); + } + + clear(): void { + FileDependencyContextCache.getInstance().delete(this.hashId); + } +} + +export { TaskProcessor }; diff --git a/arkui-plugins/tsconfig.json b/arkui-plugins/tsconfig.json index 32677ce44..c29a9c01d 100644 --- a/arkui-plugins/tsconfig.json +++ b/arkui-plugins/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { - "target": "es2018", + "target": "esnext", "lib": ["ESNext", "ESNext.WeakRef", "DOM"], - "module": "CommonJS", + "module": "esnext", "rootDir": ".", "baseUrl": ".", "outDir": "./lib", @@ -16,7 +16,8 @@ "strict": true, "skipLibCheck": true, "removeComments": false, - "isolatedModules": true + "isolatedModules": true, + "esModuleInterop": true }, "include": [ "./common/**/*.ts", diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts index 5e4dc8331..7a821bd74 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts @@ -16,15 +16,25 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../../common/abstract-visitor'; import { isBuilderLambda, isBuilderLambdaMethodDecl } from './utils'; import { factory } from './factory'; +import { ImportCollector } from '../import-collector'; +import { ProjectConfig } from '../../common/plugin-context'; export class BuilderLambdaTransformer extends AbstractVisitor { + projectConfig: ProjectConfig | undefined; + + constructor(projectConfig: ProjectConfig | undefined) { + super(); + this.projectConfig = projectConfig; + } + reset(): void { super.reset(); + ImportCollector.getInstance().reset(); } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { if (arkts.isCallExpression(beforeChildren) && isBuilderLambda(beforeChildren)) { - const lambda = factory.transformBuilderLambda(beforeChildren); + const lambda = factory.transformBuilderLambda(beforeChildren, this.projectConfig); return this.visitEachChild(lambda); } if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren)) { @@ -32,6 +42,9 @@ export class BuilderLambdaTransformer extends AbstractVisitor { return this.visitEachChild(lambda); } const node = this.visitEachChild(beforeChildren); + if (arkts.isEtsScript(node) && ImportCollector.getInstance().importInfos.length > 0) { + ImportCollector.getInstance().insertCurrentImports(this.program); + } return node; } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 245659d46..b3eaa5870 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -14,14 +14,22 @@ */ import * as arkts from '@koalaui/libarkts'; -import { BuilderLambdaNames } from '../utils'; +import { + addMemoAnnotation, + BuilderLambdaNames, + CustomComponentNames, + findCanAddMemoFromParamExpression, + findImportSource, + getCustomComponentOptionsName, + isCustomComponentAnnotation, +} from '../utils'; import { annotation, backingField, filterDefined, removeAnnotationByName } from '../../common/arkts-utils'; import { BuilderLambdaDeclInfo, builderLambdaFunctionName, builderLambdaMethodDeclType, - builderLambdaTypeName, callIsGoodForBuilderLambda, + collectComponentAttributeImport, findBuilderLambdaDecl, findBuilderLambdaDeclInfo, isBuilderLambda, @@ -35,29 +43,73 @@ import { InstanceCallInfo, isStyleChainedCall, isStyleWithReceiverCall, + builderLambdaType, } from './utils'; -import { DecoratorNames } from '../property-translators/utils'; +import { DecoratorIntrinsicNames, DecoratorNames, isDecoratorIntrinsicAnnotation } from '../property-translators/utils'; import { factory as PropertyFactory } from '../property-translators/factory'; import { ProjectConfig } from '../../common/plugin-context'; +import { ImportCollector } from '../import-collector'; export class factory { - /* - * update @ComponentBuilder decorated method. + /** + * generate `reuseKey?: string` in `@ComponentBuilder` $_instantiate + */ + static createReusableKeyArgForCustomComponent(): arkts.ETSParameterExpression { + return arkts.factory + .createParameterDeclaration( + arkts.factory.createIdentifier( + 'reuseKey', + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('string')) + ) + ), + undefined + ) + .setOptional(true); + } + + /** + * generate `packageInfo: string` in `@ComponentBuilder` XComponent + */ + static createPackageInfoArgForXComponent(): arkts.ETSParameterExpression { + return arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + 'packageInfo', + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('string')) + ) + ), + undefined + ); + } + + /** + * update `@ComponentBuilder` decorated method. */ static updateBuilderLambdaMethodDecl( node: arkts.MethodDefinition, - styleArg: arkts.ETSParameterExpression, + prefixArgs: arkts.ETSParameterExpression[], newAnno: arkts.AnnotationUsage[], newName: string | undefined ): arkts.MethodDefinition { const func: arkts.ScriptFunction = node.scriptFunction; + let newParams: arkts.Expression[]; + if (func.params.length > 0) { + newParams = [...prefixArgs, ...func.params.slice(0, func.params.length - 1)]; + if (node.name.name === BuilderLambdaNames.ORIGIN_METHOD_NAME) { + newParams.push(this.createReusableKeyArgForCustomComponent()); + } + newParams.push(func.params.at(func.params.length - 1)!); + } else { + newParams = prefixArgs; + } const updateFunc = arkts.factory .updateScriptFunction( func, func.body, arkts.FunctionSignature.createFunctionSignature( func.typeParams, - [styleArg, ...func.params], + newParams, arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), false ), @@ -70,9 +122,9 @@ export class factory { node, node.kind, arkts.factory.updateIdentifier(node.name, newName ?? node.name.name), - arkts.factory.createFunctionExpression(updateFunc), + updateFunc, node.modifiers, - false // TODO: how do I get it? + false ); } @@ -85,7 +137,7 @@ export class factory { return [...call.arguments]; } const type: arkts.AstNode | undefined = arkts.isEtsParameterExpression(decl.scriptFunction.params[0]) - ? decl.scriptFunction.params[0].type + ? decl.scriptFunction.params[0].type?.clone() : undefined; if ( type && @@ -115,7 +167,11 @@ export class factory { /* * create style instance call, e.g. `instance.margin(10)`. */ - static createStyleLambdaBody(lambdaBody: arkts.AstNode, callInfo: InstanceCallInfo, projectConfig: ProjectConfig | undefined): arkts.CallExpression { + static createStyleLambdaBody( + lambdaBody: arkts.AstNode, + callInfo: InstanceCallInfo, + projectConfig: ProjectConfig | undefined + ): arkts.CallExpression { if (!callInfo.isReceiver) { const newArgs: arkts.Expression[] = factory.getTransformedStyle(callInfo.call); return arkts.factory.createCallExpression( @@ -166,7 +222,9 @@ export class factory { if (!lambdaBody) { return arkts.factory.createUndefinedLiteral(); } + collectComponentAttributeImport(typeNode); const safeType: arkts.TypeNode | undefined = isSafeType(typeNode) ? typeNode : undefined; + const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, safeType), undefined @@ -228,7 +286,9 @@ export class factory { undefined ); } - parameter.annotations = [annotation('memo')]; + if (findCanAddMemoFromParamExpression(parameter)) { + addMemoAnnotation(parameter); + } return parameter; } @@ -236,15 +296,18 @@ export class factory { * If a builder lambda's argument is an arrow function, * then transform any builder lambda in the function body. */ - static processArgArrowFunction(arg: arkts.ArrowFunctionExpression, projectConfig: ProjectConfig | undefined): arkts.ArrowFunctionExpression { + static processArgArrowFunction( + arg: arkts.ArrowFunctionExpression, + projectConfig: ProjectConfig | undefined + ): arkts.ArrowFunctionExpression { const func: arkts.ScriptFunction = arg.scriptFunction; const updateFunc = arkts.factory.updateScriptFunction( func, !!func.body && arkts.isBlockStatement(func.body) ? arkts.factory.updateBlock( - func.body, - func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st, projectConfig)) - ) + func.body, + func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st, projectConfig)) + ) : undefined, arkts.FunctionSignature.createFunctionSignature( func.typeParams, @@ -268,16 +331,10 @@ export class factory { } else if (arkts.isObjectExpression(arg)) { expr = arg; } - if (!expr) { return arg; } - - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); - const properties = expr.properties as arkts.Property[]; - properties.forEach((prop, index) => { - this.updateParameterPassingInLinkedProperties(prop, index, currentStructInfo, properties); - }); + const properties = (expr.properties as arkts.Property[]).map((p) => factory.updatePropertiesInOptions(p)); const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( expr, arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, @@ -290,49 +347,32 @@ export class factory { return updatedExpr as T; } - /** - * update any `@Link` parameter passing to the custom-component child. - */ - static updateParameterPassingInLinkedProperties( - prop: arkts.Property, - index: number, - currentStructInfo: arkts.StructInfo, - properties: arkts.Property[] - ): void { - const decl = prop.key ? arkts.getDecl(prop.key) : undefined; - if (decl && arkts.isMethodDefinition(decl)) { - const type: arkts.TypeNode | undefined = decl.scriptFunction.returnTypeAnnotation; - if ( - type && - hasBindableProperty(type, BindableDecl.BINDABLE) && - arkts.isProperty(prop) && - prop.value && - isDoubleDollarCall(prop.value) - ) { - properties[index] = factory.updateBindableProperty(prop); - } + static updatePropertiesInOptions(prop: arkts.Property): arkts.Property { + let decl: arkts.AstNode | undefined; + if (!prop.key || !prop.value || !(decl = arkts.getDecl(prop.key)) || !arkts.isMethodDefinition(decl)) { + return prop; } - if ( - !!prop.key && - !!prop.value && + const returnType: arkts.TypeNode | undefined = decl.scriptFunction.returnTypeAnnotation; + const isBindable: boolean = !!returnType && hasBindableProperty(returnType, BindableDecl.BINDABLE); + const isLinkIntrinsic: boolean = decl.scriptFunction.annotations.some((anno) => + isDecoratorIntrinsicAnnotation(anno, DecoratorIntrinsicNames.LINK) + ); + if (isBindable && isDoubleDollarCall(prop.value)) { + return factory.updateBindableProperty(prop); + } else if ( + isLinkIntrinsic && arkts.isIdentifier(prop.key) && arkts.isMemberExpression(prop.value) && arkts.isThisExpression(prop.value.object) && arkts.isIdentifier(prop.value.property) ) { - const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; - if ( - structVariableMetadata && - structVariableMetadata.properties.length && - structVariableMetadata.properties.includes(DecoratorNames.LINK) - ) { - properties[index] = arkts.Property.updateProperty( - prop, - arkts.factory.createIdentifier(backingField(prop.key.name)), - this.updateBackingMember(prop.value, prop.value.property.name) - ); - } + return arkts.Property.updateProperty( + prop, + arkts.factory.createIdentifier(backingField(prop.key.name)), + factory.updateBackingMember(prop.value, prop.value.property.name) + ); } + return prop; } /** @@ -343,9 +383,10 @@ export class factory { arg: arkts.Expression | undefined, projectConfig: ProjectConfig | undefined, typeName?: string, - ): arkts.AstNode { + fallback?: arkts.AstNode + ): arkts.AstNode | undefined { if (!arg) { - return arkts.factory.createUndefinedLiteral(); + return fallback; } if (arkts.isArrowFunctionExpression(arg)) { return this.processArgArrowFunction(arg, projectConfig); @@ -366,33 +407,62 @@ export class factory { declInfo: BuilderLambdaDeclInfo, projectConfig: ProjectConfig | undefined ): (arkts.AstNode | undefined)[] { - const { params, returnType } = declInfo; - const typeName: string | undefined = builderLambdaTypeName(leaf); + const { isFunctionCall, params, returnType } = declInfo; + const type: arkts.Identifier | undefined = builderLambdaType(leaf); + let isReusable: boolean | undefined; + let reuseId: arkts.StringLiteral | undefined; + if (!isFunctionCall && !!type) { + const customComponentDecl = arkts.getDecl(type); + isReusable = + !!customComponentDecl && + arkts.isClassDefinition(customComponentDecl) && + customComponentDecl.annotations.some((anno) => + isCustomComponentAnnotation(anno, CustomComponentNames.RESUABLE_ANNOTATION) + ); + reuseId = isReusable ? arkts.factory.createStringLiteral(type.name) : undefined; + } const args: (arkts.AstNode | undefined)[] = [this.createStyleArgInBuilderLambda(lambdaBody, returnType)]; let index = 0; while (index < params.length) { - args.push(this.createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), projectConfig, typeName)); - index++; - } - const isReusable: boolean = typeName - ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable : false; - if (isReusable) { - args.splice(-1, 1, arkts.factory.createStringLiteral(typeName!)); - } - else if (typeName === 'XComponent') { - let packageInfo: string = ''; - if (projectConfig?.bundleName && projectConfig?.moduleName) { - packageInfo = projectConfig?.bundleName + '/' + projectConfig?.moduleName; + if (isReusable && index === params.length - 1) { + args.push(this.createOrUpdateArgInBuilderLambda(undefined, undefined, undefined, reuseId)); + args.push( + this.createOrUpdateArgInBuilderLambda( + leaf.arguments.at(index), + projectConfig, + type?.name, + arkts.factory.createUndefinedLiteral() + ) + ); + } else if (type?.name === 'XComponent' && index === params.length - 1) { + let packageInfo: string = ''; + if (projectConfig?.bundleName && projectConfig?.moduleName) { + packageInfo = projectConfig?.bundleName + '/' + projectConfig?.moduleName; + } + const packageInfoNode = arkts.factory.createStringLiteral(packageInfo); + args.push( + this.createOrUpdateArgInBuilderLambda( + leaf.arguments.at(index), + projectConfig, + type?.name, + packageInfoNode + ) + ); + } else { + args.push(this.createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), projectConfig, type?.name)); } - args.splice(args.length - 1, 0, arkts.factory.createStringLiteral(packageInfo)); + index++; } - return args; + return filterDefined(args); } /** * update if-else in trailing lambda contents in a builder lambda call. */ - static updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, projectConfig: ProjectConfig | undefined): arkts.AstNode { + static updateIfElseContentBodyInBuilderLambda( + statement: arkts.AstNode, + projectConfig: ProjectConfig | undefined + ): arkts.AstNode { if (arkts.isIfStatement(statement)) { const alternate = !!statement.alternate ? this.updateIfElseContentBodyInBuilderLambda(statement.alternate, projectConfig) @@ -412,7 +482,10 @@ export class factory { /** * update trailing lambda contents in a builder lambda call. */ - static updateContentBodyInBuilderLambda(statement: arkts.Statement, projectConfig: ProjectConfig | undefined): arkts.Statement { + static updateContentBodyInBuilderLambda( + statement: arkts.Statement, + projectConfig: ProjectConfig | undefined + ): arkts.Statement { if ( arkts.isExpressionStatement(statement) && arkts.isCallExpression(statement.expression) && @@ -460,18 +533,25 @@ export class factory { /** * transform `@ComponentBuilder` in declared methods. */ - static transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.MethodDefinition { + static transformBuilderLambdaMethodDecl( + node: arkts.MethodDefinition, + externalSourceName?: string + ): arkts.MethodDefinition { const func: arkts.ScriptFunction = node.scriptFunction; const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); - const styleArg: arkts.ETSParameterExpression = this.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall); + const prefixArgs: arkts.ETSParameterExpression[] = []; + prefixArgs.push(this.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall)); + if (externalSourceName === 'arkui.component.xcomponent' && node.name.name === 'XComponent') { + prefixArgs.push(this.createPackageInfoArgForXComponent()); + } const newOverloads: arkts.MethodDefinition[] = node.overloads.map((method) => factory.transformBuilderLambdaMethodDecl(method) ); return this.updateBuilderLambdaMethodDecl( node, - styleArg, + prefixArgs, removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), replaceBuilderLambdaDeclMethodName(node.name.name) ).setOverloads(newOverloads); @@ -561,7 +641,12 @@ export class factory { }); } - const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, projectConfig); + const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda( + leaf, + lambdaBody!, + declInfo, + projectConfig + ); return arkts.factory.updateCallExpression(node, replace, leaf.typeArguments, filterDefined(args)); } @@ -638,9 +723,13 @@ export class factory { * generate `Bindable`. */ static createBindableType(valueType: arkts.TypeNode): arkts.ETSTypeReference { + const transformedKey = BindableDecl.BINDABLE; + const source = findImportSource(transformedKey); + ImportCollector.getInstance().collectSource(transformedKey, source); + ImportCollector.getInstance().collectImport(transformedKey); return arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(BindableDecl.BINDABLE), + arkts.factory.createIdentifier(transformedKey), arkts.factory.createTSTypeParameterInstantiation([valueType.clone()]) ) ); diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index f7cd7c6de..4b9f4b9ba 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -16,6 +16,9 @@ import * as arkts from '@koalaui/libarkts'; import { isAnnotation } from '../../common/arkts-utils'; import { BuilderLambdaNames, Dollars } from '../utils'; +import { ImportCollector } from '../import-collector'; +import { DeclarationCollector } from '../../common/declaration-collector'; +import { ARKUI_COMPONENT_IMPORT_NAME } from '../../common/predefines'; export type BuilderLambdaDeclInfo = { isFunctionCall: boolean; // isFunctionCall means it is from $_instantiate. @@ -54,12 +57,7 @@ export function builderLambdaArgumentName(annotation: arkts.AnnotationUsage): st return property.value.str; } -/** - * Determine whether it is a custom component. - * - * @param node class declaration node - */ -export function isBuilderLambda(node: arkts.AstNode, isExternal?: boolean): boolean { +export function isBuilderLambda(node: arkts.AstNode): boolean { const builderLambdaCall: arkts.AstNode | undefined = getDeclForBuilderLambda(node); if (!builderLambdaCall) { return arkts.isCallExpression(node) && node.arguments.length > 0 && isBuilderLambda(node.arguments[0]); @@ -131,15 +129,12 @@ export function replaceBuilderLambdaDeclMethodName(name: string | undefined): st return undefined; } -export function isBuilderLambdaMethodDecl(node: arkts.AstNode, isExternal?: boolean): boolean { +export function isBuilderLambdaMethodDecl(node: arkts.AstNode): boolean { const builderLambdaMethodDecl: arkts.AstNode | undefined = getDeclForBuilderLambdaMethodDecl(node); return !!builderLambdaMethodDecl; } -export function getDeclForBuilderLambdaMethodDecl( - node: arkts.AstNode, - isExternal?: boolean -): arkts.AstNode | undefined { +export function getDeclForBuilderLambdaMethodDecl(node: arkts.AstNode): arkts.AstNode | undefined { if (!node || !arkts.isMethodDefinition(node)) { return undefined; } @@ -154,7 +149,7 @@ export function getDeclForBuilderLambdaMethodDecl( return undefined; } -export function getDeclForBuilderLambda(node: arkts.AstNode, isExternal?: boolean): arkts.AstNode | undefined { +export function getDeclForBuilderLambda(node: arkts.AstNode): arkts.AstNode | undefined { if (!node || !arkts.isCallExpression(node)) { return undefined; } @@ -278,6 +273,7 @@ export function findBuilderLambdaDecl(node: arkts.CallExpression | arkts.Identif if (!decl) { return undefined; } + DeclarationCollector.getInstance().collect(decl); return decl; } @@ -348,17 +344,17 @@ export function builderLambdaMethodDeclType(method: arkts.MethodDefinition): ark return method.scriptFunction.returnTypeAnnotation; } -export function builderLambdaTypeName(leaf: arkts.CallExpression): string | undefined { +export function builderLambdaType(leaf: arkts.CallExpression): arkts.Identifier | undefined { if (!callIsGoodForBuilderLambda(leaf)) { return undefined; } const node = leaf.expression; - let name: string | undefined; + let name: arkts.Identifier | undefined; if (arkts.isIdentifier(node)) { - name = node.name; + name = node; } if (arkts.isMemberExpression(node) && arkts.isIdentifier(node.object)) { - name = node.object.name; + name = node.object; } return name; } @@ -411,7 +407,7 @@ export function hasBindableProperty(type: arkts.AstNode, bindableDecl: BindableD * * @param value expression node */ -export function isDoubleDollarCall(value: arkts.Expression): boolean { +export function isDoubleDollarCall(value: arkts.Expression): value is arkts.CallExpression { if ( arkts.isCallExpression(value) && value.expression && @@ -475,3 +471,24 @@ export function getElementTypeFromArray(arrayType: arkts.TypeNode): arkts.TypeNo } return undefined; } + +export function collectComponentAttributeImport(type: arkts.TypeNode | undefined): void { + if ( + !type || + !arkts.isETSTypeReference(type) || + !type.part || + !type.part.name || + !arkts.isIdentifier(type.part.name) + ) { + return; + } + + const regex: RegExp = /(?\w+Attribute)(?:<.*>)?$/; + const name: string = type.part.name.name; + const match: RegExpExecArray | null = regex.exec(name); + const attributeName: string | undefined = match?.groups?.source; + if (!!attributeName) { + ImportCollector.getInstance().collectSource(attributeName, ARKUI_COMPONENT_IMPORT_NAME); + ImportCollector.getInstance().collectImport(attributeName); + } +} diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 4bd3d809e..890414658 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -17,68 +17,67 @@ import * as arkts from '@koalaui/libarkts'; import { ProjectConfig } from '../common/plugin-context'; import { factory as structFactory } from './struct-translators/factory'; import { factory as builderLambdaFactory } from './builder-lambda-translators/factory'; -import { factory as uiFactory } from './ui-factory'; import { factory as entryFactory } from './entry-translators/factory'; import { AbstractVisitor } from '../common/abstract-visitor'; -import { annotation, collect, filterDefined } from '../common/arkts-utils'; import { - CustomComponentNames, - getCustomComponentOptionsName, - getTypeNameFromTypeParameter, - getTypeParamsFromClassDecl, - getGettersFromClassDecl, addMemoAnnotation, + collectCustomComponentScopeInfo, + CustomComponentNames, + isCustomComponentClass, } from './utils'; -import { hasDecorator, DecoratorNames } from './property-translators/utils'; import { - isCustomComponentClass, - isKnownMethodDefinition, - isEtsGlobalClass, - isReourceNode, - ScopeInfoCollection, CustomComponentScopeInfo, - isMemoCall, + ScopeInfoCollection, findCanAddMemoFromArrowFunction, + isResourceNode, } from './struct-translators/utils'; import { isBuilderLambda, isBuilderLambdaMethodDecl } from './builder-lambda-translators/utils'; import { isEntryWrapperClass } from './entry-translators/utils'; -import { classifyObservedTrack, classifyProperty, PropertyTranslator } from './property-translators'; -import { ObservedTrackTranslator } from './property-translators/observedTrack'; -import { nodeByType } from '@koalaui/libarkts/build/src/reexport-for-generated'; +import { ImportCollector } from './import-collector'; +import { PropertyCache } from './property-translators/utils'; import { isArkUICompatible, updateArkUICompatible } from './interop'; export class CheckedTransformer extends AbstractVisitor { - private scopeInfoCollection: ScopeInfoCollection; + private scope: ScopeInfoCollection; projectConfig: ProjectConfig | undefined; constructor(projectConfig: ProjectConfig | undefined) { super(); this.projectConfig = projectConfig; - this.scopeInfoCollection = { customComponents: [] }; + this.scope = { customComponents: [] }; } reset(): void { super.reset(); - this.scopeInfoCollection = { customComponents: [] }; + this.scope = { customComponents: [] }; + PropertyCache.getInstance().reset(); + ImportCollector.getInstance().reset(); } enter(node: arkts.AstNode): void { - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfoCollection.customComponents.push({ name: node.definition!.ident!.name }); + if (arkts.isClassDeclaration(node) && !!node.definition && node.definition.body.length > 0) { + const customComponentInfo = collectCustomComponentScopeInfo(node); + if (!!customComponentInfo) { + this.scope.customComponents.push(customComponentInfo); + } } - if (arkts.isMethodDefinition(node) && this.scopeInfoCollection.customComponents.length > 0) { + if (arkts.isMethodDefinition(node) && this.scope.customComponents.length > 0) { const name = node.name.name; - const scopeInfo = this.scopeInfoCollection.customComponents.pop()!; + const scopeInfo = this.scope.customComponents.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; - this.scopeInfoCollection.customComponents.push(scopeInfo); + this.scope.customComponents.push(scopeInfo); } } exit(node: arkts.AstNode): void { - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfoCollection.customComponents.pop(); + if ( + arkts.isClassDeclaration(node) && + this.scope.customComponents.length > 0 && + isCustomComponentClass(node, this.scope.customComponents[this.scope.customComponents.length - 1]) + ) { + this.scope.customComponents.pop(); } } @@ -88,387 +87,35 @@ export class CheckedTransformer extends AbstractVisitor { const lambda = builderLambdaFactory.transformBuilderLambda(beforeChildren, this.projectConfig); return this.visitEachChild(lambda); } else if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren)) { - const lambda = builderLambdaFactory.transformBuilderLambdaMethodDecl(beforeChildren); + const lambda = builderLambdaFactory.transformBuilderLambdaMethodDecl(beforeChildren, this.externalSourceName); return this.visitEachChild(lambda); } const node = this.visitEachChild(beforeChildren); - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - let scope: CustomComponentScopeInfo | undefined; - const scopeInfos: CustomComponentScopeInfo[] = this.scopeInfoCollection.customComponents; - if (scopeInfos.length > 0) { - scope = scopeInfos[scopeInfos.length - 1]; - } - const newClass: arkts.ClassDeclaration = tranformClassMembers( - node, - arkts.hasModifierFlag(node, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE), - scope - ); + if ( + arkts.isClassDeclaration(node) && + this.scope.customComponents.length > 0 && + isCustomComponentClass(node, this.scope.customComponents[this.scope.customComponents.length - 1]) + ) { + const scope: CustomComponentScopeInfo = this.scope.customComponents[this.scope.customComponents.length - 1]; + const newClass: arkts.ClassDeclaration = structFactory.tranformClassMembers(node, scope); this.exit(beforeChildren); return newClass; } else if (isEntryWrapperClass(node)) { entryFactory.addMemoToEntryWrapperClassMethods(node); return node; - } else if (arkts.isClassDeclaration(node) && isEtsGlobalClass(node)) { - return transformEtsGlobalClassMembers(node); - } else if (arkts.isCallExpression(node) && isReourceNode(node)) { - return transformResource(node, this.projectConfig); - } else if (findCanAddMemoFromArrowFunction(node)) { - return addMemoAnnotation(node); } else if (arkts.isClassDeclaration(node)) { - return transformObservedTracked(node); + return structFactory.transformNormalClass(node); + } else if (arkts.isCallExpression(node) && isResourceNode(node)) { + return structFactory.transformResource(node, this.projectConfig); } else if (isArkUICompatible(node)) { return updateArkUICompatible(node as arkts.CallExpression); - } else if (this.externalSourceName) { - return structFactory.transformExternalSource(this.externalSourceName, node); + } else if (arkts.isTSInterfaceDeclaration(node)) { + return structFactory.tranformInterfaceMembers(node, this.externalSourceName); + } else if (findCanAddMemoFromArrowFunction(node)) { + return addMemoAnnotation(node); + } else if (arkts.isEtsScript(node) && ImportCollector.getInstance().importInfos.length > 0) { + ImportCollector.getInstance().insertCurrentImports(this.program); } return node; } } - -export type ClassScopeInfo = { - isObserved: boolean; - classHasTrack: boolean; - getters: arkts.MethodDefinition[]; -}; - -function transformObservedTracked(node: arkts.ClassDeclaration): arkts.ClassDeclaration { - if (!node.definition) { - return node; - } - const isObserved: boolean = hasDecorator(node.definition, DecoratorNames.OBSERVED); - const classHasTrack: boolean = node.definition.body.some( - (member) => arkts.isClassProperty(member) && hasDecorator(member, DecoratorNames.TRACK) - ); - if (!isObserved && !classHasTrack) { - return node; - } - - const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( - node.definition, - node.definition.ident, - node.definition.typeParams, - node.definition.superTypeParams, - [ - ...node.definition.implements, - arkts.TSClassImplements.createTSClassImplements( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('IObservedObject')) - ) - ), - ], - undefined, - node.definition.super, - observedTrackPropertyMembers(classHasTrack, node.definition, isObserved), - node.definition.modifiers, - arkts.classDefinitionFlags(node.definition) - ); - return arkts.factory.updateClassDeclaration(node, updateClassDef); -} - -function observedTrackPropertyMembers( - classHasTrack: boolean, - definition: arkts.ClassDefinition, - isObserved: boolean -): arkts.AstNode[] { - const watchMembers: arkts.AstNode[] = createWatchMembers(); - const permissibleAddRefDepth: arkts.ClassProperty = arkts.factory.createClassProperty( - arkts.factory.createIdentifier('_permissibleAddRefDepth'), - arkts.factory.createNumericLiteral(0), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('int32')) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false - ); - - const meta: arkts.ClassProperty = arkts.factory.createClassProperty( - arkts.factory.createIdentifier('__meta'), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) - ), - [arkts.factory.createStringLiteral('@Observe properties (no @Track)')] - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - - const getters: arkts.MethodDefinition[] = getGettersFromClassDecl(definition); - - const classScopeInfo: ClassScopeInfo = { - isObserved: isObserved, - classHasTrack: classHasTrack, - getters: getters, - }; - - const propertyTranslators: ObservedTrackTranslator[] = filterDefined( - definition.body.map((it) => classifyObservedTrack(it, classScopeInfo)) - ); - - const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); - - const nonClassPropertyOrGetter: arkts.AstNode[] = definition.body.filter( - (member) => - !arkts.isClassProperty(member) && - !( - arkts.isMethodDefinition(member) && - arkts.hasModifierFlag(member, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_GETTER) - ) - ); - - return [ - ...watchMembers, - ...(classHasTrack ? [permissibleAddRefDepth] : [permissibleAddRefDepth, meta]), - ...collect(...propertyMembers), - ...nonClassPropertyOrGetter, - ...classScopeInfo.getters, - ]; -} - -function createWatchMethod( - methodName: string, - returnType: arkts.Es2pandaPrimitiveType, - paramName: string, - paramType: string, - isReturnStatement: boolean -): arkts.MethodDefinition { - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - arkts.factory.createIdentifier(methodName), - arkts.factory.createFunctionExpression( - arkts.factory.createScriptFunction( - arkts.factory.createBlock([ - isReturnStatement - ? arkts.factory.createReturnStatement( - arkts.factory.createCallExpression(thisSubscribedWatchesMember(methodName), undefined, [ - arkts.factory.createIdentifier(paramName), - ]) - ) - : arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(thisSubscribedWatchesMember(methodName), undefined, [ - arkts.factory.createIdentifier(paramName), - ]) - ), - ]), - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - paramName, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(paramType)) - ) - ), - undefined - ), - ], - arkts.factory.createPrimitiveType(returnType), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false - ); -} - -function createWatchMembers(): arkts.AstNode[] { - const subscribedWatches: arkts.ClassProperty = arkts.factory.createClassProperty( - arkts.factory.createIdentifier('subscribedWatches'), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('SubscribedWatches')) - ), - [] - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('SubscribedWatches')) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - - const addWatchSubscriber = createWatchMethod( - 'addWatchSubscriber', - arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID, - 'watchId', - 'WatchIdType', - false - ); - - const removeWatchSubscriber = createWatchMethod( - 'removeWatchSubscriber', - arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BOOLEAN, - 'watchId', - 'WatchIdType', - true - ); - - const executeOnSubscribingWatches = createWatchMethod( - 'executeOnSubscribingWatches', - arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID, - 'propertyName', - 'string', - false - ); - - return [subscribedWatches, addWatchSubscriber, removeWatchSubscriber, executeOnSubscribingWatches]; -} - -function thisSubscribedWatchesMember(member: string): arkts.MemberExpression { - return arkts.factory.createMemberExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('subscribedWatches'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createIdentifier(member), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ); -} - -/** - * @deprecated - */ -function tranformClassMembers( - node: arkts.ClassDeclaration, - isDecl?: boolean, - scope?: CustomComponentScopeInfo -): arkts.ClassDeclaration { - if (!node.definition) { - return node; - } - - let classTypeName: string | undefined; - let classOptionsName: string | undefined; - if (isDecl) { - const [classType, classOptions] = getTypeParamsFromClassDecl(node); - classTypeName = getTypeNameFromTypeParameter(classType); - classOptionsName = getTypeNameFromTypeParameter(classOptions); - } - const definition: arkts.ClassDefinition = node.definition; - const className: string | undefined = node.definition.ident?.name; - if (!className) { - throw new Error('Non Empty className expected for Component'); - } - - const propertyTranslators: PropertyTranslator[] = filterDefined( - definition.body.map((it) => classifyProperty(it, className)) - ); - const translatedMembers: arkts.AstNode[] = tranformPropertyMembers( - className, - propertyTranslators, - classOptionsName ?? getCustomComponentOptionsName(className), - isDecl, - scope - ); - const updateMembers: arkts.AstNode[] = definition.body - .filter((member) => !arkts.isClassProperty(member)) - .map((member: arkts.AstNode) => - transformOtherMembersInClass(member, classTypeName, classOptionsName, className, isDecl) - ); - - const updateClassDef: arkts.ClassDefinition = structFactory.updateCustomComponentClass(definition, [ - ...translatedMembers, - ...updateMembers, - ]); - return arkts.factory.updateClassDeclaration(node, updateClassDef); -} - -/** - * @deprecated - */ -function transformOtherMembersInClass( - member: arkts.AstNode, - classTypeName: string | undefined, - classOptionsName: string | undefined, - className: string, - isDecl?: boolean -): arkts.AstNode { - if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { - member.scriptFunction.setAnnotations([annotation('memo')]); - return member; - } - if ( - arkts.isMethodDefinition(member) && - isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI) && - !isDecl - ) { - return uiFactory.createConstructorMethod(member); - } - if (arkts.isMethodDefinition(member) && isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI)) { - return structFactory.transformBuildMethodWithOriginBuild( - member, - classTypeName ?? className, - classOptionsName ?? getCustomComponentOptionsName(className), - isDecl - ); - } - return member; -} - -/** - * @deprecated - */ -function tranformPropertyMembers( - className: string, - propertyTranslators: PropertyTranslator[], - optionsTypeName: string, - isDecl?: boolean, - scope?: CustomComponentScopeInfo -): arkts.AstNode[] { - const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); - const collections = []; - if (!scope?.hasInitializeStruct) { - collections.push(structFactory.createInitializeStruct(currentStructInfo, optionsTypeName, isDecl)); - } - if (!scope?.hasUpdateStruct) { - collections.push(structFactory.createUpdateStruct(currentStructInfo, optionsTypeName, isDecl)); - } - if (currentStructInfo.isReusable) { - collections.push(structFactory.toRecord(optionsTypeName, currentStructInfo.toRecordBody)); - } - return collect(...collections, ...propertyMembers); -} - -/** - * @deprecated - */ -function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.ClassDeclaration { - if (!node.definition) { - return node; - } - node.definition.body.map((member: arkts.AstNode) => { - if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { - member.scriptFunction.setAnnotations([annotation('memo')]); - } - return member; - }); - return node; -} - -/** - * @deprecated - */ -function transformResource( - resourceNode: arkts.CallExpression, - projectConfig: ProjectConfig | undefined -): arkts.CallExpression { - const newArgs: arkts.AstNode[] = [ - arkts.factory.create1StringLiteral(projectConfig?.bundleName ? projectConfig.bundleName : ''), - arkts.factory.create1StringLiteral(projectConfig?.moduleName ? projectConfig.moduleName : ''), - ...resourceNode.arguments, - ]; - return structFactory.generateTransformedResource(resourceNode, newArgs); -} diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index db66f9d7e..cf856101a 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -21,37 +21,32 @@ import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { CustomComponentNames, getCustomComponentOptionsName, - createOptionalClassProperty, findLocalImport, + CustomComponentInfo, + collectCustomComponentScopeInfo, + isComponentStruct, } from './utils'; -import { isAnnotation, updateStructMetadata, backingField, expectName, annotation } from '../common/arkts-utils'; +import { backingField, expectName, annotation, filterDefined, collect } from '../common/arkts-utils'; import { EntryWrapperNames, findEntryWithStorageInClassAnnotations } from './entry-translators/utils'; import { factory as entryFactory } from './entry-translators/factory'; import { - hasDecorator, + hasDecoratorName, DecoratorNames, - getStateManagementType, - collectPropertyDecorators, + findDecoratorInfos, + isDecoratorAnnotation, + decoratorTypeMap, + DecoratorIntrinsicNames, } from './property-translators/utils'; import { factory } from './ui-factory'; +import { factory as propertyFactory } from './property-translators/factory'; import { StructMap } from '../common/program-visitor'; import { generateTempCallFunction } from './interop'; -import { stringify } from 'querystring'; export interface ComponentTransformerOptions extends VisitorOptions { arkui?: string; } -type ScopeInfo = { - name: string; - isEntry?: boolean; - isComponent?: boolean; - isReusable?: boolean; -}; - -interface ComponentContext { - structMembers: Map; -} +type ScopeInfo = CustomComponentInfo; export interface InteropContext { className: string; @@ -65,12 +60,12 @@ export class ComponentTransformer extends AbstractVisitor { private scopeInfos: ScopeInfo[] = []; private componentInterfaceCollection: arkts.TSInterfaceDeclaration[] = []; private entryNames: string[] = []; - private reusableNames: string[] = []; private readonly arkui?: string; - private context: ComponentContext = { structMembers: new Map() }; + private structMembersMap: Map = new Map(); private isCustomComponentImported: boolean = false; private isEntryPointImported: boolean = false; - private hasLegacy = false; + private shouldAddLinkIntrinsic: boolean = false; + private hasLegacy: boolean = false; private legacyStructMap: Map = new Map(); private legacyCallMap: Map = new Map(); @@ -85,10 +80,10 @@ export class ComponentTransformer extends AbstractVisitor { this.scopeInfos = []; this.componentInterfaceCollection = []; this.entryNames = []; - this.reusableNames = []; - this.context = { structMembers: new Map() }; + this.structMembersMap = new Map(); this.isCustomComponentImported = false; this.isEntryPointImported = false; + this.shouldAddLinkIntrinsic = false; this.hasLegacy = false; this.legacyStructMap = new Map(); this.legacyCallMap = new Map(); @@ -96,13 +91,10 @@ export class ComponentTransformer extends AbstractVisitor { enter(node: arkts.AstNode) { if (arkts.isStructDeclaration(node) && !!node.definition.ident) { - const scopeInfo: ScopeInfo = { name: node.definition.ident.name }; - node.definition.annotations.forEach((anno) => { - scopeInfo.isEntry ||= isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION_NAME); - scopeInfo.isComponent ||= isAnnotation(anno, CustomComponentNames.COMPONENT_ANNOTATION_NAME); - scopeInfo.isReusable ||= isAnnotation(anno, CustomComponentNames.RESUABLE_ANNOTATION_NAME); - }); - this.scopeInfos.push(scopeInfo); + const info: ScopeInfo | undefined = collectCustomComponentScopeInfo(node); + if (info) { + this.scopeInfos.push(info); + } } if (arkts.isETSImportDeclaration(node) && !this.isCustomComponentImported) { this.isCustomComponentImported = !!findLocalImport( @@ -129,12 +121,6 @@ export class ComponentTransformer extends AbstractVisitor { } } - isComponentStruct(): boolean { - if (this.scopeInfos.length === 0) return false; - const scopeInfo: ScopeInfo = this.scopeInfos[this.scopeInfos.length - 1]; - return !!scopeInfo.isComponent; - } - createImportDeclaration(): void { const source: arkts.StringLiteral = arkts.factory.create1StringLiteral( this.arkui ?? CustomComponentNames.COMPONENT_DEFAULT_IMPORT @@ -157,7 +143,11 @@ export class ComponentTransformer extends AbstractVisitor { if (this.isExternal && this.componentInterfaceCollection.length === 0 && this.entryNames.length === 0) { return node; } - let updateStatements: arkts.AstNode[] = []; + const updateStatements: arkts.AstNode[] = []; + if (this.shouldAddLinkIntrinsic) { + const expr = arkts.factory.createIdentifier(DecoratorIntrinsicNames.LINK); + updateStatements.push(factory.createIntrinsicAnnotationDeclaration({ expr })); + } if (this.componentInterfaceCollection.length > 0) { if (!this.isCustomComponentImported) this.createImportDeclaration(); updateStatements.push(...this.componentInterfaceCollection); @@ -165,7 +155,7 @@ export class ComponentTransformer extends AbstractVisitor { if (this.entryNames.length > 0) { if (!this.isEntryPointImported) entryFactory.createAndInsertEntryPointImport(this.program); - // TODO: normally, we should only have at most one @Entry component in a single file. + // normally, we should only have at most one @Entry component in a single file. // probably need to handle error message here. updateStatements.push(...this.entryNames.map(entryFactory.generateEntryWrapper)); } @@ -203,7 +193,7 @@ export class ComponentTransformer extends AbstractVisitor { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, arkts.factory.createIdentifier(CustomComponentNames.BUILDCOMPATIBLENODE), - arkts.factory.createFunctionExpression(script), + script, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, false ); @@ -218,23 +208,22 @@ export class ComponentTransformer extends AbstractVisitor { return node; } - arkts.GlobalInfo.getInfoInstance().add(className); + arkts.insertGlobalStructInfo(className); if (arkts.isStructDeclaration(node)) { this.collectComponentMembers(node, className); } - if (scopeInfo.isReusable) { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); - currentStructInfo.isReusable = true; - arkts.GlobalInfo.getInfoInstance().setStructInfo(className, currentStructInfo); - } - - this.componentInterfaceCollection.push(this.generateComponentInterface(className, node.modifiers)); + const customComponentInterface = this.generateComponentInterface( + className, + node.modifiers | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT, + Object.values(scopeInfo.annotations ?? {}).map((anno) => anno.clone()) + ); + this.componentInterfaceCollection.push(customComponentInterface); const definition: arkts.ClassDefinition = node.definition!; const newDefinitionBody: arkts.AstNode[] = []; - if (scopeInfo.isEntry) { + if (!!scopeInfo.annotations?.entry) { this.entryNames.push(className); const entryWithStorage: arkts.ClassProperty | undefined = findEntryWithStorageInClassAnnotations(definition); @@ -274,94 +263,106 @@ export class ComponentTransformer extends AbstractVisitor { staticMethodBody.push(buildCompatibleNode); } } - return arkts.factory.updateClassDefinition( - definition, - definition.ident, - undefined, - undefined, // superTypeParams doen't work - definition.implements, - undefined, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_CLASS_NAME), - arkts.factory.createTSTypeParameterInstantiation([ - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(className)) - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier( - `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${className}` + return arkts.factory + .createClassDefinition( + definition.ident, + undefined, + undefined, // superTypeParams doen't work + definition.implements, + undefined, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_CLASS_NAME), + arkts.factory.createTSTypeParameterInstantiation([ + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(className)) + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier( + `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${className}` + ) ) - ) - ), - ]) - ) - ), - [ - ...newDefinitionBody, - ...definition.body.map((st: arkts.AstNode) => factory.PreprocessClassPropertyModifier(st)), - ...staticMethodBody, - ], - definition.modifiers, - arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL - ); + ), + ]) + ) + ), + [ + ...newDefinitionBody, + ...definition.body.map((st: arkts.AstNode) => factory.PreprocessClassPropertyModifier(st)), + ...staticMethodBody, + ], + definition.modifiers, + arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL + ) + .setAnnotations(definition.annotations); } - generateComponentInterface(name: string, modifiers: number): arkts.TSInterfaceDeclaration { - const interfaceNode = arkts.factory.createInterfaceDeclaration( - [], - arkts.factory.createIdentifier(getCustomComponentOptionsName(name)), - nullptr, // TODO: wtf - arkts.factory.createInterfaceBody([...(this.context.structMembers.get(name) || [])]), - false, - false - ); + generateComponentInterface( + name: string, + modifiers: number, + annotations?: readonly arkts.AnnotationUsage[] + ): arkts.TSInterfaceDeclaration { + const interfaceNode = arkts.factory + .createInterfaceDeclaration( + [], + arkts.factory.createIdentifier(getCustomComponentOptionsName(name)), + nullptr, + arkts.factory.createInterfaceBody([...(this.structMembersMap.get(name) || [])]), + false, + false + ) + .setAnnotations(annotations ?? []); interfaceNode.modifiers = modifiers; return interfaceNode; } collectComponentMembers(node: arkts.StructDeclaration, className: string): void { - const structInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); - if (!this.context.structMembers.has(className)) { - this.context.structMembers.set(className, []); - } - node.definition.body.map((it) => { - if (arkts.isClassProperty(it)) { - if (hasDecorator(it, DecoratorNames.PROVIDE)) { - factory.processNoAliasProvideVariable(it); - } - this.context.structMembers.get(className)!.push(...this.createInterfaceInnerMember(it, structInfo)); - } - }); - arkts.GlobalInfo.getInfoInstance().setStructInfo(className, structInfo); + const members = filterDefined( + collect( + ...node.definition.body.filter(arkts.isClassProperty).map((it) => { + if (hasDecoratorName(it, DecoratorNames.PROVIDE)) { + factory.processNoAliasProvideVariable(it); + } + return this.createInterfaceInnerMember(it); + }) + ) + ); + this.structMembersMap.set(className, members); } - createInterfaceInnerMember(member: arkts.ClassProperty, structInfo: arkts.StructInfo): arkts.ClassProperty[] { + createInterfaceInnerMember(member: arkts.ClassProperty): arkts.ClassProperty[] { const originalName: string = expectName(member.key); - const newName: string = backingField(originalName); - - const properties = collectPropertyDecorators(member); - const hasStateManagementType = properties.length > 0; - updateStructMetadata(structInfo, originalName, properties, member.modifiers, hasStateManagementType); - - const originMember: arkts.ClassProperty = createOptionalClassProperty( + const originMember: arkts.ClassProperty = propertyFactory.createOptionalClassProperty( originalName, member, - '', + undefined, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); - if (member.annotations.length > 0 && !hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { - const newMember: arkts.ClassProperty = createOptionalClassProperty( - newName, - member, - getStateManagementType(member), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ); - return [originMember, newMember]; + const infos = findDecoratorInfos(member); + const buildParamInfo = infos.find((it) => + isDecoratorAnnotation(it.annotation, DecoratorNames.BUILDER_PARAM, true) + ); + if (!!buildParamInfo) { + originMember.setAnnotations([buildParamInfo.annotation.clone()]); + return [originMember]; } - if (hasDecorator(member, DecoratorNames.BUILDER_PARAM) && !!originMember.typeAnnotation) { - originMember.typeAnnotation.setAnnotations([annotation('memo')]); + const targetInfo = infos.find((it) => decoratorTypeMap.has(it.name)); + if (!!targetInfo) { + const newName: string = backingField(originalName); + const newMember: arkts.ClassProperty = propertyFactory + .createOptionalClassProperty( + newName, + member, + undefined, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ) + .setAnnotations([targetInfo.annotation.clone()]); + if (isDecoratorAnnotation(targetInfo.annotation, DecoratorNames.LINK, true)) { + this.shouldAddLinkIntrinsic = true; + originMember.setAnnotations([annotation(DecoratorIntrinsicNames.LINK)]); + } + return [originMember, newMember]; } return [originMember]; } @@ -373,15 +374,15 @@ export class ComponentTransformer extends AbstractVisitor { processImport(node: arkts.ETSImportDeclaration): void { const source = node.source?.str!; - const specifiers = node.specifiers; + const specifiers = node.specifiers as arkts.ImportSpecifier[]; if (this.legacyStructMap.has(source)) { const structMap = this.legacyStructMap.get(source); if (!structMap) { return; } for (const specifier of specifiers) { - const name = specifier.local.name; - if (structMap[name]) { + const name = specifier.local?.name; + if (!!name && structMap[name]) { this.legacyCallMap.set(name, structMap[name]); } } @@ -394,7 +395,11 @@ export class ComponentTransformer extends AbstractVisitor { if (arkts.isEtsScript(newNode)) { return this.processEtsScript(newNode); } - if (arkts.isStructDeclaration(newNode) && this.isComponentStruct()) { + if ( + arkts.isStructDeclaration(newNode) && + this.scopeInfos.length > 0 && + isComponentStruct(newNode, this.scopeInfos[this.scopeInfos.length - 1]) + ) { const updateNode = this.processComponent(newNode); this.exit(newNode); return updateNode; @@ -405,22 +410,16 @@ export class ComponentTransformer extends AbstractVisitor { if (arkts.isETSImportDeclaration(newNode)) { this.processImport(newNode); } - if (arkts.isCallExpression(newNode)) { - const ident = newNode.expression; - if (!(ident instanceof arkts.Identifier)) { - return newNode; - } - const className = ident.name; + if (arkts.isCallExpression(newNode) && arkts.isIdentifier(newNode.expression)) { + const className = newNode.expression.name; if (this.legacyCallMap.has(className)) { const path = this.legacyCallMap.get(className)!; - // const pathName = 'path/har1'; const args = newNode.arguments; const context: InteropContext = { className: className, path: path, - arguments: args && args.length === 1 && args[0] instanceof arkts.ObjectExpression - ? args[0] - : undefined + arguments: + args && args.length === 1 && args[0] instanceof arkts.ObjectExpression ? args[0] : undefined, }; return generateTempCallFunction(context); } diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index e2d04b3d2..1e395923a 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -83,11 +83,7 @@ export class factory { */ static generateEntryFunction(name: string): arkts.MethodDefinition { const exp = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createIdentifier(name), - undefined, - [arkts.factory.createUndefinedLiteral()] // TODO: Add this undefined later - ) + arkts.factory.createCallExpression(arkts.factory.createIdentifier(name), undefined, []) ); const key: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_FUNC); const block = arkts.factory.createBlock([exp]); @@ -108,7 +104,7 @@ export class factory { const def = arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, key, - arkts.factory.createFunctionExpression(entryScript), + entryScript, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -132,7 +128,7 @@ export class factory { const def = arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, key, - arkts.factory.createFunctionExpression(entryScript), + entryScript, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, false ); @@ -151,7 +147,7 @@ export class factory { arkts.factory.createCallExpression( arkts.factory.createIdentifier(name), undefined, - [arkts.factory.createUndefinedLiteral()] // TODO: Add this undefined later + [] ) ); const key: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_FUNC); diff --git a/arkui-plugins/ui-plugins/entry-translators/utils.ts b/arkui-plugins/ui-plugins/entry-translators/utils.ts index 61a03783c..2788e987c 100644 --- a/arkui-plugins/ui-plugins/entry-translators/utils.ts +++ b/arkui-plugins/ui-plugins/entry-translators/utils.ts @@ -73,7 +73,7 @@ export function isEntryWrapperClass(node: arkts.AstNode): node is arkts.ClassDec */ export function findEntryWithStorageInClassAnnotations(node: arkts.ClassDefinition): arkts.ClassProperty | undefined { const annotation = node.annotations.find((anno) => { - if (!isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION_NAME)) return false; + if (!isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION)) return false; const property = anno.properties?.at(0); if (!property || !arkts.isClassProperty(property)) return false; if (!property.key || !arkts.isIdentifier(property.key)) return false; diff --git a/arkui-plugins/ui-plugins/import-collector.ts b/arkui-plugins/ui-plugins/import-collector.ts new file mode 100644 index 000000000..c16c6cdb0 --- /dev/null +++ b/arkui-plugins/ui-plugins/import-collector.ts @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { factory } from './ui-factory'; + +interface ImportInfo { + imported: string; + local: string; + source: string; + kind: arkts.Es2pandaImportKinds; +} + +function insertImport(importInfo: ImportInfo, program?: arkts.Program): void { + const source: arkts.StringLiteral = arkts.factory.create1StringLiteral(importInfo.source); + const imported: arkts.Identifier = arkts.factory.createIdentifier(importInfo.imported); + const local: arkts.Identifier = arkts.factory.createIdentifier(importInfo.local); + // Insert this import at the top of the script's statements. + if (!program) { + throw Error('Failed to insert import: Transformer has no program'); + } + factory.createAndInsertImportDeclaration(source, imported, local, importInfo.kind, program); +} + +export class ImportCollector { + public importInfos: ImportInfo[]; + public localMap: Map; + public sourceMap: Map; + private static instance: ImportCollector; + + /** this set is used for keeping the import sentence unique */ + private imported: Set; + + private constructor() { + this.importInfos = []; + this.imported = new Set(); + this.localMap = new Map(); + this.sourceMap = new Map(); + } + + static getInstance(): ImportCollector { + if (!this.instance) { + this.instance = new ImportCollector(); + } + return this.instance; + } + + reset(): void { + this.importInfos = []; + this.imported.clear(); + this.localMap.clear(); + this.sourceMap.clear(); + } + + collectSource(imported: string, source: string): void { + if (!this.sourceMap.has(imported)) { + this.sourceMap.set(imported, source); + } + } + + collectImport( + imported: string, + local?: string, + kind: arkts.Es2pandaImportKinds = arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE + ): void { + if (!this.sourceMap.has(imported)) { + throw new Error(`ImportCollector: import ${imported}'s source haven't been collected yet.`); + } + if (this.imported.has(imported)) { + return; + } + const source: string = this.sourceMap.get(imported)!; + const _local: string = local ?? imported; + this.importInfos.push({ + source, + imported, + local: _local, + kind, + }); + this.localMap.set(imported, _local); + this.imported.add(imported); + } + + getLocal(imported: string): string | undefined { + return this.localMap.get(imported); + } + + insertCurrentImports(program?: arkts.Program): void { + this.importInfos.forEach((importInfo) => { + insertImport(importInfo, program); + }); + } +} diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index 76e2e6883..a50014ecf 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -36,7 +36,7 @@ export function uiTransform(): Plugins { function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; console.log('[UI PLUGIN] AFTER PARSED ENTER'); - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; @@ -47,7 +47,7 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { getDumpFileName(0, 'SRC', 1, 'UI_AfterParse_Begin'), true, cachePath, - program.programFileNameWithExtension + program.fileNameWithExtension ); arkts.Performance.getInstance().createEvent('ui-parsed'); const componentTransformer = new ComponentTransformer(); @@ -61,14 +61,14 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { }); program = programVisitor.programVisitor(program); script = program.astNode; - arkts.Performance.getInstance().stopEvent('ui-parsed', true); + arkts.Performance.getInstance().stopEvent('ui-parsed', false); debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); debugDump( script.dumpSrc(), getDumpFileName(0, 'SRC', 2, 'UI_AfterParse_End'), true, cachePath, - program.programFileNameWithExtension + program.fileNameWithExtension ); this.setArkTSAst(script); console.log('[UI PLUGIN] AFTER PARSED EXIT'); @@ -81,7 +81,7 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; console.log('[UI PLUGIN] AFTER CHECKED ENTER'); - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; @@ -92,7 +92,7 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { getDumpFileName(0, 'SRC', 3, 'UI_AfterCheck_Begin'), true, cachePath, - program.programFileNameWithExtension + program.fileNameWithExtension ); arkts.Performance.getInstance().createEvent('ui-checked'); const checkedTransformer = new CheckedTransformer(this.getProjectConfig()); @@ -105,20 +105,22 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { }); program = programVisitor.programVisitor(program); script = program.astNode; - arkts.Performance.getInstance().stopEvent('ui-checked', true); + arkts.Performance.getInstance().stopEvent('ui-checked', false); debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); debugDump( script.dumpSrc(), getDumpFileName(0, 'SRC', 4, 'UI_AfterCheck_End'), true, cachePath, - program.programFileNameWithExtension + program.fileNameWithExtension ); - arkts.GlobalInfo.getInfoInstance().reset(); arkts.Performance.getInstance().createEvent('ui-recheck'); arkts.recheckSubtree(script); - arkts.Performance.getInstance().stopEvent('ui-recheck', true); - arkts.Performance.getInstance().clearAllEvents(); + arkts.Performance.getInstance().stopEvent('ui-recheck', false); + arkts.Performance.getInstance().clearAllEvents(false); + arkts.Performance.getInstance().visualizeEvents(true); + arkts.Performance.getInstance().clearHistory(); + arkts.Performance.getInstance().clearTotalDuration(); this.setArkTSAst(script); console.log('[UI PLUGIN] AFTER CHECKED EXIT'); return script; diff --git a/arkui-plugins/ui-plugins/legacy-transformer.ts b/arkui-plugins/ui-plugins/legacy-transformer.ts index 8196f89a2..2791e0192 100644 --- a/arkui-plugins/ui-plugins/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/legacy-transformer.ts @@ -82,7 +82,7 @@ export class LegacyTransformer extends AbstractVisitor { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, arkts.factory.createIdentifier('instantiate_Interop'), - arkts.factory.createFunctionExpression(script), + script, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, false ); @@ -111,7 +111,7 @@ export class LegacyTransformer extends AbstractVisitor { const interfaceNode = arkts.factory.createInterfaceDeclaration( [], arkts.factory.createIdentifier(getCustomComponentOptionsName(name)), - nullptr, // TODO: wtf + nullptr, arkts.factory.createInterfaceBody([...(this.generateMember(map) || [])]), false, false @@ -201,7 +201,7 @@ export class LegacyTransformer extends AbstractVisitor { node, node.kind, node.name, - arkts.factory.createFunctionExpression(script), + script, node.modifiers, false ); diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 635a1e83a..35132fb5a 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -26,19 +26,10 @@ import { } from '../common/predefines'; import { NameCollector } from './name-collector'; -interface MemoImportCollection { - memo: boolean; - memoContextType: boolean; - memoIdType: boolean; -} - export class PreprocessorTransformer extends AbstractVisitor { private outNameArr: string[] = []; - private memoNameArr: string[] = []; private structInterfaceImport: arkts.ETSImportDeclaration[] = []; - private memoImportCollection: Partial = {}; private localComponentNames: string[] = []; - private isMemoImportOnce: boolean = false; private readonly nameCollector: NameCollector; @@ -50,19 +41,13 @@ export class PreprocessorTransformer extends AbstractVisitor { reset(): void { super.reset(); this.outNameArr = []; - this.memoNameArr = []; this.structInterfaceImport = []; - this.memoImportCollection = {}; this.localComponentNames = []; - this.isMemoImportOnce = false; - IMPORT_SOURCE_MAP.clear(); - IMPORT_SOURCE_MAP.set('arkui.stateManagement.runtime', new Set(['memo', '__memo_context_type', '__memo_id_type'])); } isCustomConponentDecl(node: arkts.CallExpression): boolean { - const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); const nodeName: string = node.expression.dumpSrc(); - if (structCollection.has(nodeName)) { + if (arkts.hasGlobalStructInfo(nodeName)) { return true; } return false; @@ -75,9 +60,7 @@ export class PreprocessorTransformer extends AbstractVisitor { transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { if (node.arguments.length === 0 && node.trailingBlock) { - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ - arkts.factory.createUndefinedLiteral(), - ]); + return node; } else if (arkts.isObjectExpression(node.arguments[0])) { const componentName: string = `${ CustomComponentNames.COMPONENT_INTERFACE_PREFIX @@ -122,19 +105,15 @@ export class PreprocessorTransformer extends AbstractVisitor { if (!node.source) return; const isFromCompImport: boolean = node.source.str === ARKUI_COMPONENT_IMPORT_NAME || node.source.str === KIT_ARKUI_NAME; - const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); node.specifiers.forEach((item: arkts.AstNode) => { if (!arkts.isImportSpecifier(item) || !item.imported?.name) return; const importName: string = item.imported.name; - this.memoImportCollection.memo ||= importName === 'memo'; - this.memoImportCollection.memoContextType ||= importName === '__memo_context_type'; - this.memoImportCollection.memoIdType ||= importName === '__memo_id_type'; if (isFromCompImport && this.nameCollector.getComponents().includes(importName)) { this.localComponentNames.push(item.local?.name ?? importName); } - if (structCollection.has(importName)) { + if (arkts.hasGlobalStructInfo(importName)) { const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + importName; const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( node.source?.clone(), @@ -190,51 +169,9 @@ export class PreprocessorTransformer extends AbstractVisitor { } } - prepareDependencyMap(node: arkts.ImportSpecifier, source: arkts.StringLiteral): void { - if (!node.imported?.name) return; - - // Handling component imports - const importName: string = node.imported.name; - const sourceName: string = source.str; - if ( - this.nameCollector.getComponents().includes(importName) && - (sourceName === ARKUI_COMPONENT_IMPORT_NAME || sourceName === KIT_ARKUI_NAME) - ) { - const newDependencies = [`UI${importName}Attribute`]; - this.updateOutDependencyMap(importName, newDependencies); - this.updateSourceDependencyMap(sourceName, newDependencies); - } else if ( - OUTPUT_DEPENDENCY_MAP.get(importName) && - (sourceName === ARKUI_COMPONENT_IMPORT_NAME || - sourceName === ARKUI_STATEMANAGEMENT_IMPORT_NAME || - sourceName === KIT_ARKUI_NAME) - ) { - const newDependencies: string[] = OUTPUT_DEPENDENCY_MAP.get(importName) ?? []; - this.updateSourceDependencyMap(sourceName, newDependencies); - } - } - - prepareMemoImports(): void { - const newDependencies = []; - if (!this.memoImportCollection.memo) { - newDependencies.push('memo'); - } - if (!this.memoImportCollection.memoContextType) { - newDependencies.push('__memo_context_type'); - } - if (!this.memoImportCollection.memoIdType) { - newDependencies.push('__memo_id_type'); - } - if (newDependencies.length > 0) { - this.memoNameArr.push(...newDependencies); - this.isMemoImportOnce = true; - } - } - addImportWithSpecifier(node: arkts.ImportSpecifier, source: arkts.StringLiteral): void { if (!node.imported?.name) return; - this.prepareDependencyMap(node, source); const outName: string[] = this.getOutDependencyName(node.imported?.name); this.outNameArr.push(...outName); } @@ -244,7 +181,7 @@ export class PreprocessorTransformer extends AbstractVisitor { throw Error('Failed to insert import: Transformer has no program'); } - const outNames = new Set([...this.outNameArr, ...this.memoNameArr]); + const outNames = new Set([...this.outNameArr]); outNames.forEach((item: string) => { const source: string = this.getSourceDependency(item); const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( @@ -269,17 +206,13 @@ export class PreprocessorTransformer extends AbstractVisitor { } visitor(node: arkts.AstNode): arkts.AstNode { - this.enter(node); const newNode = this.visitEachChild(node); if (arkts.isCallExpression(newNode) && this.isCustomConponentDecl(newNode)) { return this.transformComponentCall(newNode); - } else if (arkts.isCallExpression(newNode) && this.isComponentFunctionCall(newNode)) { - return this.transformComponentFunctionCall(newNode); } if (arkts.isETSImportDeclaration(node)) { this.addDependencesImport(node); } else if (arkts.isEtsScript(node)) { - if (!this.isMemoImportOnce) this.prepareMemoImports(); this.updateScriptWithImport(); } return newNode; diff --git a/arkui-plugins/ui-plugins/property-translators/base.ts b/arkui-plugins/ui-plugins/property-translators/base.ts index 4be00d1c8..6601ab282 100644 --- a/arkui-plugins/ui-plugins/property-translators/base.ts +++ b/arkui-plugins/ui-plugins/property-translators/base.ts @@ -14,55 +14,31 @@ */ import * as arkts from '@koalaui/libarkts'; -import { createGetter, createSetter, getStageManagementIdent } from './utils'; -import { createOptionalClassProperty } from '../utils'; +import { + collectStateManagementTypeImport, + collectStateManagementTypeSource, + createGetter, + createSetter, + StateManagementTypes, +} from './utils'; +import { CustomComponentInfo } from '../utils'; -export abstract class PropertyTranslator { - constructor( - protected property: arkts.ClassProperty, - protected structName: string - ) {} - - abstract translateMember(): arkts.AstNode[]; - - translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field = createOptionalClassProperty( - newName, - this.property, - getStageManagementIdent(this.property), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE - ); +export interface PropertyTranslatorOptions { + property: arkts.ClassProperty; + structInfo: CustomComponentInfo; +} - const member = arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(newName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ); - const thisValue: arkts.MemberExpression = arkts.factory.createMemberExpression( - member, - arkts.factory.createIdentifier('value'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ); +export abstract class PropertyTranslator { + protected property: arkts.ClassProperty; + protected structInfo: CustomComponentInfo; - const getter: arkts.MethodDefinition = this.translateGetter( - originalName, - this.property.typeAnnotation, - thisValue - ); - const setter: arkts.MethodDefinition = this.translateSetter( - originalName, - this.property.typeAnnotation, - thisValue - ); - return [field, getter, setter]; + constructor(options: PropertyTranslatorOptions) { + this.property = options.property; + this.structInfo = options.structInfo; } + abstract translateMember(): arkts.AstNode[]; + translateGetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, @@ -77,10 +53,37 @@ export abstract class PropertyTranslator { left: arkts.MemberExpression ): arkts.MethodDefinition { const right: arkts.CallExpression = arkts.factory.createCallExpression( - arkts.factory.createIdentifier('observableProxy'), + arkts.factory.createIdentifier(StateManagementTypes.OBSERVABLE_PROXY), undefined, [arkts.factory.createIdentifier('value')] ); + collectStateManagementTypeSource(StateManagementTypes.OBSERVABLE_PROXY); + collectStateManagementTypeImport(StateManagementTypes.OBSERVABLE_PROXY); return createSetter(originalName, typeAnnotation, left, right); } } + +export type InterfacePropertyTypes = arkts.MethodDefinition | arkts.ClassProperty; + +export interface InterfacePropertyTranslatorOptions { + property: T; +} + +export abstract class InterfacePropertyTranslator + implements InterfacePropertyTranslatorOptions +{ + property: T; + + modified: boolean; + + constructor(options: InterfacePropertyTranslatorOptions) { + this.property = options.property; + this.modified = false; + } + + abstract translateProperty(): T; + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + return false; + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts index fbf600f06..62b1f532b 100644 --- a/arkui-plugins/ui-plugins/property-translators/builderParam.ts +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -18,36 +18,40 @@ import * as arkts from '@koalaui/libarkts'; import { createGetter, createSetter, - generateThisBackingValue, generateThisBacking, - getValueInAnnotation, DecoratorNames, + hasDecorator, + removeDecorator, + PropertyCache, } from './utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; -import { createOptionalClassProperty } from '../utils'; +import { addMemoAnnotation, findCanAddMemoFromParamExpression, findCanAddMemoFromTypeAnnotation } from '../utils'; import { factory } from './factory'; export class BuilderParamTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const mutableThis: arkts.Expression = generateThisBacking(newName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(mutableThis, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, '', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, true); + const field: arkts.ClassProperty = factory.createOptionalClassProperty( + newName, + this.property, + undefined, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + true + ); const thisGetValue: arkts.Expression = generateThisBacking(newName, false, true); const thisSetValue: arkts.Expression = generateThisBacking(newName, false, false); const getter: arkts.MethodDefinition = this.translateGetter( @@ -100,3 +104,68 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia ); } } + +export class BuilderParamInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateBuilderParamMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateBuilderParamPropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.BUILDER_PARAM)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.BUILDER_PARAM)) { + return true; + } + return false; + } + + /** + * Add `@memo` to getter's return type and setter's param type (expecting a function type or a function type within a union type). + * + * @param method expecting getter with `@BuilderParam` and a setter with `@BuilderParam` in the overloads. + */ + private updateBuilderParamMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + if (method.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET) { + const type: arkts.TypeNode | undefined = method.scriptFunction.returnTypeAnnotation; + if (findCanAddMemoFromTypeAnnotation(type)) { + addMemoAnnotation(type); + } + const newOverLoads = method.overloads.map((overload) => { + if (arkts.isMethodDefinition(overload)) { + return this.updateBuilderParamMethodInInterface(overload); + } + return overload; + }); + method.setOverloads(newOverLoads); + removeDecorator(method, DecoratorNames.BUILDER_PARAM); + } else if (method.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET) { + const param: arkts.Expression | undefined = method.scriptFunction.params.at(0); + if (findCanAddMemoFromParamExpression(param)) { + addMemoAnnotation(param); + } + removeDecorator(method, DecoratorNames.BUILDER_PARAM); + } + return method; + } + + /** + * Add `@memo` to the type of the property (expecting a function type or a function type within a union type). + * + * @param property expecting property with `@BuilderParam`. + */ + private updateBuilderParamPropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + const type: arkts.TypeNode | undefined = property.typeAnnotation; + if (findCanAddMemoFromTypeAnnotation(type)) { + addMemoAnnotation(type); + } + removeDecorator(property, DecoratorNames.BUILDER_PARAM); + return property; + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/consume.ts b/arkui-plugins/ui-plugins/property-translators/consume.ts index bbb32deb1..553f586c8 100644 --- a/arkui-plugins/ui-plugins/property-translators/consume.ts +++ b/arkui-plugins/ui-plugins/property-translators/consume.ts @@ -23,37 +23,37 @@ import { generateGetOrSetCall, getValueInAnnotation, DecoratorNames, + StateManagementTypes, + hasDecorator, + PropertyCache, } from './utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; -import { createOptionalClassProperty } from '../utils'; import { factory } from './factory'; export class ConsumeTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); - currentStructInfo.initializeBody.push(initializeStruct); - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( + const field: arkts.ClassProperty = factory.createOptionalClassProperty( newName, this.property, - 'ConsumeDecoratedVariable', + StateManagementTypes.CONSUME_DECORATED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); @@ -101,3 +101,45 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer return arkts.factory.createExpressionStatement(assign); } } + +export class ConsumeInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.CONSUME)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.CONSUME)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `ConsumeDecoratedVariable | undefined`. + * + * @param method expecting getter with `@Consume` and a setter with `@Consume` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.CONSUME); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `ConsumeDecoratedVariable | undefined`. + * + * @param property expecting property with `@Consume`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.CONSUME); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts index c1f610a4b..704dced97 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -16,7 +16,17 @@ import * as arkts from '@koalaui/libarkts'; import { GenSymGenerator } from '../../common/gensym-generator'; import { factory as UIFactory } from '../ui-factory'; -import { judgeIfAddWatchFunc } from './utils'; +import { + collectStateManagementTypeImport, + collectStateManagementTypeSource, + DecoratorNames, + decoratorTypeMap, + getValueInAnnotation, + hasDecorator, + removeDecorator, + StateManagementTypes, +} from './utils'; +import { addMemoAnnotation, findCanAddMemoFromTypeAnnotation } from '../utils'; export class factory { /** @@ -254,7 +264,7 @@ export class factory { ), arkts.factory.createBooleanLiteral(allowOverride), ]; - judgeIfAddWatchFunc(args, property); + factory.judgeIfAddWatchFunc(args, property); return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), @@ -280,7 +290,7 @@ export class factory { arkts.factory.create1StringLiteral(originalName), arkts.factory.create1StringLiteral(alias), ]; - judgeIfAddWatchFunc(args, property); + factory.judgeIfAddWatchFunc(args, property); return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), @@ -293,4 +303,337 @@ export class factory { args ); } + + static judgeIfAddWatchFunc(args: arkts.Expression[], property: arkts.ClassProperty): void { + if (hasDecorator(property, DecoratorNames.WATCH)) { + const watchStr: string | undefined = getValueInAnnotation(property, DecoratorNames.WATCH); + if (watchStr) { + args.push(factory.createWatchCallback(watchStr)); + } + } + } + + static createOptionalClassProperty( + name: string, + property: arkts.ClassProperty, + stageManagementType: StateManagementTypes | undefined, + modifiers: arkts.Es2pandaModifierFlags, + needMemo: boolean = false + ): arkts.ClassProperty { + const newType: arkts.TypeNode | undefined = property.typeAnnotation?.clone(); + if (needMemo && findCanAddMemoFromTypeAnnotation(newType)) { + addMemoAnnotation(newType); + } + const newProperty = arkts.factory.createClassProperty( + arkts.factory.createIdentifier(name), + undefined, + !!stageManagementType ? factory.createStageManagementType(stageManagementType, property) : newType, + modifiers, + false + ); + return arkts.classPropertySetOptional(newProperty, true); + } + + static createStageManagementType( + stageManagementType: StateManagementTypes, + property: arkts.ClassProperty + ): arkts.ETSTypeReference { + collectStateManagementTypeSource(stageManagementType); + collectStateManagementTypeImport(stageManagementType); + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(stageManagementType), + arkts.factory.createTSTypeParameterInstantiation([ + property.typeAnnotation ? property.typeAnnotation.clone() : arkts.factory.createETSUndefinedType(), + ]) + ) + ); + } + + static createWatchMembers(): arkts.AstNode[] { + const subscribedWatches: arkts.ClassProperty = arkts.factory.createClassProperty( + arkts.factory.createIdentifier('subscribedWatches'), + arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.SUBSCRIBED_WATCHES) + ) + ), + [] + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.SUBSCRIBED_WATCHES) + ) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + collectStateManagementTypeSource(StateManagementTypes.SUBSCRIBED_WATCHES); + collectStateManagementTypeImport(StateManagementTypes.SUBSCRIBED_WATCHES); + + const addWatchSubscriber = factory.createWatchMethod( + 'addWatchSubscriber', + arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID, + 'watchId', + StateManagementTypes.WATCH_ID_TYPE, + false + ); + const removeWatchSubscriber = factory.createWatchMethod( + 'removeWatchSubscriber', + arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BOOLEAN, + 'watchId', + StateManagementTypes.WATCH_ID_TYPE, + true + ); + collectStateManagementTypeSource(StateManagementTypes.WATCH_ID_TYPE); + collectStateManagementTypeImport(StateManagementTypes.WATCH_ID_TYPE); + + const executeOnSubscribingWatches = factory.createWatchMethod( + 'executeOnSubscribingWatches', + arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID, + 'propertyName', + 'string', + false + ); + + return [subscribedWatches, addWatchSubscriber, removeWatchSubscriber, executeOnSubscribingWatches]; + } + + static createWatchMethod( + methodName: string, + returnType: arkts.Es2pandaPrimitiveType, + paramName: string, + paramType: string, + isReturnStatement: boolean + ): arkts.MethodDefinition { + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + arkts.factory.createIdentifier(methodName), + arkts.factory.createScriptFunction( + arkts.factory.createBlock([ + isReturnStatement + ? arkts.factory.createReturnStatement( + arkts.factory.createCallExpression( + factory.thisSubscribedWatchesMember(methodName), + undefined, + [arkts.factory.createIdentifier(paramName)] + ) + ) + : arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + factory.thisSubscribedWatchesMember(methodName), + undefined, + [arkts.factory.createIdentifier(paramName)] + ) + ), + ]), + arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + paramName, + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(paramType)) + ) + ), + undefined + ), + ], + arkts.factory.createPrimitiveType(returnType), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + } + + static thisSubscribedWatchesMember(member: string): arkts.MemberExpression { + return arkts.factory.createMemberExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('subscribedWatches'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.factory.createIdentifier(member), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); + } + + /** + * add `@memo` to the `@Builder` methods in class. + */ + static addMemoToBuilderClassMethod(method: arkts.MethodDefinition): arkts.MethodDefinition { + if (hasDecorator(method, DecoratorNames.BUILDER)) { + removeDecorator(method, DecoratorNames.BUILDER); + addMemoAnnotation(method.scriptFunction); + } + return method; + } + + static createStorageLinkStateValue( + property: arkts.ClassProperty, + localStorageporpValueStr: string + ): arkts.MemberExpression { + return arkts.factory.createMemberExpression( + arkts.factory.createCallExpression( + arkts.factory.createIdentifier(StateManagementTypes.STORAGE_LINK_STATE), + property.typeAnnotation ? [property.typeAnnotation] : [], + [ + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('_entry_local_storage_'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.factory.createStringLiteral(localStorageporpValueStr), + property.value ?? arkts.factory.createUndefinedLiteral(), + ] + ), + arkts.factory.createIdentifier('value'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); + } + + /** + * wrap interface non-undefined property type `T` to ``. + */ + static wrapInterfacePropertyType(type: arkts.TypeNode, wrapTypeName: StateManagementTypes): arkts.TypeNode { + if (arkts.isETSUnionType(type)) { + return arkts.factory.updateUnionType( + type, + type.types.map((t) => factory.wrapInterfacePropertyType(t, wrapTypeName)) + ); + } else if (!arkts.isETSUndefinedType(type)) { + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(wrapTypeName), + arkts.factory.createTSTypeParameterInstantiation([(type as arkts.TypeNode).clone()]) + ) + ); + } + return type; + } + + /** + * wrap interface property parameter that has non-undefined type `T` to ``. + */ + static wrapInterfacePropertyParamExpr( + param: arkts.Expression, + wrapTypeName: StateManagementTypes + ): arkts.Expression { + if (!arkts.isEtsParameterExpression(param)) { + return param; + } + if (!param.type || !arkts.isETSUnionType(param.type)) { + return param; + } + return arkts.factory.updateParameterDeclaration( + param, + arkts.factory.createIdentifier( + param.identifier.name, + factory.wrapInterfacePropertyType(param.type, wrapTypeName) + ), + param.initializer + ); + } + + static wrapStateManagementTypeToType( + type: arkts.TypeNode | undefined, + decoratorName: DecoratorNames + ): arkts.TypeNode | undefined { + let newType: arkts.TypeNode | undefined; + let wrapTypeName: StateManagementTypes | undefined; + if (!!type && !!(wrapTypeName = decoratorTypeMap.get(decoratorName))) { + collectStateManagementTypeSource(wrapTypeName); + newType = factory.wrapInterfacePropertyType(type, wrapTypeName); + collectStateManagementTypeImport(wrapTypeName); + } + return newType; + } + + static wrapStateManagementTypeToParam( + param: arkts.Expression | undefined, + decoratorName: DecoratorNames + ): arkts.Expression | undefined { + let newParam: arkts.Expression | undefined; + let wrapTypeName: StateManagementTypes | undefined; + if (!!param && !!(wrapTypeName = decoratorTypeMap.get(decoratorName))) { + collectStateManagementTypeSource(wrapTypeName); + newParam = factory.wrapInterfacePropertyParamExpr(param, wrapTypeName); + collectStateManagementTypeImport(wrapTypeName); + } + return newParam; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to ` | undefined`, where `` is getting from `DecoratorName`; + * + * @param method expecting getter with decorator annotation and a setter with decorator annotation in the overloads. + */ + static wrapStateManagementTypeToMethodInInterface( + method: arkts.MethodDefinition, + decorator: DecoratorNames + ): arkts.MethodDefinition { + if (method.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET) { + const newType: arkts.TypeNode | undefined = factory.wrapStateManagementTypeToType( + method.scriptFunction.returnTypeAnnotation, + decorator + ); + const newOverLoads = method.overloads.map((overload) => { + if (arkts.isMethodDefinition(overload)) { + return factory.wrapStateManagementTypeToMethodInInterface(overload, decorator); + } + return overload; + }); + method.setOverloads(newOverLoads); + removeDecorator(method, decorator); + if (!!newType) { + method.scriptFunction.setReturnTypeAnnotation(newType); + } + } else if (method.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET) { + const newParam: arkts.Expression | undefined = factory.wrapStateManagementTypeToParam( + method.scriptFunction.params.at(0), + decorator + ); + removeDecorator(method, decorator); + if (!!newParam) { + return UIFactory.updateMethodDefinition(method, { function: { params: [newParam] } }); + } + } + return method; + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to ` | undefined`, where `` is getting from `DecoratorName`; + * + * @param property expecting property with decorator annotation. + */ + static wrapStateManagementTypeToPropertyInInterface( + property: arkts.ClassProperty, + decorator: DecoratorNames + ): arkts.ClassProperty { + const newType: arkts.TypeNode | undefined = factory.wrapStateManagementTypeToType( + property.typeAnnotation, + decorator + ); + removeDecorator(property, decorator); + if (!!newType) { + property.setTypeAnnotation(newType); + } + return property; + } } diff --git a/arkui-plugins/ui-plugins/property-translators/index.ts b/arkui-plugins/ui-plugins/property-translators/index.ts index 013eaa286..7695a7f96 100644 --- a/arkui-plugins/ui-plugins/property-translators/index.ts +++ b/arkui-plugins/ui-plugins/property-translators/index.ts @@ -15,71 +15,118 @@ import * as arkts from '@koalaui/libarkts'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, PropertyTranslator } from './base'; import { DecoratorNames, hasDecorator } from './utils'; -import { StateTranslator } from './state'; -import { PropTranslator } from './prop'; -import { StorageLinkTranslator } from './storagelink'; -import { LocalStorageLinkTranslator } from './localstoragelink'; -import { LinkTranslator } from './link'; -import { ObjectLinkTranslator } from './objectlink'; -import { LocalStoragePropTranslator } from './localstorageprop'; -import { regularPropertyTranslator } from './regularProperty'; +import { StateInterfaceTranslator, StateTranslator } from './state'; +import { PropInterfaceTranslator, PropTranslator } from './prop'; +import { StorageLinkInterfaceTranslator, StorageLinkTranslator } from './storagelink'; +import { LocalStorageLinkInterfaceTranslator, LocalStorageLinkTranslator } from './localstoragelink'; +import { LinkInterfaceTranslator, LinkTranslator } from './link'; +import { ObjectLinkInterfaceTranslator, ObjectLinkTranslator } from './objectlink'; +import { LocalStoragePropInterfaceTranslator, LocalStoragePropTranslator } from './localstorageprop'; +import { RegularInterfaceTranslator, RegularPropertyTranslator } from './regularProperty'; import { staticPropertyTranslator } from './staticProperty'; -import { isStatic } from '../utils'; -import { StoragePropTranslator } from './storageProp'; -import { ConsumeTranslator } from './consume'; -import { ProvideTranslator } from './provide'; -import { BuilderParamTranslator } from './builderParam'; +import { CustomComponentInfo, isStatic } from '../utils'; +import { StoragePropInterfaceTranslator, StoragePropTranslator } from './storageProp'; +import { ConsumeInterfaceTranslator, ConsumeTranslator } from './consume'; +import { ProvideInterfaceTranslator, ProvideTranslator } from './provide'; +import { BuilderParamInterfaceTranslator, BuilderParamTranslator } from './builderParam'; import { ObservedTrackTranslator } from './observedTrack'; -import { ClassScopeInfo } from 'ui-plugins/checked-transformer'; +import { ClassScopeInfo } from './types'; -export { PropertyTranslator }; +export { PropertyTranslator, InterfacePropertyTranslator }; +export type { ClassScopeInfo }; -export function classifyProperty(member: arkts.AstNode, structName: string): PropertyTranslator | undefined { - if (!arkts.isClassProperty(member)) return undefined; - if (isStatic(member)) return new staticPropertyTranslator(member, structName); +export function classifyProperty( + property: arkts.AstNode, + structInfo: CustomComponentInfo +): PropertyTranslator | undefined { + if (!arkts.isClassProperty(property)) return undefined; + if (isStatic(property)) return new staticPropertyTranslator({ property, structInfo }); - if (hasDecorator(member, DecoratorNames.STATE)) { - return new StateTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.STATE)) { + return new StateTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.STORAGE_LINK)) { - return new StorageLinkTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.STORAGE_LINK)) { + return new StorageLinkTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.LOCAL_STORAGE_LINK)) { - return new LocalStorageLinkTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.LOCAL_STORAGE_LINK)) { + return new LocalStorageLinkTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.LINK)) { - return new LinkTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.LINK)) { + return new LinkTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.OBJECT_LINK)) { - return new ObjectLinkTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.OBJECT_LINK)) { + return new ObjectLinkTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.LOCAL_STORAGE_PROP)) { - return new LocalStoragePropTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.LOCAL_STORAGE_PROP)) { + return new LocalStoragePropTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.STORAGE_PROP)) { - return new StoragePropTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.STORAGE_PROP)) { + return new StoragePropTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.PROP)) { - return new PropTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.PROP)) { + return new PropTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.PROVIDE)) { - return new ProvideTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.PROVIDE)) { + return new ProvideTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.CONSUME)) { - return new ConsumeTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.CONSUME)) { + return new ConsumeTranslator({ property, structInfo }); } - if (hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { - return new BuilderParamTranslator(member, structName); + if (hasDecorator(property, DecoratorNames.BUILDER_PARAM)) { + return new BuilderParamTranslator({ property, structInfo }); } - return new regularPropertyTranslator(member, structName); + return new RegularPropertyTranslator({ property, structInfo }); } -export function classifyObservedTrack(member: arkts.AstNode, classScopeInfo: ClassScopeInfo): ObservedTrackTranslator | undefined { +export function classifyPropertyInInterface(property: arkts.AstNode): InterfacePropertyTranslator | undefined { + if (StateInterfaceTranslator.canBeTranslated(property)) { + return new StateInterfaceTranslator({ property }); + } + if (LinkInterfaceTranslator.canBeTranslated(property)) { + return new LinkInterfaceTranslator({ property }); + } + if (PropInterfaceTranslator.canBeTranslated(property)) { + return new PropInterfaceTranslator({ property }); + } + if (ProvideInterfaceTranslator.canBeTranslated(property)) { + return new ProvideInterfaceTranslator({ property }); + } + if (ConsumeInterfaceTranslator.canBeTranslated(property)) { + return new ConsumeInterfaceTranslator({ property }); + } + if (StoragePropInterfaceTranslator.canBeTranslated(property)) { + return new StoragePropInterfaceTranslator({ property }); + } + if (StorageLinkInterfaceTranslator.canBeTranslated(property)) { + return new StorageLinkInterfaceTranslator({ property }); + } + if (BuilderParamInterfaceTranslator.canBeTranslated(property)) { + return new BuilderParamInterfaceTranslator({ property }); + } + if (LocalStoragePropInterfaceTranslator.canBeTranslated(property)) { + return new LocalStoragePropInterfaceTranslator({ property }); + } + if (LocalStorageLinkInterfaceTranslator.canBeTranslated(property)) { + return new LocalStorageLinkInterfaceTranslator({ property }); + } + if (ObjectLinkInterfaceTranslator.canBeTranslated(property)) { + return new ObjectLinkInterfaceTranslator({ property }); + } + if (RegularInterfaceTranslator.canBeTranslated(property)) { + return new RegularInterfaceTranslator({ property }); + } + return undefined; +} + +export function classifyObservedTrack( + member: arkts.AstNode, + classScopeInfo: ClassScopeInfo +): ObservedTrackTranslator | undefined { if (!arkts.isClassProperty(member)) { return undefined; } return new ObservedTrackTranslator(member, classScopeInfo); -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/property-translators/link.ts b/arkui-plugins/ui-plugins/property-translators/link.ts index eafd90c95..f3c903310 100644 --- a/arkui-plugins/ui-plugins/property-translators/link.ts +++ b/arkui-plugins/ui-plugins/property-translators/link.ts @@ -21,32 +21,34 @@ import { createSetter2, generateThisBacking, generateGetOrSetCall, - judgeIfAddWatchFunc, + StateManagementTypes, + collectStateManagementTypeSource, + collectStateManagementTypeImport, + hasDecorator, + DecoratorNames, + PropertyCache, } from './utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; -import { createOptionalClassProperty } from '../utils'; export class LinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } generateInitializeStruct(newName: string, originalName: string) { @@ -61,13 +63,19 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true) ), ]; - judgeIfAddWatchFunc(args, this.property); + factory.judgeIfAddWatchFunc(args, this.property); + collectStateManagementTypeSource(StateManagementTypes.LINK_DECORATED); + collectStateManagementTypeImport(StateManagementTypes.LINK_DECORATED); const consequent = arkts.BlockStatement.createBlockStatement([ arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( generateThisBacking(newName, false, false), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.createNewDecoratedInstantiate('LinkDecoratedVariable', this.property.typeAnnotation, args) + factory.createNewDecoratedInstantiate( + StateManagementTypes.LINK_DECORATED, + this.property.typeAnnotation, + args + ) ) ), ]); @@ -76,10 +84,10 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( + const field: arkts.ClassProperty = factory.createOptionalClassProperty( newName, this.property, - 'LinkDecoratedVariable', + StateManagementTypes.LINK_DECORATED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); @@ -117,3 +125,45 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon return createSetter2(originalName, typeAnnotation, statement); } } + +export class LinkInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.LINK)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.LINK)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `DecoratedV1VariableBase | undefined`. + * + * @param method expecting getter with `@Link` and a setter with `@Link` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.LINK); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `DecoratedV1VariableBase | undefined`. + * + * @param property expecting property with `@Link`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.LINK); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts index a050e9852..b61615400 100755 --- a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts @@ -16,9 +16,18 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { DecoratorNames, generateToRecord } from './utils'; +import { + collectStateManagementTypeImport, + collectStateManagementTypeSource, + DecoratorNames, + generateToRecord, + hasDecorator, + PropertyCache, + StateManagementTypes, +} from './utils'; +import { factory } from './factory'; function getLocalStorageLinkValueStr(node: arkts.AstNode): string | undefined { if (!arkts.isClassProperty(node) || !node.value) return undefined; @@ -54,31 +63,65 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field = factory.createOptionalClassProperty( + newName, + this.property, + StateManagementTypes.MUTABLE_STATE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); + + const member = arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + ); + const thisValue: arkts.MemberExpression = arkts.factory.createMemberExpression( + member, + arkts.factory.createIdentifier('value'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisValue + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisValue + ); + return [field, getter, setter]; } generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const localStorageLinkValueStr: string | undefined = getLocalStorageLinkValueInAnnotation(this.property); if (!localStorageLinkValueStr) { - throw new Error('LocalStorageLink required only one value!!'); // TODO: replace this with proper error message. + throw new Error('LocalStorageLink required only one value!!'); } const call = arkts.factory.createCallExpression( - arkts.factory.createIdentifier('StorageLinkState'), + arkts.factory.createIdentifier(StateManagementTypes.STORAGE_LINK_STATE), this.property.typeAnnotation ? [this.property.typeAnnotation] : [], [ arkts.factory.createMemberExpression( @@ -92,6 +135,8 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In this.property.value ?? arkts.factory.createUndefinedLiteral(), ] ); + collectStateManagementTypeSource(StateManagementTypes.STORAGE_LINK_STATE); + collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_STATE); return arkts.factory.createAssignmentExpression( arkts.factory.createMemberExpression( @@ -106,3 +151,47 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In ); } } + +export class LocalStorageLinkInterfaceTranslator< + T extends InterfacePropertyTypes +> extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.LOCAL_STORAGE_LINK)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.LOCAL_STORAGE_LINK)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `MutableState | undefined`. + * + * @param method expecting getter with `@LocalStorageLink` and a setter with `@LocalStorageLink` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.LOCAL_STORAGE_LINK); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `MutableState | undefined`. + * + * @param property expecting property with `@LocalStorageLink`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.LOCAL_STORAGE_LINK); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts index d20d982cd..fb528539e 100644 --- a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts @@ -15,10 +15,19 @@ import * as arkts from '@koalaui/libarkts'; -import { DecoratorNames, generateToRecord } from './utils'; -import { PropertyTranslator } from './base'; +import { + collectStateManagementTypeImport, + collectStateManagementTypeSource, + DecoratorNames, + generateToRecord, + hasDecorator, + PropertyCache, + StateManagementTypes, +} from './utils'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; +import { factory } from './factory'; function getLocalStorageporpValueStr(node: arkts.AstNode): string | undefined { if (!arkts.isClassProperty(node) || !node.value) return undefined; @@ -54,29 +63,63 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); const updateStruct: arkts.AstNode = this.generateUpdateStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - currentStructInfo.updateBody.push(updateStruct); - - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectUpdateStruct(this.structInfo.name, [updateStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } + } + + translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { + const field = factory.createOptionalClassProperty( + newName, + this.property, + StateManagementTypes.SYNCED_PROPERTY, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); + const member = arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + ); + const thisValue: arkts.MemberExpression = arkts.factory.createMemberExpression( + member, + arkts.factory.createIdentifier('value'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ); + + const getter: arkts.MethodDefinition = this.translateGetter( + originalName, + this.property.typeAnnotation, + thisValue + ); + const setter: arkts.MethodDefinition = this.translateSetter( + originalName, + this.property.typeAnnotation, + thisValue + ); + return [field, getter, setter]; } generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const localStorageporpValueStr: string | undefined = getLocalStorageporpValueInAnnotation(this.property); if (!localStorageporpValueStr) { - throw new Error('LocalStorageProp required only one value!!'); // TODO: replace this with proper error message. + throw new Error('LocalStorageProp required only one value!!'); } const insideMember = arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), @@ -86,7 +129,7 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In false ); const binaryItem = arkts.factory.createCallExpression( - arkts.factory.createIdentifier('StorageLinkState'), + arkts.factory.createIdentifier(StateManagementTypes.STORAGE_LINK_STATE), this.property.typeAnnotation ? [this.property.typeAnnotation] : [], [ insideMember, @@ -94,8 +137,10 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In this.property.value ?? arkts.factory.createUndefinedLiteral(), ] ); + collectStateManagementTypeSource(StateManagementTypes.STORAGE_LINK_STATE); + collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_STATE); const call = arkts.factory.createCallExpression( - arkts.factory.createIdentifier('propState'), + arkts.factory.createIdentifier(StateManagementTypes.PROP_STATE), this.property.typeAnnotation ? [this.property.typeAnnotation] : [], [ arkts.factory.createMemberExpression( @@ -107,6 +152,8 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In ), ] ); + collectStateManagementTypeSource(StateManagementTypes.PROP_STATE); + collectStateManagementTypeImport(StateManagementTypes.PROP_STATE); return arkts.factory.createAssignmentExpression( arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), @@ -123,31 +170,11 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In generateUpdateStruct(newName: string, originalName: string): arkts.AstNode { const localStorageporpValueStr: string | undefined = getLocalStorageporpValueInAnnotation(this.property); if (!localStorageporpValueStr) { - throw new Error('StorageLink required only one value!!'); // TODO: replace this with proper error message. + throw new Error('StorageLink required only one value!!'); } - - const StorageLinkStateValue = arkts.factory.createMemberExpression( - arkts.factory.createCallExpression( - arkts.factory.createIdentifier('StorageLinkState'), - this.property.typeAnnotation ? [this.property.typeAnnotation] : [], - [ - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('_entry_local_storage_'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createStringLiteral(localStorageporpValueStr), - this.property.value ?? arkts.factory.createUndefinedLiteral(), - ] - ), - arkts.factory.createIdentifier('value'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ); - + const StorageLinkStateValue = factory.createStorageLinkStateValue(this.property, localStorageporpValueStr); + collectStateManagementTypeSource(StateManagementTypes.STORAGE_LINK_STATE); + collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_STATE); const test = arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), arkts.factory.createIdentifier(newName), @@ -155,7 +182,6 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In false, false ); - const consequent = arkts.BlockStatement.createBlockStatement([ arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( @@ -171,7 +197,50 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In ) ), ]); - return arkts.factory.createExpressionStatement(arkts.factory.createIfStatement(test, consequent)); } } + +export class LocalStoragePropInterfaceTranslator< + T extends InterfacePropertyTypes +> extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `SyncedProperty | undefined`. + * + * @param method expecting getter with `@LocalStorageProp` and a setter with `@LocalStorageProp` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.LOCAL_STORAGE_PROP); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `SyncedProperty | undefined`. + * + * @param property expecting property with `@LocalStorageProp`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.LOCAL_STORAGE_PROP); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/objectlink.ts b/arkui-plugins/ui-plugins/property-translators/objectlink.ts index 8da1283a2..5f7ee7d69 100644 --- a/arkui-plugins/ui-plugins/property-translators/objectlink.ts +++ b/arkui-plugins/ui-plugins/property-translators/objectlink.ts @@ -22,39 +22,35 @@ import { generateThisBacking, generateToRecord, hasDecorator, - judgeIfAddWatchFunc, + PropertyCache, + StateManagementTypes, } from './utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; -import { createOptionalClassProperty } from '../utils'; export class ObjectLinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); if (!this.ifObservedDecoratedClass()) { - throw new Error('@ObjectLink decorated property only accepts @Observed decorated class instance'); // TODO: replace this with proper error message. + throw new Error('@ObjectLink decorated property only accepts @Observed decorated class instance'); } - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); const updateStruct: arkts.AstNode = this.generateUpdateStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - currentStructInfo.updateBody.push(updateStruct); - - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectUpdateStruct(this.structInfo.name, [updateStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { @@ -66,7 +62,7 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali ); const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), initializers]; - judgeIfAddWatchFunc(args, this.property); + factory.judgeIfAddWatchFunc(args, this.property); const newClass = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( @@ -117,10 +113,10 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( + const field: arkts.ClassProperty = factory.createOptionalClassProperty( newName, this.property, - 'ObjectLinkDecoratedVariable', + StateManagementTypes.OBJECT_LINK_DECORATED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); @@ -151,3 +147,45 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali return false; } } + +export class ObjectLinkInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.OBJECT_LINK)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.OBJECT_LINK)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `ObjectLinkDecoratedVariable | undefined`. + * + * @param method expecting getter with `@ObjectLink` and a setter with `@ObjectLink` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.OBJECT_LINK); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `ObjectLinkDecoratedVariable | undefined`. + * + * @param property expecting property with `@ObjectLink`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.OBJECT_LINK); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts index c83004733..0e84301aa 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -15,14 +15,27 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, hasDecorator } from './utils'; -import { ClassScopeInfo } from 'ui-plugins/checked-transformer'; +import { + collectStateManagementTypeImport, + collectStateManagementTypeSource, + DecoratorNames, + hasDecorator, + StateManagementTypes, +} from './utils'; +import { ClassScopeInfo } from './types'; export class ObservedTrackTranslator { - constructor(protected property: arkts.ClassProperty, protected classScopeInfo: ClassScopeInfo) {} + protected property: arkts.ClassProperty; + protected classScopeInfo: ClassScopeInfo; + private hasImplement: boolean; + private isTracked: boolean; - private hasImplement: boolean = expectName(this.property.key).startsWith(''); - private isTracked: boolean = hasDecorator(this.property, DecoratorNames.TRACK); + constructor(property: arkts.ClassProperty, classScopeInfo: ClassScopeInfo) { + this.property = property; + this.classScopeInfo = classScopeInfo; + this.hasImplement = expectName(this.property.key).startsWith(''); + this.isTracked = hasDecorator(this.property, DecoratorNames.TRACK); + } translateMember(): arkts.AstNode[] { if (!this.isTracked && (this.classScopeInfo.classHasTrack || !this.classScopeInfo.isObserved)) { @@ -67,11 +80,9 @@ export class ObservedTrackTranslator { createGetter(originalName: string, newName: string, properyIsClass: boolean): arkts.MethodDefinition { const ifRefDepth: arkts.IfStatement = this.getterIfRefDepth(originalName); const returnMember: arkts.ReturnStatement = this.getterReturnMember(properyIsClass, newName); - const setObservationDepth = this.getterSetObservationDepth(newName); - const body = arkts.factory.createBlock([ ifRefDepth, - ...(properyIsClass ? [setObservationDepth] : []), + ...(properyIsClass ? [this.getterSetObservationDepth(newName)] : []), returnMember, ]); @@ -85,7 +96,7 @@ export class ObservedTrackTranslator { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, arkts.factory.createIdentifier(originalName), - arkts.factory.createFunctionExpression(scriptFunction), + scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -109,7 +120,7 @@ export class ObservedTrackTranslator { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, arkts.factory.createIdentifier(originalName), - arkts.factory.createFunctionExpression(scriptFunction), + scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -160,9 +171,7 @@ export class ObservedTrackTranslator { originGetter, originGetter.kind, newGetter.name, - arkts.factory.createFunctionExpression( - newGetter.scriptFunction.addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) - ), + newGetter.scriptFunction.addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD), originGetter.modifiers, false ); @@ -170,11 +179,9 @@ export class ObservedTrackTranslator { originSetter, originSetter.kind, newSetter.name, - arkts.factory.createFunctionExpression( - newSetter.scriptFunction - .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_OVERLOAD) - .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) - ), + newSetter.scriptFunction + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_OVERLOAD) + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD), originSetter.modifiers, false ); @@ -186,13 +193,15 @@ export class ObservedTrackTranslator { } propertyIsClassField(newName: string): arkts.ClassProperty { + collectStateManagementTypeSource(StateManagementTypes.BACKING_VALUE); + collectStateManagementTypeImport(StateManagementTypes.BACKING_VALUE); return arkts.factory.createClassProperty( arkts.factory.createIdentifier(newName), this.property.value ? arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('BackingValue'), + arkts.factory.createIdentifier(StateManagementTypes.BACKING_VALUE), arkts.factory.createTSTypeParameterInstantiation( this.property.typeAnnotation ? [this.property.typeAnnotation] : [] ) @@ -203,7 +212,7 @@ export class ObservedTrackTranslator { : undefined, arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('BackingValue'), + arkts.factory.createIdentifier(StateManagementTypes.BACKING_VALUE), arkts.factory.createTSTypeParameterInstantiation( this.property.typeAnnotation ? [this.property.typeAnnotation] : [] ) @@ -215,16 +224,22 @@ export class ObservedTrackTranslator { } metaField(originalName: string): arkts.ClassProperty { + collectStateManagementTypeSource(StateManagementTypes.MUTABLE_STATE_META); + collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); return arkts.factory.createClassProperty( arkts.factory.createIdentifier(`__meta_${originalName}`), arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) + ) ), [arkts.factory.createStringLiteral('@Track')] ), arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) + ) ), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, false @@ -271,21 +286,27 @@ export class ObservedTrackTranslator { } getterSetObservationDepth(newName: string): arkts.ExpressionStatement { + collectStateManagementTypeSource(StateManagementTypes.SET_OBSERVATION_DEPTH); + collectStateManagementTypeImport(StateManagementTypes.SET_OBSERVATION_DEPTH); return arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(arkts.factory.createIdentifier('setObservationDepth'), undefined, [ - this.genThisBackingValue(newName), - arkts.factory.createBinaryExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('_permissibleAddRefDepth'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false + arkts.factory.createCallExpression( + arkts.factory.createIdentifier(StateManagementTypes.SET_OBSERVATION_DEPTH), + undefined, + [ + this.genThisBackingValue(newName), + arkts.factory.createBinaryExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('_permissibleAddRefDepth'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.factory.createNumericLiteral(1), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_MINUS ), - arkts.factory.createNumericLiteral(1), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_MINUS - ), - ]) + ] + ) ); } diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts index b8bb3d991..f1b09a65d 100644 --- a/arkui-plugins/ui-plugins/property-translators/prop.ts +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -21,12 +21,16 @@ import { createSetter2, generateGetOrSetCall, generateThisBacking, - judgeIfAddWatchFunc, + StateManagementTypes, + collectStateManagementTypeSource, + collectStateManagementTypeImport, + hasDecorator, + DecoratorNames, + PropertyCache, } from './utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; -import { createOptionalClassProperty } from '../utils'; import { factory } from './factory'; export class PropTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { @@ -34,29 +38,27 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const mutableThis: arkts.Expression = generateThisBacking(newName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); const updateStruct: arkts.AstNode = this.generateUpdateStruct(mutableThis, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - currentStructInfo.updateBody.push(updateStruct); - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectUpdateStruct(this.structInfo.name, [updateStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( + const field: arkts.ClassProperty = factory.createOptionalClassProperty( newName, this.property, - 'PropDecoratedVariable', + StateManagementTypes.PROP_DECORATED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); @@ -113,11 +115,13 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon false ), ]; - judgeIfAddWatchFunc(args, this.property); + factory.judgeIfAddWatchFunc(args, this.property); + collectStateManagementTypeSource(StateManagementTypes.PROP_DECORATED); + collectStateManagementTypeImport(StateManagementTypes.PROP_DECORATED); const right = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('PropDecoratedVariable'), + arkts.factory.createIdentifier(StateManagementTypes.PROP_DECORATED), arkts.factory.createTSTypeParameterInstantiation( this.property.typeAnnotation ? [this.property.typeAnnotation] : [] ) @@ -165,3 +169,45 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon ); } } + +export class PropInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.PROP)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.PROP)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `PropDecoratedVariable | undefined`. + * + * @param method expecting getter with `@Prop` and a setter with `@Prop` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.PROP); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `PropDecoratedVariable | undefined`. + * + * @param property expecting property with `@Prop`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.PROP); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/provide.ts b/arkui-plugins/ui-plugins/property-translators/provide.ts index 144d1239a..b084201c8 100644 --- a/arkui-plugins/ui-plugins/property-translators/provide.ts +++ b/arkui-plugins/ui-plugins/property-translators/provide.ts @@ -16,44 +16,45 @@ import * as arkts from '@koalaui/libarkts'; import { - generateToRecord, createGetter, + generateToRecord, + StateManagementTypes, createSetter2, generateThisBacking, generateGetOrSetCall, getValueInProvideAnnotation, ProvideOptions, + hasDecorator, + DecoratorNames, + PropertyCache, } from './utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; -import { createOptionalClassProperty } from '../utils'; import { factory } from './factory'; export class ProvideTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); - currentStructInfo.initializeBody.push(initializeStruct); - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( + const field: arkts.ClassProperty = factory.createOptionalClassProperty( newName, this.property, - 'ProvideDecoratedVariable', + StateManagementTypes.PROVIDE_DECORATED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); @@ -103,3 +104,45 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer return arkts.factory.createExpressionStatement(assign); } } + +export class ProvideInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.PROVIDE)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.PROVIDE)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `ProvideDecoratedVariable | undefined`. + * + * @param method expecting getter with `@Provide` and a setter with `@Provide` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.PROVIDE); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `ProvideDecoratedVariable | undefined`. + * + * @param property expecting property with `@Provide`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.PROVIDE); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts index d89b471e7..a059055f4 100644 --- a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts +++ b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts @@ -15,37 +15,34 @@ import * as arkts from '@koalaui/libarkts'; -import { createGetter, generateToRecord, generateThisBacking, createSetter2 } from './utils'; -import { PropertyTranslator } from './base'; +import { createGetter, generateToRecord, generateThisBacking, createSetter2, PropertyCache } from './utils'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { createOptionalClassProperty } from '../utils'; import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; -export class regularPropertyTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { +export class RegularPropertyTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( + const field: arkts.ClassProperty = factory.createOptionalClassProperty( newName, this.property, - '', + undefined, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, false); @@ -53,7 +50,7 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini arkts.factory.createAssignmentExpression( thisValue, arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier('value'), + arkts.factory.createIdentifier('value') ) ); const getter: arkts.MethodDefinition = this.translateGetter( @@ -103,3 +100,13 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini return arkts.factory.createExpressionStatement(assign); } } + +export class RegularInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + return true; + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts index 667fabac7..b072d83e9 100644 --- a/arkui-plugins/ui-plugins/property-translators/state.ts +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -21,38 +21,44 @@ import { createSetter2, generateThisBacking, generateGetOrSetCall, - judgeIfAddWatchFunc, + hasDecorator, + DecoratorNames, + removeDecorator, + decoratorTypeMap, + StateManagementTypes, + collectStateManagementTypeImport, + collectStateManagementTypeSource, + PropertyCache, } from './utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; -import { createOptionalClassProperty } from '../utils'; +import { CustomComponentNames } from '../utils'; import { factory } from './factory'; +import { factory as uiFactory } from '../ui-factory'; export class StateTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( + const field: arkts.ClassProperty = factory.createOptionalClassProperty( newName, this.property, - 'StateDecoratedVariable', + StateManagementTypes.STATE_DECORATED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); @@ -93,18 +99,20 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const binaryItem = arkts.factory.createBinaryExpression( factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), + arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), originalName ), this.property.value ?? arkts.factory.createUndefinedLiteral(), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ); const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), binaryItem]; - judgeIfAddWatchFunc(args, this.property); + factory.judgeIfAddWatchFunc(args, this.property); + collectStateManagementTypeSource(StateManagementTypes.STATE_DECORATED); + collectStateManagementTypeImport(StateManagementTypes.STATE_DECORATED); const right = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('StateDecoratedVariable'), + arkts.factory.createIdentifier(StateManagementTypes.STATE_DECORATED), arkts.factory.createTSTypeParameterInstantiation( this.property.typeAnnotation ? [this.property.typeAnnotation] : [] ) @@ -120,3 +128,45 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo return arkts.factory.createExpressionStatement(assign); } } + +export class StateInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.STATE)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.STATE)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `StateDecoratedVariable | undefined`. + * + * @param method expecting getter with `@State` and a setter with `@State` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.STATE); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `StateDecoratedVariable | undefined`. + * + * @param property expecting property with `@State`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.STATE); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/storageProp.ts b/arkui-plugins/ui-plugins/property-translators/storageProp.ts index 2693f749d..d4861e5b2 100644 --- a/arkui-plugins/ui-plugins/property-translators/storageProp.ts +++ b/arkui-plugins/ui-plugins/property-translators/storageProp.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { DecoratorNames, @@ -25,9 +25,13 @@ import { createSetter2, generateThisBacking, generateGetOrSetCall, - judgeIfAddWatchFunc, + StateManagementTypes, + collectStateManagementTypeSource, + collectStateManagementTypeImport, + hasDecorator, + PropertyCache, } from './utils'; -import { createOptionalClassProperty } from '../utils'; +import { factory } from './factory'; function getStoragePropValueStr(node: arkts.AstNode): string | undefined { if (!arkts.isClassProperty(node) || !node.value) return undefined; @@ -63,27 +67,23 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const storagePropValueStr: string | undefined = getStoragePropValueInAnnotation(this.property); if (!storagePropValueStr) { - throw new Error('StorageProp required only one value!!'); // TODO: replace this with proper error message. + throw new Error('StorageProp required only one value!!'); } const args: arkts.Expression[] = [ @@ -91,12 +91,13 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial arkts.factory.create1StringLiteral(originalName), this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; - judgeIfAddWatchFunc(args, this.property); - + factory.judgeIfAddWatchFunc(args, this.property); + collectStateManagementTypeSource(StateManagementTypes.STORAGE_PROP_DECORATED); + collectStateManagementTypeImport(StateManagementTypes.STORAGE_PROP_DECORATED); const newClass = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('StoragePropDecoratedVariable'), + arkts.factory.createIdentifier(StateManagementTypes.STORAGE_PROP_DECORATED), arkts.factory.createTSTypeParameterInstantiation( this.property.typeAnnotation ? [this.property.typeAnnotation] : [] ) @@ -119,10 +120,10 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field = createOptionalClassProperty( + const field = factory.createOptionalClassProperty( newName, this.property, - 'StoragePropDecoratedVariable', + StateManagementTypes.STORAGE_PROP_DECORATED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); @@ -159,3 +160,45 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial return createSetter2(originalName, typeAnnotation, statement); } } + +export class StoragePropInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.STORAGE_PROP)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.STORAGE_PROP)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `StoragePropDecoratedVariable | undefined`. + * + * @param method expecting getter with `@StorageProp` and a setter with `@StorageProp` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.STORAGE_PROP); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `StoragePropDecoratedVariable | undefined`. + * + * @param property expecting property with `@StorageProp`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.STORAGE_PROP); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/storagelink.ts b/arkui-plugins/ui-plugins/property-translators/storagelink.ts index efd83e9d6..dadb5b297 100644 --- a/arkui-plugins/ui-plugins/property-translators/storagelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/storagelink.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { PropertyTranslator } from './base'; +import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { DecoratorNames, @@ -25,9 +25,13 @@ import { createSetter2, generateThisBacking, generateGetOrSetCall, - judgeIfAddWatchFunc, + StateManagementTypes, + collectStateManagementTypeSource, + collectStateManagementTypeImport, + hasDecorator, + PropertyCache, } from './utils'; -import { createOptionalClassProperty } from '../utils'; +import { factory } from './factory'; function getStorageLinkValueStr(node: arkts.AstNode): string | undefined { if (!arkts.isClassProperty(node) || !node.value) return undefined; @@ -63,27 +67,23 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... + this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); } cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - - if (currentStructInfo.isReusable) { + PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); + if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); + PropertyCache.getInstance().collectToRecord(this.structInfo.name, [toRecord]); } - - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const storageLinkValueStr: string | undefined = getStorageLinkValueInAnnotation(this.property); if (!storageLinkValueStr) { - throw new Error('StorageLink required only one value!!'); // TODO: replace this with proper error message. + throw new Error('StorageLink required only one value!!'); } const args: arkts.Expression[] = [ @@ -91,12 +91,13 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial arkts.factory.create1StringLiteral(originalName), this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; - judgeIfAddWatchFunc(args, this.property); - + factory.judgeIfAddWatchFunc(args, this.property); + collectStateManagementTypeSource(StateManagementTypes.STORAGE_LINK_DECORATED); + collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_DECORATED); const newClass = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('StorageLinkDecoratedVariable'), + arkts.factory.createIdentifier(StateManagementTypes.STORAGE_LINK_DECORATED), arkts.factory.createTSTypeParameterInstantiation( this.property.typeAnnotation ? [this.property.typeAnnotation] : [] ) @@ -119,10 +120,10 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field = createOptionalClassProperty( + const field = factory.createOptionalClassProperty( newName, this.property, - 'StorageLinkDecoratedVariable', + StateManagementTypes.STORAGE_LINK_DECORATED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); @@ -159,3 +160,45 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial return createSetter2(originalName, typeAnnotation, statement); } } + +export class StorageLinkInterfaceTranslator extends InterfacePropertyTranslator { + translateProperty(): T { + if (arkts.isMethodDefinition(this.property)) { + this.modified = true; + return this.updateStateMethodInInterface(this.property) as T; + } else if (arkts.isClassProperty(this.property)) { + this.modified = true; + return this.updateStatePropertyInInterface(this.property) as T; + } + return this.property; + } + + static canBeTranslated(node: arkts.AstNode): node is InterfacePropertyTypes { + if (arkts.isMethodDefinition(node) && hasDecorator(node, DecoratorNames.STORAGE_LINK)) { + return true; + } else if (arkts.isClassProperty(node) && hasDecorator(node, DecoratorNames.STORAGE_LINK)) { + return true; + } + return false; + } + + /** + * Wrap getter's return type and setter's param type (expecting an union type with `T` and `undefined`) + * to `StorageLinkDecoratedVariable | undefined`. + * + * @param method expecting getter with `@StorageLink` and a setter with `@StorageLink` in the overloads. + */ + private updateStateMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { + return factory.wrapStateManagementTypeToMethodInInterface(method, DecoratorNames.STORAGE_LINK); + } + + /** + * Wrap to the type of the property (expecting an union type with `T` and `undefined`) + * to `StorageLinkDecoratedVariable | undefined`. + * + * @param property expecting property with `@StorageLink`. + */ + private updateStatePropertyInInterface(property: arkts.ClassProperty): arkts.ClassProperty { + return factory.wrapStateManagementTypeToPropertyInInterface(property, DecoratorNames.STORAGE_LINK); + } +} diff --git a/arkui-plugins/ui-plugins/property-translators/types.ts b/arkui-plugins/ui-plugins/property-translators/types.ts index b791a7da1..24e9e3bf6 100644 --- a/arkui-plugins/ui-plugins/property-translators/types.ts +++ b/arkui-plugins/ui-plugins/property-translators/types.ts @@ -32,3 +32,9 @@ export interface InitializerConstructor { cacheTranslatedInitializer(newName: string, originalName: string): void; translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[]; } + +export type ClassScopeInfo = { + isObserved: boolean; + classHasTrack: boolean; + getters: arkts.MethodDefinition[] +}; diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index acdae5b2f..feeef959b 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -14,8 +14,15 @@ */ import * as arkts from '@koalaui/libarkts'; -import { annotation } from '../../common/arkts-utils'; -import { factory } from './factory'; +import { DeclarationCollector } from '../../common/declaration-collector'; +import { ImportCollector } from '../import-collector'; +import { ARKUI_COMPONENT_IMPORT_NAME, ARKUI_STATEMANAGEMENT_IMPORT_NAME } from '../../common/predefines'; +import { + addMemoAnnotation, + findCanAddMemoFromParamExpression, + findCanAddMemoFromTypeAnnotation, + findImportSource, +} from '../utils'; export enum DecoratorNames { STATE = 'State', @@ -37,20 +44,131 @@ export enum DecoratorNames { TRACK = 'Track', } -export function collectPropertyDecorators(property: arkts.ClassProperty): string[] { - const properties: string[] = []; - property.annotations.forEach((anno) => { - if (!!anno.expr && arkts.isIdentifier(anno.expr)) { - properties.push(anno.expr.name); - } - }); - return properties; +export enum DecoratorIntrinsicNames { + LINK = '__Link_intrinsic', +} + +export enum DecoratorDeclarationNames { + STMT_COMMON = 'arkui.stateManagement.common', + COMP_COMMON = 'arkui.component.common', + CUSTOM_COMP = 'arkui.component.customComponent', } -export function isDecoratorAnnotation(anno: arkts.AnnotationUsage, decoratorName: DecoratorNames): boolean { +export enum StateManagementTypes { + STATE_DECORATED = 'StateDecoratedVariable', + LINK_DECORATED = 'LinkDecoratedVariable', + STORAGE_LINK_DECORATED = 'StorageLinkDecoratedVariable', + STORAGE_PROP_DECORATED = 'StoragePropDecoratedVariable', + DECORATED_V1 = 'DecoratedV1VariableBase', + PROP_DECORATED = 'PropDecoratedVariable', + MUTABLE_STATE = 'MutableState', + MUTABLE_STATE_META = 'MutableStateMeta', + SYNCED_PROPERTY = 'SyncedProperty', + PROVIDE_DECORATED = 'ProvideDecoratedVariable', + CONSUME_DECORATED = 'ConsumeDecoratedVariable', + OBJECT_LINK_DECORATED = 'ObjectLinkDecoratedVariable', + BACKING_VALUE = 'BackingValue', + SET_OBSERVATION_DEPTH = 'setObservationDepth', + OBSERVED_OBJECT = 'IObservedObject', + WATCH_ID_TYPE = 'WatchIdType', + SUBSCRIBED_WATCHES = 'SubscribedWatches', + STORAGE_LINK_STATE = 'StorageLinkState', + OBSERVABLE_PROXY = 'observableProxy', + PROP_STATE = 'propState', + INT_32 = 'int32', +} + +export interface DecoratorInfo { + annotation: arkts.AnnotationUsage; + name: DecoratorNames; +} + +export const decoratorTypeMap = new Map([ + [DecoratorNames.STATE, StateManagementTypes.STATE_DECORATED], + [DecoratorNames.LINK, StateManagementTypes.DECORATED_V1], + [DecoratorNames.PROP, StateManagementTypes.PROP_DECORATED], + [DecoratorNames.STORAGE_LINK, StateManagementTypes.STORAGE_LINK_DECORATED], + [DecoratorNames.STORAGE_PROP, StateManagementTypes.STORAGE_PROP_DECORATED], + [DecoratorNames.LOCAL_STORAGE_PROP, StateManagementTypes.SYNCED_PROPERTY], + [DecoratorNames.LOCAL_STORAGE_LINK, StateManagementTypes.MUTABLE_STATE], + [DecoratorNames.OBJECT_LINK, StateManagementTypes.OBJECT_LINK_DECORATED], + [DecoratorNames.PROVIDE, StateManagementTypes.PROVIDE_DECORATED], + [DecoratorNames.CONSUME, StateManagementTypes.CONSUME_DECORATED], +]); + +export function isFromDecoratorDeclaration(value: any): value is DecoratorDeclarationNames { + return Object.values(DecoratorDeclarationNames).includes(value); +} + +export function getImportSourceFromDeclarationName(name: DecoratorDeclarationNames): string { + if (name === DecoratorDeclarationNames.STMT_COMMON) { + return ARKUI_STATEMANAGEMENT_IMPORT_NAME; + } + return ARKUI_COMPONENT_IMPORT_NAME; +} + +export function isDecoratorIntrinsicAnnotation( + anno: arkts.AnnotationUsage, + decoratorName: DecoratorIntrinsicNames +): boolean { return !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === decoratorName; } +export function isDecoratorAnnotation( + anno: arkts.AnnotationUsage, + decoratorName: DecoratorNames, + ignoreDecl?: boolean +): boolean { + if (!(!!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === decoratorName)) { + return false; + } + if (!ignoreDecl) { + const decl = arkts.getDecl(anno.expr); + if (!decl) { + return false; + } + const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; + if (!isFromDecoratorDeclaration(moduleName)) { + return false; + } + ImportCollector.getInstance().collectSource(decoratorName, getImportSourceFromDeclarationName(moduleName)); + DeclarationCollector.getInstance().collect(decl); + } + return true; +} + +export function removeDecorator( + property: arkts.ClassProperty | arkts.ClassDefinition | arkts.MethodDefinition, + decoratorName: DecoratorNames, + ignoreDecl?: boolean +): void { + if (arkts.isMethodDefinition(property)) { + property.scriptFunction.setAnnotations( + property.scriptFunction.annotations.filter( + (anno) => !isDecoratorAnnotation(anno, decoratorName, ignoreDecl) + ) + ); + } else { + property.setAnnotations( + property.annotations.filter((anno) => !isDecoratorAnnotation(anno, decoratorName, ignoreDecl)) + ); + } +} + +/** + * checking whether astNode's annotations contain given corresponding decorator name, + * regardless where the annotation's declaration is from arkui declaration files. + */ +export function hasDecoratorName( + property: arkts.ClassProperty | arkts.ClassDefinition | arkts.MethodDefinition, + decoratorName: DecoratorNames +): boolean { + if (arkts.isMethodDefinition(property)) { + return property.scriptFunction.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName, true)); + } + return property.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName, true)); +} + export function hasDecorator( property: arkts.ClassProperty | arkts.ClassDefinition | arkts.MethodDefinition, decoratorName: DecoratorNames @@ -68,45 +186,75 @@ export function hasDecorator( */ export function needDefiniteOrOptionalModifier(st: arkts.ClassProperty): boolean { return ( - hasDecorator(st, DecoratorNames.LINK) || - hasDecorator(st, DecoratorNames.CONSUME) || - hasDecorator(st, DecoratorNames.OBJECT_LINK) || - (hasDecorator(st, DecoratorNames.PROP) && !st.value) + hasDecoratorName(st, DecoratorNames.LINK) || + hasDecoratorName(st, DecoratorNames.CONSUME) || + hasDecoratorName(st, DecoratorNames.OBJECT_LINK) || + (hasDecoratorName(st, DecoratorNames.PROP) && !st.value) ); } -export function getStateManagementType(node: arkts.ClassProperty): string { - if (hasDecorator(node, DecoratorNames.STATE)) { - return 'StateDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.LINK)) { - return 'DecoratedV1VariableBase'; - } else if (hasDecorator(node, DecoratorNames.PROP)) { - return 'PropDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.STORAGE_LINK)) { - return 'StorageLinkDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.STORAGE_PROP)) { - return 'StoragePropDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.PROVIDE)) { - return 'ProvideDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.CONSUME)) { - return 'ConsumeDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.OBJECT_LINK)) { - return 'ObjectLinkDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP)) { - return 'SyncedProperty'; +export function findDecoratorByName( + property: arkts.ClassProperty | arkts.ClassDefinition | arkts.MethodDefinition, + decoratorName: DecoratorNames +): arkts.AnnotationUsage | undefined { + if (arkts.isMethodDefinition(property)) { + return property.scriptFunction.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName, true)); + } + return property.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName, true)); +} + +export function findDecorator( + property: arkts.ClassProperty | arkts.ClassDefinition | arkts.MethodDefinition, + decoratorName: DecoratorNames +): arkts.AnnotationUsage | undefined { + if (arkts.isMethodDefinition(property)) { + return property.scriptFunction.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName)); + } + return property.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName)); +} + +export function findDecoratorInfos( + property: arkts.ClassProperty | arkts.ClassDefinition | arkts.MethodDefinition +): DecoratorInfo[] { + const decoratorNames = Object.values(DecoratorNames); + const infos: DecoratorInfo[] = []; + for (let i = 0; i < decoratorNames.length; i++) { + const name = decoratorNames[i]; + const annotation: arkts.AnnotationUsage | undefined = findDecoratorByName(property, name); + if (!!annotation) { + infos.push({ annotation, name }); + } + } + return infos; +} + +export function getStateManagementType(decoratorInfo: DecoratorInfo): StateManagementTypes { + const decoratorName = decoratorInfo.name; + const typeName = decoratorTypeMap.get(decoratorName); + if (!!typeName) { + return typeName; } - return 'MutableState'; + return StateManagementTypes.MUTABLE_STATE; +} + +export function collectStateManagementTypeImport(type: StateManagementTypes): void { + ImportCollector.getInstance().collectImport(type); +} + +export function collectStateManagementTypeSource(type: StateManagementTypes): void { + const source = findImportSource(type); + ImportCollector.getInstance().collectSource(type, source); } export function createGetter( name: string, type: arkts.TypeNode | undefined, returns: arkts.Expression, - needMemo: boolean = false, + needMemo: boolean = false ): arkts.MethodDefinition { const returnType: arkts.TypeNode | undefined = type?.clone(); - if (needMemo) { - returnType?.setAnnotations([annotation('memo')]); + if (needMemo && findCanAddMemoFromTypeAnnotation(returnType)) { + addMemoAnnotation(returnType); } const body = arkts.factory.createBlock([arkts.factory.createReturnStatement(returns)]); const scriptFunction = arkts.factory.createScriptFunction( @@ -118,7 +266,7 @@ export function createGetter( return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, arkts.factory.createIdentifier(name), - arkts.factory.createFunctionExpression(scriptFunction), + scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -144,8 +292,8 @@ export function createSetter( arkts.factory.createIdentifier('value', type?.clone()), undefined ); - if (needMemo) { - param.annotations = [annotation('memo')]; + if (needMemo && findCanAddMemoFromParamExpression(param)) { + addMemoAnnotation(param); } const scriptFunction = arkts.factory.createScriptFunction( body, @@ -157,7 +305,7 @@ export function createSetter( return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, arkts.factory.createIdentifier(name), - arkts.factory.createFunctionExpression(scriptFunction), + scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -183,7 +331,7 @@ export function createSetter2( return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, arkts.factory.createIdentifier(name), - arkts.factory.createFunctionExpression(scriptFunction), + scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -293,15 +441,6 @@ function getDifferentAnnoTypeValue(value: arkts.Expression): string | boolean { return value.dumpSrc(); } -export function judgeIfAddWatchFunc(args: arkts.Expression[], property: arkts.ClassProperty): void { - if (hasDecorator(property, DecoratorNames.WATCH)) { - const watchStr: string | undefined = getValueInAnnotation(property, DecoratorNames.WATCH); - if (watchStr) { - args.push(factory.createWatchCallback(watchStr)); - } - } -} - export function generateGetOrSetCall(beforCall: arkts.AstNode, type: string) { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -339,25 +478,59 @@ export function generateToRecord(newName: string, originalName: string): arkts.P ); } -export function getStageManagementIdent(property: arkts.ClassProperty): string { - const useMutableState: boolean = - hasDecorator(property, DecoratorNames.STATE) || - hasDecorator(property, DecoratorNames.STORAGE_LINK) || - hasDecorator(property, DecoratorNames.PROVIDE) || - hasDecorator(property, DecoratorNames.CONSUME) || - hasDecorator(property, DecoratorNames.LINK) || - hasDecorator(property, DecoratorNames.LOCAL_STORAGE_LINK) || - hasDecorator(property, DecoratorNames.LINK); - const useSyncedProperty: boolean = - hasDecorator(property, DecoratorNames.PROP) || - hasDecorator(property, DecoratorNames.STORAGE_PROP) || - hasDecorator(property, DecoratorNames.LOCAL_STORAGE_PROP) || - hasDecorator(property, DecoratorNames.OBJECT_LINK); - if (useMutableState) { - return 'MutableState'; - } else if (useSyncedProperty) { - return 'SyncedProperty'; - } else { - return ''; - } +// CACHE +export interface PropertyCachedBody { + initializeBody?: arkts.AstNode[]; + updateBody?: arkts.AstNode[]; + toRecordBody?: arkts.Property[]; } + +export class PropertyCache { + private _cache: Map; + private static instance: PropertyCache; + + private constructor() { + this._cache = new Map(); + } + + static getInstance(): PropertyCache { + if (!this.instance) { + this.instance = new PropertyCache(); + } + return this.instance; + } + + reset(): void { + this._cache.clear(); + } + + getInitializeBody(name: string): arkts.AstNode[] { + return this._cache.get(name)?.initializeBody ?? []; + } + + getUpdateBody(name: string): arkts.AstNode[] { + return this._cache.get(name)?.updateBody ?? []; + } + + getToRecordBody(name: string): arkts.Property[] { + return this._cache.get(name)?.toRecordBody ?? []; + } + + collectInitializeStruct(name: string, initializeStruct: arkts.AstNode[]): void { + const initializeBody = this._cache.get(name)?.initializeBody ?? []; + const newInitializeBody = [...initializeBody, ...initializeStruct]; + this._cache.set(name, { ...this._cache.get(name), initializeBody: newInitializeBody }); + } + + collectUpdateStruct(name: string, updateStruct: arkts.AstNode[]): void { + const updateBody = this._cache.get(name)?.updateBody ?? []; + const newUpdateBody = [...updateBody, ...updateStruct]; + this._cache.set(name, { ...this._cache.get(name), updateBody: newUpdateBody }); + } + + collectToRecord(name: string, toRecord: arkts.Property[]): void { + const toRecordBody = this._cache.get(name)?.toRecordBody ?? []; + const newToRecordBody = [...toRecordBody, ...toRecord]; + this._cache.set(name, { ...this._cache.get(name), toRecordBody: newToRecordBody }); + } +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index 918d2ebac..d5f3dadff 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -14,22 +14,54 @@ */ import * as arkts from '@koalaui/libarkts'; -import { BuilderLambdaNames, CustomComponentNames, Dollars } from '../utils'; +import { + BuilderLambdaNames, + addMemoAnnotation, + CustomComponentNames, + Dollars, + findImportSource, + getCustomComponentOptionsName, + getGettersFromClassDecl, + getTypeNameFromTypeParameter, + getTypeParamsFromClassDecl, + isCustomComponentInterface, +} from '../utils'; import { factory as uiFactory } from '../ui-factory'; -import { annotation } from '../../common/arkts-utils'; +import { factory as propertyFactory } from '../property-translators/factory'; +import { collect, filterDefined } from '../../common/arkts-utils'; +import { + classifyObservedTrack, + classifyProperty, + classifyPropertyInInterface, + ClassScopeInfo, + InterfacePropertyTranslator, + PropertyTranslator, +} from '../property-translators'; +import { CustomComponentScopeInfo, isEtsGlobalClass, isKnownMethodDefinition } from './utils'; +import { + collectStateManagementTypeImport, + collectStateManagementTypeSource, + DecoratorDeclarationNames, + DecoratorNames, + hasDecorator, + PropertyCache, + removeDecorator, + StateManagementTypes, +} from '../property-translators/utils'; +import { ProjectConfig } from '../../common/plugin-context'; +import { DeclarationCollector } from '../../common/declaration-collector'; +import { ObservedTrackTranslator } from '../../ui-plugins/property-translators/observedTrack'; +import { ImportCollector } from '../../ui-plugins/import-collector'; export class factory { /* - * create `constructor() {}`. + * update class `constructor` to private. */ - static createConstructorMethod(member: arkts.MethodDefinition): arkts.MethodDefinition { - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, - member.name, - arkts.factory.createFunctionExpression(member.scriptFunction), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, - false - ); + static setStructConstructorToPrivate(member: arkts.MethodDefinition): arkts.MethodDefinition { + member.modifiers &= arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; + member.modifiers &= arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PROTECTED; + member.modifiers |= arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE; + return member; } /* @@ -44,23 +76,22 @@ export class factory { const updateKey: arkts.Identifier = arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_BUILD); const scriptFunction: arkts.ScriptFunction = method.scriptFunction; - const updateScriptFunction = arkts.factory - .createScriptFunction( - scriptFunction.body, - arkts.FunctionSignature.createFunctionSignature( - scriptFunction.typeParams, - [ - uiFactory.createStyleParameter(typeName), - uiFactory.createContentParameter(), - uiFactory.createInitializersOptionsParameter(optionsName), - ], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - scriptFunction.flags, - scriptFunction.modifiers - ) - .setAnnotations([annotation('memo')]); + const updateScriptFunction = arkts.factory.createScriptFunction( + scriptFunction.body, + arkts.FunctionSignature.createFunctionSignature( + scriptFunction.typeParams, + [ + uiFactory.createStyleParameter(typeName), + uiFactory.createContentParameter(), + uiFactory.createInitializersOptionsParameter(optionsName), + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ), + scriptFunction.flags, + scriptFunction.modifiers + ); + addMemoAnnotation(updateScriptFunction); const modifiers: arkts.Es2pandaModifierFlags = isDecl ? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT @@ -68,7 +99,7 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, updateKey, - arkts.factory.createFunctionExpression(updateScriptFunction), + updateScriptFunction, modifiers, false ); @@ -79,10 +110,14 @@ export class factory { */ static generateTransformedResource( resourceNode: arkts.CallExpression, + key: arkts.Identifier, newArgs: arkts.AstNode[] ): arkts.CallExpression { const transformedKey: string = - resourceNode.expression.dumpSrc() === Dollars.DOLLAR_RESOURCE ? '_r' : '_rawfile'; + key.name === Dollars.DOLLAR_RESOURCE ? Dollars.TRANSFORM_DOLLAR_RESOURCE : Dollars.TRANSFORM_DOLLAR_RAWFILE; + const source = findImportSource(transformedKey); + ImportCollector.getInstance().collectSource(transformedKey, source); + ImportCollector.getInstance().collectImport(transformedKey); return arkts.factory.updateCallExpression( resourceNode, arkts.factory.createIdentifier(transformedKey), @@ -94,19 +129,15 @@ export class factory { /* * create __initializeStruct method. */ - static createInitializeStruct( - structInfo: arkts.StructInfo, - optionsTypeName: string, - isDecl?: boolean - ): arkts.MethodDefinition { + static createInitializeStruct(optionsTypeName: string, scope: CustomComponentScopeInfo): arkts.MethodDefinition { const updateKey: arkts.Identifier = arkts.factory.createIdentifier( CustomComponentNames.COMPONENT_INITIALIZE_STRUCT ); let body: arkts.BlockStatement | undefined; let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT; - if (!isDecl) { - body = arkts.factory.createBlock(structInfo.initializeBody); + if (!scope.isDecl) { + body = arkts.factory.createBlock(PropertyCache.getInstance().getInitializeBody(scope.name)); modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; } const scriptFunction: arkts.ScriptFunction = arkts.factory @@ -126,7 +157,7 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, updateKey, - arkts.factory.createFunctionExpression(scriptFunction), + scriptFunction, modifiers, false ); @@ -135,19 +166,15 @@ export class factory { /* * create __updateStruct method. */ - static createUpdateStruct( - structInfo: arkts.StructInfo, - optionsTypeName: string, - isDecl?: boolean - ): arkts.MethodDefinition { + static createUpdateStruct(optionsTypeName: string, scope: CustomComponentScopeInfo): arkts.MethodDefinition { const updateKey: arkts.Identifier = arkts.factory.createIdentifier( CustomComponentNames.COMPONENT_UPDATE_STRUCT ); let body: arkts.BlockStatement | undefined; let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT; - if (!isDecl) { - body = arkts.factory.createBlock(structInfo.updateBody); + if (!scope.isDecl) { + body = arkts.factory.createBlock(PropertyCache.getInstance().getUpdateBody(scope.name)); modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; } @@ -168,7 +195,7 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, updateKey, - arkts.factory.createFunctionExpression(scriptFunction), + scriptFunction, modifiers, false ); @@ -177,12 +204,12 @@ export class factory { /* * create __toRecord method when the component is decorated with @Reusable. */ - static toRecord(optionsTypeName: string, toRecordBody: arkts.Property[]): arkts.MethodDefinition { + static createToRecord(optionsTypeName: string, scope: CustomComponentScopeInfo): arkts.MethodDefinition { const paramsCasted = factory.generateParamsCasted(optionsTypeName); const returnRecord = arkts.factory.createReturnStatement( arkts.ObjectExpression.createObjectExpression( arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - toRecordBody, + PropertyCache.getInstance().getToRecordBody(scope.name), false ) ); @@ -203,7 +230,7 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, arkts.factory.createIdentifier('__toRecord'), - arkts.factory.createFunctionExpression(toRecordScriptFunction), + toRecordScriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE, false ); @@ -278,7 +305,7 @@ export class factory { /* * add headers for animation in UICommonMethod */ - static modifyExternalComponentCommon(node: arkts.TSInterfaceDeclaration): arkts.AstNode { + static modifyExternalComponentCommon(node: arkts.TSInterfaceDeclaration): arkts.TSInterfaceDeclaration { const animationStart = factory.createAnimationMethod(BuilderLambdaNames.ANIMATION_START); const animationStop = factory.createAnimationMethod(BuilderLambdaNames.ANIMATION_STOP); const updatedBody = arkts.factory.updateInterfaceBody(node.body!, [ @@ -305,83 +332,315 @@ export class factory { arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier( 'value', - arkts.factory.createUnionType( - [ - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('AnimateParam')) - ), - arkts.factory.createETSUndefinedType() - ] - ) + arkts.factory.createUnionType([ + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('AnimateParam')) + ), + arkts.factory.createETSUndefinedType(), + ]) ), undefined ), ]; - const aniFuncExpr = arkts.factory.createFunctionExpression( - arkts.factory.createScriptFunction( - undefined, - arkts.factory.createFunctionSignature(undefined, aniparams, arkts.TSThisType.createTSThisType(), false), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ) + const aniFunc = arkts.factory.createScriptFunction( + undefined, + arkts.factory.createFunctionSignature(undefined, aniparams, arkts.TSThisType.createTSThisType(), false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, arkts.factory.createIdentifier(key), - aniFuncExpr, + aniFunc, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); } - /* - * generate XComponent(..., packageInfo: string, ...) + /** + * transform property members in custom-component class. */ - static modifyXcomponent(node: arkts.ScriptFunction): arkts.ScriptFunction { - const info = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - 'packageInfo', - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('string') - ) - ) - ), - undefined + static tranformPropertyMembers( + propertyTranslators: PropertyTranslator[], + optionsTypeName: string, + scope: CustomComponentScopeInfo + ): arkts.AstNode[] { + const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); + const collections = []; + if (!scope.hasInitializeStruct) { + collections.push(this.createInitializeStruct(optionsTypeName, scope)); + } + if (!scope.hasUpdateStruct) { + collections.push(this.createUpdateStruct(optionsTypeName, scope)); + } + if (!!scope.annotations?.reusable) { + collections.push(this.createToRecord(optionsTypeName, scope)); + } + return collect(...collections, ...propertyMembers); + } + + /** + * transform non-property members in custom-component class. + */ + static transformNonPropertyMembersInClass( + member: arkts.AstNode, + classTypeName: string | undefined, + classOptionsName: string | undefined, + className: string, + isDecl?: boolean + ): arkts.AstNode { + if (arkts.isMethodDefinition(member)) { + propertyFactory.addMemoToBuilderClassMethod(member); + if (isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI) && !isDecl) { + return this.setStructConstructorToPrivate(member); + } else if (isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI)) { + return this.transformBuildMethodWithOriginBuild( + member, + classTypeName ?? className, + classOptionsName ?? getCustomComponentOptionsName(className), + isDecl + ); + } + return member; + } + return member; + } + + /** + * transform members in custom-component class. + */ + static tranformClassMembers(node: arkts.ClassDeclaration, scope: CustomComponentScopeInfo): arkts.ClassDeclaration { + if (!node.definition) { + return node; + } + let classTypeName: string | undefined; + let classOptionsName: string | undefined; + if (scope.isDecl) { + const [classType, classOptions] = getTypeParamsFromClassDecl(node); + classTypeName = getTypeNameFromTypeParameter(classType); + classOptionsName = getTypeNameFromTypeParameter(classOptions); + } + const definition: arkts.ClassDefinition = node.definition; + const className: string | undefined = node.definition.ident?.name; + if (!className) { + throw new Error('Non Empty className expected for Component'); + } + + const propertyTranslators: PropertyTranslator[] = filterDefined( + definition.body.map((it) => classifyProperty(it, scope)) ); - return arkts.factory.updateScriptFunction( - node, - node.body, - arkts.factory.createFunctionSignature( - node.typeParams, - [...node.params.slice(0, 2), info, ...node.params.slice(2)], - node.returnTypeAnnotation, - false - ), - node.flags, - node.modifiers + const translatedMembers: arkts.AstNode[] = this.tranformPropertyMembers( + propertyTranslators, + classOptionsName ?? getCustomComponentOptionsName(className), + scope ); + const updateMembers: arkts.AstNode[] = definition.body + .filter((member) => !arkts.isClassProperty(member)) + .map((member: arkts.AstNode) => + factory.transformNonPropertyMembersInClass( + member, + classTypeName, + classOptionsName, + className, + scope.isDecl + ) + ); + + const updateClassDef: arkts.ClassDefinition = this.updateCustomComponentClass(definition, [ + ...translatedMembers, + ...updateMembers, + ]); + return arkts.factory.updateClassDeclaration(node, updateClassDef); } - /* - * transform ExternalSource headers + /** + * transform `$r` and `$rawfile` function calls. */ - static transformExternalSource(externalSourceName: string, node: arkts.AstNode): arkts.AstNode { - if ( - externalSourceName === 'arkui.component.common' && - arkts.isTSInterfaceDeclaration(node) && - !!node.id && - node.id.name === 'UICommonMethod' - ) { + static transformResource( + resourceNode: arkts.CallExpression, + projectConfig: ProjectConfig | undefined + ): arkts.CallExpression { + let decl: arkts.AstNode | undefined; + if (!arkts.isIdentifier(resourceNode.expression) || !(decl = arkts.getDecl(resourceNode.expression))) { + return resourceNode; + } + DeclarationCollector.getInstance().collect(decl); + + const newArgs: arkts.AstNode[] = [ + arkts.factory.create1StringLiteral(projectConfig?.bundleName ? projectConfig.bundleName : ''), + arkts.factory.create1StringLiteral(projectConfig?.moduleName ? projectConfig.moduleName : ''), + ...resourceNode.arguments, + ]; + return this.generateTransformedResource(resourceNode, resourceNode.expression, newArgs); + } + + /** + * transform members in interface. + */ + static tranformInterfaceMembers( + node: arkts.TSInterfaceDeclaration, + externalSourceName?: string + ): arkts.TSInterfaceDeclaration { + if (!node.id || !node.body) { + return node; + } + if (externalSourceName === DecoratorDeclarationNames.COMP_COMMON && node.id.name === 'UICommonMethod') { return factory.modifyExternalComponentCommon(node); - } else if ( - externalSourceName === 'arkui.component.xcomponent' && - arkts.isScriptFunction(node) && - !!node.id && - node.id.name === 'XComponent' - ) { - return factory.modifyXcomponent(node); + } + if (isCustomComponentInterface(node)) { + return factory.tranformCustomComponentInterfaceMembers(node); } return node; } + + /** + * transform members in custom-component related interface. + */ + static tranformCustomComponentInterfaceMembers(node: arkts.TSInterfaceDeclaration): arkts.TSInterfaceDeclaration { + const propertyTranslators: InterfacePropertyTranslator[] = filterDefined( + node.body!.body.map((it) => classifyPropertyInInterface(it)) + ); + + let shouldUpdate: boolean = false; + const newBody = propertyTranslators.map((translator) => { + const newProperty = translator.translateProperty(); + shouldUpdate ||= translator.modified; + return newProperty; + }); + + if (shouldUpdate) { + return arkts.factory.updateInterfaceDeclaration( + node, + node.extends, + node.id, + node.typeParams, + arkts.factory.updateInterfaceBody(node.body!, newBody), + node.isStatic, + node.isFromExternal + ); + } + + return node; + } + + static transformNormalClass(node: arkts.ClassDeclaration): arkts.ClassDeclaration { + if (!node.definition) { + return node; + } + if (isEtsGlobalClass(node)) { + node.definition.body.forEach( + (member: arkts.AstNode) => + arkts.isMethodDefinition(member) && propertyFactory.addMemoToBuilderClassMethod(member) + ); + return node; + } + const newClassDef = factory.updateObservedTrackClassDef(node.definition); + return arkts.factory.updateClassDeclaration(node, newClassDef); + } + + static updateObservedTrackClassDef(node: arkts.ClassDefinition): arkts.ClassDefinition { + const isObserved: boolean = hasDecorator(node, DecoratorNames.OBSERVED); + const classHasTrack: boolean = node.body.some( + (member) => arkts.isClassProperty(member) && hasDecorator(member, DecoratorNames.TRACK) + ); + if (!isObserved && !classHasTrack) { + return node; + } + const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( + node, + node.ident, + node.typeParams, + node.superTypeParams, + [ + ...node.implements, + arkts.TSClassImplements.createTSClassImplements( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.OBSERVED_OBJECT) + ) + ) + ), + ], + undefined, + node.super, + factory.observedTrackPropertyMembers(classHasTrack, node, isObserved), + node.modifiers, + arkts.classDefinitionFlags(node) + ); + collectStateManagementTypeSource(StateManagementTypes.OBSERVED_OBJECT); + collectStateManagementTypeImport(StateManagementTypes.OBSERVED_OBJECT); + return updateClassDef; + } + + static createPermissibleAddRefDepthInObservedClass(): arkts.ClassProperty { + return arkts.factory.createClassProperty( + arkts.factory.createIdentifier('_permissibleAddRefDepth'), + arkts.factory.createNumericLiteral(0), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(StateManagementTypes.INT_32)) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + } + + static createMutableStateMetaInObservedClass(): arkts.ClassProperty { + return arkts.factory.createClassProperty( + arkts.factory.createIdentifier('__meta'), + arkts.factory.createETSNewClassInstanceExpression( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) + ) + ), + [arkts.factory.createStringLiteral('@Observe properties (no @Track)')] + ), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) + ) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + } + + static observedTrackPropertyMembers( + classHasTrack: boolean, + definition: arkts.ClassDefinition, + isObserved: boolean + ): arkts.AstNode[] { + const watchMembers: arkts.AstNode[] = propertyFactory.createWatchMembers(); + const permissibleAddRefDepth: arkts.ClassProperty = factory.createPermissibleAddRefDepthInObservedClass(); + collectStateManagementTypeSource(StateManagementTypes.INT_32); + collectStateManagementTypeImport(StateManagementTypes.INT_32); + const meta: arkts.ClassProperty = factory.createMutableStateMetaInObservedClass(); + collectStateManagementTypeSource(StateManagementTypes.MUTABLE_STATE_META); + collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); + const getters: arkts.MethodDefinition[] = getGettersFromClassDecl(definition); + const classScopeInfo: ClassScopeInfo = { + isObserved: isObserved, + classHasTrack: classHasTrack, + getters: getters, + }; + const propertyTranslators: ObservedTrackTranslator[] = filterDefined( + definition.body.map((it) => classifyObservedTrack(it, classScopeInfo)) + ); + const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); + const nonClassPropertyOrGetter: arkts.AstNode[] = definition.body.filter( + (member) => + !arkts.isClassProperty(member) && + !( + arkts.isMethodDefinition(member) && + arkts.hasModifierFlag(member, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_GETTER) + ) + ); + return [ + ...watchMembers, + ...(classHasTrack ? [permissibleAddRefDepth] : [permissibleAddRefDepth, meta]), + ...collect(...propertyMembers), + ...nonClassPropertyOrGetter, + ...classScopeInfo.getters, + ]; + } } diff --git a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts index be9ebdb11..920ce8270 100644 --- a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts +++ b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts @@ -15,205 +15,88 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../../common/abstract-visitor'; -import { annotation, collect, filterDefined } from '../../common/arkts-utils'; import { ProjectConfig } from '../../common/plugin-context'; -import { classifyProperty, PropertyTranslator } from '../property-translators'; import { addMemoAnnotation, + collectCustomComponentScopeInfo, CustomComponentNames, - getCustomComponentOptionsName, - getTypeNameFromTypeParameter, - getTypeParamsFromClassDecl, + isCustomComponentClass, } from '../utils'; -import { isCustomComponentClass, isKnownMethodDefinition, isEtsGlobalClass, isReourceNode, CustomComponentScopeInfo, findCanAddMemoFromArrowFunction } from './utils'; -import { factory as uiFactory } from '../ui-factory'; +import { CustomComponentScopeInfo, findCanAddMemoFromArrowFunction, isResourceNode, ScopeInfoCollection } from './utils'; import { factory } from './factory'; import { isEntryWrapperClass } from '../entry-translators/utils'; import { factory as entryFactory } from '../entry-translators/factory'; -import { DecoratorNames, hasDecorator } from '../property-translators/utils'; -import { ScopeInfoCollection } from './utils'; - -function tranformPropertyMembers( - className: string, - propertyTranslators: PropertyTranslator[], - optionsTypeName: string, - isDecl?: boolean, - scope?: CustomComponentScopeInfo -): arkts.AstNode[] { - const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); - const collections = []; - if (!scope?.hasInitializeStruct) { - collections.push(factory.createInitializeStruct(currentStructInfo, optionsTypeName, isDecl)); - } - if (!scope?.hasUpdateStruct) { - collections.push(factory.createUpdateStruct(currentStructInfo, optionsTypeName, isDecl)); - } - if (currentStructInfo.isReusable) { - collections.push(factory.toRecord(optionsTypeName, currentStructInfo.toRecordBody)); - } - return collect(...collections, ...propertyMembers); -} - -function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.ClassDeclaration { - if (!node.definition) { - return node; - } - node.definition.body.map((member: arkts.AstNode) => { - if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { - member.scriptFunction.setAnnotations([annotation('memo')]); - } - return member; - }); - return node; -} - -function transformOtherMembersInClass( - member: arkts.AstNode, - classTypeName: string | undefined, - classOptionsName: string | undefined, - className: string, - isDecl?: boolean -): arkts.AstNode { - if (arkts.isMethodDefinition(member) && hasDecorator(member, DecoratorNames.BUILDER)) { - member.scriptFunction.setAnnotations([annotation('memo')]); - return member; - } - if ( - arkts.isMethodDefinition(member) && - isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI) && - !isDecl - ) { - return uiFactory.createConstructorMethod(member); - } - if (arkts.isMethodDefinition(member) && isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI)) { - return factory.transformBuildMethodWithOriginBuild( - member, - classTypeName ?? className, - classOptionsName ?? getCustomComponentOptionsName(className), - isDecl - ); - } - return member; -} - -function tranformClassMembers( - node: arkts.ClassDeclaration, - isDecl?: boolean, - scope?: CustomComponentScopeInfo -): arkts.ClassDeclaration { - if (!node.definition) { - return node; - } - - let classTypeName: string | undefined; - let classOptionsName: string | undefined; - if (isDecl) { - const [classType, classOptions] = getTypeParamsFromClassDecl(node); - classTypeName = getTypeNameFromTypeParameter(classType); - classOptionsName = getTypeNameFromTypeParameter(classOptions); - } - const definition: arkts.ClassDefinition = node.definition; - const className: string | undefined = node.definition.ident?.name; - if (!className) { - throw new Error('Non Empty className expected for Component'); - } - - const propertyTranslators: PropertyTranslator[] = filterDefined( - definition.body.map((it) => classifyProperty(it, className)) - ); - const translatedMembers: arkts.AstNode[] = tranformPropertyMembers( - className, - propertyTranslators, - classOptionsName ?? getCustomComponentOptionsName(className), - isDecl, - scope - ); - const updateMembers: arkts.AstNode[] = definition.body - .filter((member) => !arkts.isClassProperty(member)) - .map((member: arkts.AstNode) => - transformOtherMembersInClass(member, classTypeName, classOptionsName, className, isDecl) - ); - - const updateClassDef: arkts.ClassDefinition = factory.updateCustomComponentClass(definition, [ - ...translatedMembers, - ...updateMembers, - ]); - return arkts.factory.updateClassDeclaration(node, updateClassDef); -} - -function transformResource( - resourceNode: arkts.CallExpression, - projectConfig: ProjectConfig | undefined -): arkts.CallExpression { - const newArgs: arkts.AstNode[] = [ - arkts.factory.create1StringLiteral(projectConfig?.bundleName ? projectConfig.bundleName : ''), - arkts.factory.create1StringLiteral(projectConfig?.moduleName ? projectConfig.moduleName : ''), - ...resourceNode.arguments, - ]; - return factory.generateTransformedResource(resourceNode, newArgs); -} +import { ImportCollector } from '../import-collector'; +import { PropertyCache } from '../property-translators/utils'; export class StructTransformer extends AbstractVisitor { - private scopeInfoCollection: ScopeInfoCollection; + private scope: ScopeInfoCollection; projectConfig: ProjectConfig | undefined; constructor(projectConfig: ProjectConfig | undefined) { super(); this.projectConfig = projectConfig; - this.scopeInfoCollection = { customComponents: [] }; + this.scope = { customComponents: [] }; } reset(): void { super.reset(); - this.scopeInfoCollection = { customComponents: [] }; + this.scope = { customComponents: [] }; + PropertyCache.getInstance().reset(); + ImportCollector.getInstance().reset(); } enter(node: arkts.AstNode): void { - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfoCollection.customComponents.push({ name: node.definition!.ident!.name }); + if (arkts.isClassDeclaration(node) && !!node.definition && node.definition.body.length > 0) { + const customComponentInfo = collectCustomComponentScopeInfo(node); + if (!!customComponentInfo) { + this.scope.customComponents.push(customComponentInfo); + } } - if (arkts.isMethodDefinition(node) && this.scopeInfoCollection.customComponents.length > 0) { + if (arkts.isMethodDefinition(node) && this.scope.customComponents.length > 0) { const name = node.name.name; - const scopeInfo = this.scopeInfoCollection.customComponents.pop()!; + const scopeInfo = this.scope.customComponents.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; - this.scopeInfoCollection.customComponents.push(scopeInfo); + this.scope.customComponents.push(scopeInfo); } } - exit(node: arkts.AstNode): void { - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfoCollection.customComponents.pop(); + if ( + arkts.isClassDeclaration(node) && + this.scope.customComponents.length > 0 && + isCustomComponentClass(node, this.scope.customComponents[this.scope.customComponents.length - 1]) + ) { + this.scope.customComponents.pop(); } } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { this.enter(beforeChildren); const node = this.visitEachChild(beforeChildren); - if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - let scope: CustomComponentScopeInfo | undefined; - const scopeInfos: CustomComponentScopeInfo[] = this.scopeInfoCollection.customComponents; - if (scopeInfos.length > 0) { - scope = scopeInfos[scopeInfos.length - 1]; - } - const newClass: arkts.ClassDeclaration = tranformClassMembers( - node, - arkts.hasModifierFlag(node, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE), - scope - ); + if ( + arkts.isClassDeclaration(node) && + this.scope.customComponents.length > 0 && + isCustomComponentClass(node, this.scope.customComponents[this.scope.customComponents.length - 1]) + ) { + const scope: CustomComponentScopeInfo = this.scope.customComponents[this.scope.customComponents.length - 1]; + const newClass: arkts.ClassDeclaration = factory.tranformClassMembers(node, scope); this.exit(beforeChildren); return newClass; } else if (isEntryWrapperClass(node)) { entryFactory.addMemoToEntryWrapperClassMethods(node); return node; - } else if (arkts.isClassDeclaration(node) && isEtsGlobalClass(node)) { - return transformEtsGlobalClassMembers(node); - } else if (arkts.isCallExpression(node) && isReourceNode(node)) { - return transformResource(node, this.projectConfig); + } else if (arkts.isClassDeclaration(node)) { + return factory.transformNormalClass(node); + } else if (arkts.isCallExpression(node) && isResourceNode(node)) { + return factory.transformResource(node, this.projectConfig); + } else if (arkts.isTSInterfaceDeclaration(node)) { + return factory.tranformInterfaceMembers(node, this.externalSourceName); } else if (findCanAddMemoFromArrowFunction(node)) { return addMemoAnnotation(node); + } else if (arkts.isEtsScript(node) && ImportCollector.getInstance().importInfos.length > 0) { + ImportCollector.getInstance().insertCurrentImports(this.program); } return node; } diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts index 2af217626..a8b056534 100644 --- a/arkui-plugins/ui-plugins/struct-translators/utils.ts +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -14,7 +14,7 @@ */ import * as arkts from '@koalaui/libarkts'; -import { Dollars, isMemoAnnotation } from '../utils'; +import { CustomComponentInfo, Dollars, isMemoAnnotation, MemoNames } from '../utils'; import { CustomComponentNames } from '../utils'; import { DecoratorNames, isDecoratorAnnotation } from '../property-translators/utils'; @@ -22,27 +22,12 @@ export type ScopeInfoCollection = { customComponents: CustomComponentScopeInfo[]; }; -export type CustomComponentScopeInfo = { - name: string; +export type CustomComponentScopeInfo = CustomComponentInfo & { hasInitializeStruct?: boolean; hasUpdateStruct?: boolean; hasReusableRebind?: boolean; }; -/** - * Determine whether it is a custom component. - * - * @param node class declaration node - */ -export function isCustomComponentClass(node: arkts.ClassDeclaration): boolean { - if (!node.definition?.ident?.name) { - return false; - } - const name: string = node.definition.ident.name; - const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); - return name === CustomComponentNames.COMPONENT_CLASS_NAME || structCollection.has(name); -} - /** * Determine whether it is method with specified name. * @@ -72,15 +57,15 @@ export function isEtsGlobalClass(node: arkts.ClassDeclaration): boolean { } /** - * Determine whether it is resource node begin with '$r' or '$rawfile'. + * Determine whether it is resource node begin with `$r` or `$rawfile`. * * @param node call expression node */ -export function isReourceNode(node: arkts.CallExpression): boolean { - if (node.expression.dumpSrc() === Dollars.DOLLAR_RESOURCE || node.expression.dumpSrc() === Dollars.DOLLAR_RAWFILE) { - return true; - } - return false; +export function isResourceNode(node: arkts.CallExpression): boolean { + return ( + arkts.isIdentifier(node.expression) && + (node.expression.name === Dollars.DOLLAR_RESOURCE || node.expression.name === Dollars.DOLLAR_RAWFILE) + ); } export function isMemoCall(node: arkts.AstNode): node is arkts.CallExpression { @@ -96,7 +81,7 @@ export function isMemoCall(node: arkts.AstNode): node is arkts.CallExpression { if (arkts.isMethodDefinition(decl)) { return decl.scriptFunction.annotations.some( - (anno) => isDecoratorAnnotation(anno, DecoratorNames.BUILDER) || isMemoAnnotation(anno, 'memo') + (anno) => isDecoratorAnnotation(anno, DecoratorNames.BUILDER) || isMemoAnnotation(anno, MemoNames.MEMO) ); } return false; @@ -106,7 +91,7 @@ export function findCanAddMemoFromArrowFunction(node: arkts.AstNode): node is ar if (!arkts.isArrowFunctionExpression(node)) { return false; } - const hasMemo: boolean = node.annotations.some((anno) => isMemoAnnotation(anno, 'memo')); + const hasMemo: boolean = node.annotations.some((anno) => isMemoAnnotation(anno, MemoNames.MEMO)); if (!hasMemo && !!node.scriptFunction.body && arkts.isBlockStatement(node.scriptFunction.body)) { return node.scriptFunction.body.statements.some( (st) => arkts.isExpressionStatement(st) && isMemoCall(st.expression) diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index f41800a4b..26281073f 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -14,10 +14,43 @@ */ import * as arkts from '@koalaui/libarkts'; -import { BuilderLambdaNames, CustomComponentNames, hasPropertyInAnnotation, hasNullOrUndefinedType } from './utils'; -import { annotation } from '../common/arkts-utils'; +import { + addMemoAnnotation, + BuilderLambdaNames, + CustomComponentNames, + findCanAddMemoFromParamExpression, + hasNullOrUndefinedType, + hasPropertyInAnnotation, +} from './utils'; +import { PartialExcept, PartialNested, PartialNestedExcept, PickNested } from '../common/safe-types'; import { DecoratorNames, needDefiniteOrOptionalModifier } from './property-translators/utils'; +export interface ScriptFunctionConfiguration { + key: arkts.Identifier | undefined; + body: arkts.AstNode | undefined; + typeParams: arkts.TSTypeParameterDeclaration | undefined; + params: readonly arkts.Expression[]; + returnTypeAnnotation: arkts.TypeNode | undefined; + hasReceiver: boolean; + flags: arkts.Es2pandaScriptFunctionFlags; + modifiers: arkts.Es2pandaModifierFlags; + annotations: arkts.AnnotationUsage[]; +} + +export interface MethodDefinitionConfiguration { + key: arkts.Identifier; + kind: arkts.Es2pandaMethodDefinitionKind; + function: ScriptFunctionConfiguration; + overloads: arkts.MethodDefinition[]; + modifiers: arkts.Es2pandaModifierFlags; + isComputed: boolean; +} + +export interface IntrinsicAnnotationDeclarationConfiguration { + expr: arkts.Identifier; + properties: arkts.AstNode[]; +} + export class factory { /** * create `instance: ` as identifier @@ -69,8 +102,10 @@ export class factory { */ static createStyleParameter(typeName: string): arkts.ETSParameterExpression { const styleParam: arkts.Identifier = factory.createStyleIdentifier(typeName); - const param = arkts.factory.createParameterDeclaration(styleParam, undefined); - param.annotations = [annotation('memo')]; + const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration(styleParam, undefined); + if (findCanAddMemoFromParamExpression(param)) { + addMemoAnnotation(param); + } return param; } @@ -112,8 +147,10 @@ export class factory { */ static createContentParameter(): arkts.ETSParameterExpression { const contentParam: arkts.Identifier = factory.createContentIdentifier(); - const param = arkts.factory.createParameterDeclaration(contentParam, undefined); - param.annotations = [annotation('memo')]; + const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration(contentParam, undefined); + if (findCanAddMemoFromParamExpression(param)) { + addMemoAnnotation(param); + } return param; } @@ -165,7 +202,7 @@ export class factory { return; } - /* + /** * create `import { as } ...`. */ static createAdditionalImportSpecifier(imported: string, local: string): arkts.ImportSpecifier { @@ -175,59 +212,128 @@ export class factory { ); } - /* - * create `constructor() {}`. + /** + * update ScriptFunction with configurations. */ - static createConstructorMethod(member: arkts.MethodDefinition): arkts.MethodDefinition { - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, - member.name, - arkts.factory.createFunctionExpression(member.scriptFunction), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, - false + static updateScriptFunction( + original: arkts.ScriptFunction, + config: Partial + ): arkts.ScriptFunction { + const newFunc: arkts.ScriptFunction = arkts.factory.updateScriptFunction( + original, + config.body ?? original.body, + arkts.factory.createFunctionSignature( + config.typeParams ?? original.typeParams, + config.params ?? original.params, + config.returnTypeAnnotation ?? original.returnTypeAnnotation, + config.hasReceiver ?? original.hasReceiver + ), + config.flags ?? original.flags, + config.modifiers ?? original.modifiers ); + if (!!config.key) { + newFunc.setIdent(config.key); + } + if (!!config.annotations) { + newFunc.setAnnotations(config.annotations); + } + return newFunc; } - /* - * create `@memo() _build(<>)`. + /** + * create ScriptFunction with configurations. */ - static transformBuildMethodWithOriginBuild( - method: arkts.MethodDefinition, - typeName: string, - optionsName: string, - isDecl?: boolean + static createScriptFunction(config: Partial): arkts.ScriptFunction { + const newFunc: arkts.ScriptFunction = arkts.factory.createScriptFunction( + config.body ?? undefined, + arkts.factory.createFunctionSignature( + config.typeParams ?? undefined, + config.params ?? [], + config.returnTypeAnnotation ?? undefined, + config.hasReceiver ?? false + ), + config.flags ?? arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, + config.modifiers ?? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); + if (!!config.key) { + newFunc.setIdent(config.key); + } + if (!!config.annotations) { + newFunc.setAnnotations(config.annotations); + } + return newFunc; + } + + /** + * update MethodDefinition with configurations. + */ + static updateMethodDefinition( + original: arkts.MethodDefinition, + config: PartialNested ): arkts.MethodDefinition { - const updateKey: arkts.Identifier = arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_BUILD); + const key: arkts.Identifier = config.key ?? original.name; + const newFunc: arkts.ScriptFunction = factory.updateScriptFunction(original.scriptFunction, { + ...config.function, + key, + }); + const newMethod: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( + original, + config.kind ?? original.kind, + key, + newFunc, + config.modifiers ?? original.modifiers, + config.isComputed ?? false + ); + if (!!config.overloads) { + newMethod.setOverloads(config.overloads); + } + return newMethod; + } - const scriptFunction: arkts.ScriptFunction = method.scriptFunction; - const updateScriptFunction = arkts.factory - .createScriptFunction( - scriptFunction.body, - arkts.FunctionSignature.createFunctionSignature( - scriptFunction.typeParams, - [ - factory.createStyleParameter(typeName), - factory.createContentParameter(), - factory.createInitializersOptionsParameter(optionsName), - ], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + /** + * create MethodDefinition with configurations. + */ + static createMethodDefinition( + config: PartialNestedExcept + ): arkts.MethodDefinition { + const newFunc: arkts.ScriptFunction = factory.createScriptFunction({ + ...config.function, + key: config.key, + }); + const newMethod: arkts.MethodDefinition = arkts.factory.createMethodDefinition( + config.kind ?? arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_NONE, + config.key, + newFunc, + config.modifiers ?? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + config.isComputed ?? false + ); + if (!!config.overloads) { + newMethod.setOverloads(config.overloads); + } + return newMethod; + } + + /** + * create intrinsic `@Retention({policy:"SOURCE"})` AnnotationDeclaration with configurations. + */ + static createIntrinsicAnnotationDeclaration( + config: PartialExcept + ): arkts.AnnotationDeclaration { + const intrinsicAnnotations: arkts.AnnotationUsage[] = [ + arkts.factory.create1AnnotationUsage(arkts.factory.createIdentifier('Retention'), [ + arkts.factory.createClassProperty( + arkts.factory.createIdentifier('policy'), + arkts.factory.createStringLiteral('SOURCE'), + undefined, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ), - scriptFunction.flags, - scriptFunction.modifiers - ) - .setAnnotations([annotation('memo')]); - - const modifiers: arkts.Es2pandaModifierFlags = isDecl - ? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT - : arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - updateKey, - arkts.factory.createFunctionExpression(updateScriptFunction), - modifiers, - false - ); + ]), + ]; + const newAnnotationDecl: arkts.AnnotationDeclaration = arkts.factory + .createAnnotationDeclaration(config.expr, config.properties ?? []) + .setAnnotations(intrinsicAnnotations); + return newAnnotationDecl; } /* @@ -277,9 +383,9 @@ export class factory { static PreprocessClassPropertyModifier(st: arkts.AstNode): arkts.AstNode { if (arkts.isClassProperty(st) && needDefiniteOrOptionalModifier(st)) { if (st.typeAnnotation && hasNullOrUndefinedType(st.typeAnnotation)) { - st.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL; + st.modifiers |= arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL; } else { - st.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DEFINITE; + st.modifiers |= arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DEFINITE; } } return st; diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index 847a830a5..f5870ac80 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -15,12 +15,14 @@ import * as arkts from '@koalaui/libarkts'; import { annotation } from '../common/arkts-utils'; -import { DecoratorNames } from './property-translators/utils'; +import { ImportCollector } from './import-collector'; +import { ARKUI_STATEMANAGEMENT_IMPORT_NAME, IMPORT_SOURCE_MAP_V2 } from '../common/predefines'; +import { DeclarationCollector } from '../common/declaration-collector'; export enum CustomComponentNames { - ENTRY_ANNOTATION_NAME = 'Entry', - COMPONENT_ANNOTATION_NAME = 'Component', - RESUABLE_ANNOTATION_NAME = 'Reusable', + ENTRY_ANNOTATION = 'Entry', + COMPONENT_ANNOTATION = 'Component', + RESUABLE_ANNOTATION = 'Reusable', COMPONENT_BUILD_ORI = 'build', COMPONENT_CONSTRUCTOR_ORI = 'constructor', COMPONENT_DEFAULT_IMPORT = 'arkui.component.customComponent', @@ -51,6 +53,21 @@ export enum Dollars { DOLLAR_RESOURCE = '$r', DOLLAR_RAWFILE = '$rawfile', DOLLAR_DOLLAR = '$$', + TRANSFORM_DOLLAR_RESOURCE = '_r', + TRANSFORM_DOLLAR_RAWFILE = '_rawfile', +} + +export enum MemoNames { + MEMO = 'memo', +} + +// IMPORT +export function findImportSource(importName: string): string { + const source = IMPORT_SOURCE_MAP_V2.get(importName); + if (!source) { + throw new Error(`cannot find "${importName}" in the import source map.`); + } + return source; } export function findLocalImport( @@ -67,22 +84,30 @@ export function findLocalImport( return importSpecifier?.local ?? importSpecifier?.imported; } -// TODO: currently, we forcely assume initializerOptions is named in pattern __Options_xxx -export function getCustomComponentNameFromInitializerOptions(name: string): string | undefined { - const prefix: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX; - if (name.startsWith(prefix)) { - return name.substring(prefix.length); - } -} - -export function getCustomComponentOptionsName(className: string): string { - return `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${className}`; -} - +// AST NODE export function isStatic(node: arkts.AstNode): boolean { return node.isStatic; } +/** + * Determine whether the type node includes null or undefined type. + * + * @param type type node + */ +export function hasNullOrUndefinedType(type: arkts.TypeNode): boolean { + let res: boolean = false; + if (arkts.isETSUnionType(type)) { + type.types.forEach((item: arkts.TypeNode) => { + res = res || hasNullOrUndefinedType(item); + }); + } + if (arkts.isETSUndefinedType(type) || arkts.isETSNullType(type)) { + res = true; + } + return res; +} + +// TYPE PARAMETER export function getTypeParamsFromClassDecl(node: arkts.ClassDeclaration | undefined): readonly arkts.TSTypeParameter[] { return node?.definition?.typeParams?.params ?? []; } @@ -91,41 +116,7 @@ export function getTypeNameFromTypeParameter(node: arkts.TSTypeParameter | undef return node?.name?.name; } -export function createOptionalClassProperty( - name: string, - property: arkts.ClassProperty, - stageManagementIdent: string, - modifiers: arkts.Es2pandaModifierFlags, - needMemo: boolean = false -): arkts.ClassProperty { - const newType: arkts.TypeNode | undefined = property.typeAnnotation?.clone(); - if (needMemo) { - newType?.setAnnotations([annotation('memo')]); - } - const newProperty = arkts.factory.createClassProperty( - arkts.factory.createIdentifier(name), - undefined, - stageManagementIdent.length ? createStageManagementType(stageManagementIdent, property) : newType, - modifiers, - false - ); - return arkts.classPropertySetOptional(newProperty, true); -} - -export function createStageManagementType( - stageManagementIdent: string, - property: arkts.ClassProperty -): arkts.ETSTypeReference { - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(stageManagementIdent), - arkts.factory.createTSTypeParameterInstantiation([ - property.typeAnnotation ? property.typeAnnotation.clone() : arkts.factory.createETSUndefinedType(), - ]) - ) - ); -} - +// GETTER export function getGettersFromClassDecl(definition: arkts.ClassDefinition): arkts.MethodDefinition[] { return definition.body.filter( (member) => @@ -134,6 +125,133 @@ export function getGettersFromClassDecl(definition: arkts.ClassDefinition): arkt ) as arkts.MethodDefinition[]; } +// ANNOTATION +export function hasPropertyInAnnotation(annotation: arkts.AnnotationUsage, propertyName: string): boolean { + return !!annotation.properties.find( + (annoProp: arkts.AstNode) => + arkts.isClassProperty(annoProp) && + annoProp.key && + arkts.isIdentifier(annoProp.key) && + annoProp.key.name === propertyName + ); +} + +// CUSTOM COMPONENT +export type CustomComponentInfo = { + name: string; + isDecl: boolean; + annotations: CustomComponentAnontations; +}; + +export type CustomComponentAnontations = { + component?: arkts.AnnotationUsage; + entry?: arkts.AnnotationUsage; + reusable?: arkts.AnnotationUsage; +}; + +export function isCustomComponentAnnotation( + anno: arkts.AnnotationUsage, + decoratorName: CustomComponentNames, + ignoreDecl?: boolean +): boolean { + if (!(!!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === decoratorName)) { + return false; + } + if (!ignoreDecl) { + const decl = arkts.getDecl(anno.expr); + if (!decl) { + return false; + } + const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; + if (!moduleName) { + return false; + } + DeclarationCollector.getInstance().collect(decl); + } + return true; +} + +export function collectCustomComponentScopeInfo( + node: arkts.ClassDeclaration | arkts.StructDeclaration +): CustomComponentInfo | undefined { + const definition: arkts.ClassDefinition | undefined = node.definition; + if (!definition || !definition?.ident?.name) { + return undefined; + } + const isStruct = arkts.isStructDeclaration(node); + const isDecl: boolean = arkts.hasModifierFlag(node, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE); + const isCustomComponentClassDecl = !isStruct && isDecl; + const shouldIgnoreDecl = isStruct || isDecl; + if (isCustomComponentClassDecl && definition.ident.name !== CustomComponentNames.COMPONENT_CLASS_NAME) { + return undefined; + } + let annotations: CustomComponentAnontations = {}; + if (!isCustomComponentClassDecl) { + let isCustomComponent: boolean = false; + for (const anno of definition.annotations) { + const isComponent = isCustomComponentAnnotation( + anno, + CustomComponentNames.COMPONENT_ANNOTATION, + shouldIgnoreDecl + ); + const isEntry = isCustomComponentAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION, shouldIgnoreDecl); + const isReusable = isCustomComponentAnnotation( + anno, + CustomComponentNames.RESUABLE_ANNOTATION, + shouldIgnoreDecl + ); + isCustomComponent ||= isComponent; + annotations = { + ...annotations, + ...(isComponent && !annotations?.component && { component: anno }), + ...(isEntry && !annotations?.entry && { entry: anno }), + ...(isReusable && !annotations?.reusable && { reusable: anno }), + }; + } + if (!isCustomComponent) { + return undefined; + } + } + return { + name: definition.ident.name, + isDecl, + annotations: annotations as CustomComponentAnontations, + }; +} + +export function isComponentStruct(node: arkts.StructDeclaration, scopeInfo: CustomComponentInfo): boolean { + return scopeInfo.name === node.definition.ident?.name; +} + +/** + * Determine whether it is a custom component. + * + * @param node class declaration node + */ +export function isCustomComponentClass(node: arkts.ClassDeclaration, scopeInfo: CustomComponentInfo): boolean { + if (!node.definition?.ident?.name) { + return false; + } + const name: string = node.definition.ident.name; + if (scopeInfo.isDecl) { + return name === CustomComponentNames.COMPONENT_CLASS_NAME; + } + return name === scopeInfo.name; +} + +export function isCustomComponentInterface(node: arkts.TSInterfaceDeclaration): boolean { + const checkPrefix = !!node.id?.name.startsWith(CustomComponentNames.COMPONENT_INTERFACE_PREFIX); + const checkComponent = node.annotations.some((anno) => + isCustomComponentAnnotation(anno, CustomComponentNames.COMPONENT_ANNOTATION) + ); + return checkPrefix && checkComponent; +} + +export function getCustomComponentOptionsName(className: string): string { + return `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${className}`; +} + +// MEMO export type MemoAstNode = | arkts.ScriptFunction | arkts.ETSParameterExpression @@ -143,14 +261,56 @@ export type MemoAstNode = | arkts.ArrowFunctionExpression | arkts.ETSUnionType; -export function isMemoAnnotation(node: arkts.AnnotationUsage, memoName: string): boolean { +export function hasMemoAnnotation(node: T): boolean { + return node.annotations.some((it) => isMemoAnnotation(it, MemoNames.MEMO)); +} + +export function collectMemoAnnotationImport(memoName: MemoNames = MemoNames.MEMO): void { + ImportCollector.getInstance().collectImport(memoName); +} + +export function collectMemoAnnotationSource(memoName: MemoNames = MemoNames.MEMO): void { + if (memoName === MemoNames.MEMO) { + ImportCollector.getInstance().collectSource(memoName, 'arkui.stateManagement.runtime'); + } +} + +export function findCanAddMemoFromTypeAnnotation( + typeAnnotation: arkts.AstNode | undefined +): typeAnnotation is arkts.ETSFunctionType { + if (!typeAnnotation) { + return false; + } + if (arkts.isETSFunctionType(typeAnnotation)) { + return true; + } else if (arkts.isETSUnionType(typeAnnotation)) { + return typeAnnotation.types.some((type) => arkts.isETSFunctionType(type)); + } + return false; +} + +export function findCanAddMemoFromParamExpression( + param: arkts.AstNode | undefined +): param is arkts.ETSParameterExpression { + if (!param) { + return false; + } + if (!arkts.isEtsParameterExpression(param)) { + return false; + } + const type = param.type; + return findCanAddMemoFromTypeAnnotation(type); +} + +export function isMemoAnnotation(node: arkts.AnnotationUsage, memoName: MemoNames): boolean { if (!(node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === memoName)) { return false; } return true; } -export function addMemoAnnotation(node: T, memoName: string = 'memo'): T { +export function addMemoAnnotation(node: T, memoName: MemoNames = MemoNames.MEMO): T { + collectMemoAnnotationSource(memoName); if (arkts.isETSUnionType(node)) { const functionType = node.types.find((type) => arkts.isETSFunctionType(type)); if (!functionType) { @@ -163,37 +323,10 @@ export function addMemoAnnotation(node: T, memoName: stri ...node.annotations.filter((it) => !isMemoAnnotation(it, memoName)), annotation(memoName), ]; + collectMemoAnnotationImport(memoName); if (arkts.isEtsParameterExpression(node)) { node.annotations = newAnnotations; return node; } return node.setAnnotations(newAnnotations) as T; } - -export function hasPropertyInAnnotation(annotation: arkts.AnnotationUsage, propertyName: string): boolean { - return !!annotation.properties.find( - (annoProp: arkts.AstNode) => - arkts.isClassProperty(annoProp) && - annoProp.key && - arkts.isIdentifier(annoProp.key) && - annoProp.key.name === propertyName - ); -} - -/** - * Determine whether the type node includes null or undefined type. - * - * @param type type node - */ -export function hasNullOrUndefinedType(type: arkts.TypeNode): boolean { - let res: boolean = false; - if (arkts.isETSUnionType(type)) { - type.types.forEach((item: arkts.TypeNode) => { - res = res || hasNullOrUndefinedType(item); - }); - } - if (arkts.isETSUndefinedType(type) || arkts.isETSNullType(type)) { - res = true; - } - return res; -} \ No newline at end of file diff --git a/koala-wrapper/native/include/common.h b/koala-wrapper/native/include/common.h index 77ed29cf8..399d28d22 100644 --- a/koala-wrapper/native/include/common.h +++ b/koala-wrapper/native/include/common.h @@ -32,7 +32,7 @@ string getString(KStringPtr ptr); char* getStringCopy(KStringPtr& ptr); -inline KUInt unpackUInt(const KByte* bytes); +KUInt unpackUInt(const KByte* bytes); es2panda_ContextState intToState(KInt state); diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index 31984c2dd..9adabf743 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -15,6 +15,28 @@ #include "common.h" +#include +#include +#include + +std::set globalStructInfo; +std::mutex g_structMutex; + +void impl_InsertGlobalStructInfo(KNativePointer contextPtr, KStringPtr& instancePtr) +{ + std::lock_guard lock(g_structMutex); + globalStructInfo.insert(getStringCopy(instancePtr)); + return; +} +KOALA_INTEROP_V2(InsertGlobalStructInfo, KNativePointer, KStringPtr); + +KBoolean impl_HasGlobalStructInfo(KNativePointer contextPtr, KStringPtr& instancePtr) +{ + std::lock_guard lock(g_structMutex); + return globalStructInfo.count(getStringCopy(instancePtr)); +} +KOALA_INTEROP_2(HasGlobalStructInfo, KBoolean, KNativePointer, KStringPtr); + KBoolean impl_ClassDefinitionIsFromStructConst(KNativePointer contextPtr, KNativePointer instancePtr) { auto context = reinterpret_cast(contextPtr); @@ -178,7 +200,7 @@ KOALA_INTEROP_1(ContextProgram, KNativePointer, KNativePointer) KNativePointer impl_ProgramAst(KNativePointer contextPtr, KNativePointer programPtr) { - auto context = reinterpret_cast(programPtr); + auto context = reinterpret_cast(contextPtr); auto program = reinterpret_cast(programPtr); return GetImpl()->ProgramAst(context, program); } @@ -252,12 +274,31 @@ static KNativePointer impl_ProgramExternalSources(KNativePointer contextPtr, KNa { auto context = reinterpret_cast(contextPtr); auto&& instance = reinterpret_cast(instancePtr); - std::size_t source_len = 0; - auto external_sources = GetImpl()->ProgramExternalSources(context, instance, &source_len); - return new std::vector(external_sources, external_sources + source_len); + std::size_t sourceLen = 0; + auto externalSources = GetImpl()->ProgramExternalSources(context, instance, &sourceLen); + return new std::vector(externalSources, externalSources + sourceLen); } KOALA_INTEROP_2(ProgramExternalSources, KNativePointer, KNativePointer, KNativePointer); +static KNativePointer impl_ProgramDirectExternalSources(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto&& instance = reinterpret_cast(instancePtr); + std::size_t sourceLen = 0; + auto externalSources = GetImpl()->ProgramDirectExternalSources(context, instance, &sourceLen); + return new std::vector(externalSources, externalSources + sourceLen); +} +KOALA_INTEROP_2(ProgramDirectExternalSources, KNativePointer, KNativePointer, KNativePointer); + +static KNativePointer impl_ProgramModuleNameConst(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto program = reinterpret_cast(instancePtr); + auto result = GetImpl()->ProgramModuleNameConst(context, program); + return new std::string(result); +} +KOALA_INTEROP_2(ProgramModuleNameConst, KNativePointer, KNativePointer, KNativePointer); + static KNativePointer impl_ExternalSourceName(KNativePointer instance) { auto&& _instance_ = reinterpret_cast(instance); @@ -269,9 +310,9 @@ KOALA_INTEROP_1(ExternalSourceName, KNativePointer, KNativePointer); static KNativePointer impl_ExternalSourcePrograms(KNativePointer instance) { auto&& _instance_ = reinterpret_cast(instance); - std::size_t program_len = 0; - auto programs = GetImpl()->ExternalSourcePrograms(_instance_, &program_len); - return new std::vector(programs, programs + program_len); + std::size_t programLen = 0; + auto programs = GetImpl()->ExternalSourcePrograms(_instance_, &programLen); + return new std::vector(programs, programs + programLen); } KOALA_INTEROP_1(ExternalSourcePrograms, KNativePointer, KNativePointer); @@ -380,6 +421,14 @@ KNativePointer impl_ProgramFileNameWithExtensionConst(KNativePointer contextPtr, } KOALA_INTEROP_2(ProgramFileNameWithExtensionConst, KNativePointer, KNativePointer, KNativePointer) +KBoolean impl_ProgramIsASTLoweredConst(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto context = reinterpret_cast(contextPtr); + auto &&instance = reinterpret_cast(instancePtr); + return GetImpl()->ProgramIsASTLoweredConst(context, instance); +} +KOALA_INTEROP_2(ProgramIsASTLoweredConst, KBoolean, KNativePointer, KNativePointer); + KNativePointer impl_ETSParserGetGlobalProgramAbsName(KNativePointer contextPtr) { auto context = reinterpret_cast(contextPtr); diff --git a/koala-wrapper/native/src/common.cc b/koala-wrapper/native/src/common.cc index eb7a6acb5..e6c30a48b 100644 --- a/koala-wrapper/native/src/common.cc +++ b/koala-wrapper/native/src/common.cc @@ -98,6 +98,56 @@ inline KUInt unpackUInt(const KByte* bytes) { ); } +void impl_MemInitialize() +{ + GetImpl()->MemInitialize(); +} +KOALA_INTEROP_V0(MemInitialize) + +void impl_MemFinalize() +{ + GetImpl()->MemFinalize(); +} +KOALA_INTEROP_V0(MemFinalize) + +KNativePointer impl_CreateGlobalContext(KNativePointer configPtr, KStringArray externalFileListPtr, + KInt fileNum, KBoolean lspUsage) +{ + auto config = reinterpret_cast(configPtr); + + const std::size_t headerLen = 4; + + const char** externalFileList = new const char* [fileNum]; + std::size_t position = headerLen; + std::size_t strLen; + for (std::size_t i = 0; i < static_cast(fileNum); ++i) { + strLen = unpackUInt(externalFileListPtr + position); + position += headerLen; + externalFileList[i] = strdup(std::string( + reinterpret_cast(externalFileListPtr + position), strLen).c_str()); + position += strLen; + } + + return GetImpl()->CreateGlobalContext(config, externalFileList, fileNum, lspUsage); +} +KOALA_INTEROP_4(CreateGlobalContext, KNativePointer, KNativePointer, KStringArray, KInt, KBoolean) + +void impl_DestroyGlobalContext(KNativePointer globalContextPtr) +{ + auto context = reinterpret_cast(globalContextPtr); + GetImpl()->DestroyGlobalContext(context); +} +KOALA_INTEROP_V1(DestroyGlobalContext, KNativePointer) + +KNativePointer impl_CreateCacheContextFromFile(KNativePointer configPtr, KStringPtr& fileName, + KNativePointer globalContext, KBoolean isExternal) +{ + auto config = reinterpret_cast(configPtr); + auto context = reinterpret_cast(globalContext); + return GetImpl()->CreateCacheContextFromFile(config, getStringCopy(fileName), context, isExternal); +} +KOALA_INTEROP_4(CreateCacheContextFromFile, KNativePointer, KNativePointer, KStringPtr, KNativePointer, KBoolean) + KNativePointer impl_CreateConfig(KInt argc, KStringArray argvPtr) { const std::size_t headerLen = 4; @@ -170,8 +220,20 @@ TODO: NOT FROM API (shouldn't be there) ----------------------------------------------------------------------------------------------------------------------------- */ -es2panda_AstNode * cachedParentNode; -es2panda_Context * cachedContext; +KNativePointer impl_AstNodeProgram(KNativePointer contextPtr, KNativePointer instancePtr) +{ + auto _context = reinterpret_cast(contextPtr); + auto _receiver = reinterpret_cast(instancePtr); + + if (GetImpl()->AstNodeIsProgramConst(_context, _receiver)) { + return GetImpl()->ETSModuleProgram(_context, _receiver); + } + return impl_AstNodeProgram(_context, GetImpl()->AstNodeParent(_context, _receiver)); +} +KOALA_INTEROP_2(AstNodeProgram, KNativePointer, KNativePointer, KNativePointer) + +thread_local es2panda_AstNode *cachedParentNode; +thread_local es2panda_Context *cachedContext; static void changeParent(es2panda_AstNode *child) { @@ -206,7 +268,7 @@ KNativePointer impl_AstNodeUpdateChildren(KNativePointer contextPtr, KNativePoin } KOALA_INTEROP_2(AstNodeUpdateChildren, KNativePointer, KNativePointer, KNativePointer) -std::vector cachedChildren; +thread_local std::vector cachedChildren; static void visitChild(es2panda_AstNode *node) { cachedChildren.emplace_back(node); diff --git a/koala-wrapper/native/src/generated/bridges.cc b/koala-wrapper/native/src/generated/bridges.cc index e1de4b1a1..d89b383f9 100644 --- a/koala-wrapper/native/src/generated/bridges.cc +++ b/koala-wrapper/native/src/generated/bridges.cc @@ -2707,16 +2707,6 @@ void impl_TSTypeAliasDeclarationSetTypeParameters(KNativePointer context, KNativ } KOALA_INTEROP_V3(TSTypeAliasDeclarationSetTypeParameters, KNativePointer, KNativePointer, KNativePointer); -KNativePointer impl_TSTypeAliasDeclarationAnnotations(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - std::size_t length; - auto result = GetImpl()->TSTypeAliasDeclarationAnnotations(_context, _receiver, &length); - return new std::vector(result, result + length); -} -KOALA_INTEROP_2(TSTypeAliasDeclarationAnnotations, KNativePointer, KNativePointer, KNativePointer); - KNativePointer impl_TSTypeAliasDeclarationAnnotationsConst(KNativePointer context, KNativePointer receiver) { const auto _context = reinterpret_cast(context); @@ -3325,16 +3315,6 @@ void impl_ScriptFunctionAddFlag(KNativePointer context, KNativePointer receiver, } KOALA_INTEROP_V3(ScriptFunctionAddFlag, KNativePointer, KNativePointer, KInt); -void impl_ScriptFunctionAddModifier(KNativePointer context, KNativePointer receiver, KInt flags) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - const auto _flags = static_cast(flags); - GetImpl()->ScriptFunctionAddModifier(_context, _receiver, _flags); - return ; -} -KOALA_INTEROP_V3(ScriptFunctionAddModifier, KNativePointer, KNativePointer, KInt); - KUInt impl_ScriptFunctionFormalParamsLengthConst(KNativePointer context, KNativePointer receiver) { const auto _context = reinterpret_cast(context); @@ -4681,6 +4661,58 @@ void impl_ETSTupleSetTypeAnnotationsList(KNativePointer context, KNativePointer } KOALA_INTEROP_V4(ETSTupleSetTypeAnnotationsList, KNativePointer, KNativePointer, KNativePointerArray, KUInt); +KNativePointer impl_CreateTryStatement(KNativePointer context, KNativePointer block, KNativePointerArray catchClauses, KUInt catchClausesSequenceLength, KNativePointer finalizer, KNativePointerArray finalizerInsertionsLabelPair, KUInt finalizerInsertionsLabelPairSequenceLength, KNativePointerArray finalizerInsertionsStatement, KUInt finalizerInsertionsStatementSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _block = reinterpret_cast(block); + const auto _catchClauses = reinterpret_cast(catchClauses); + const auto _catchClausesSequenceLength = static_cast(catchClausesSequenceLength); + const auto _finalizer = reinterpret_cast(finalizer); + const auto _finalizerInsertionsLabelPair = reinterpret_cast(finalizerInsertionsLabelPair); + const auto _finalizerInsertionsLabelPairSequenceLength = static_cast(finalizerInsertionsLabelPairSequenceLength); + const auto _finalizerInsertionsStatement = reinterpret_cast(finalizerInsertionsStatement); + const auto _finalizerInsertionsStatementSequenceLength = static_cast(finalizerInsertionsStatementSequenceLength); + auto result = GetImpl()->CreateTryStatement(_context, _block, _catchClauses, _catchClausesSequenceLength, _finalizer, _finalizerInsertionsLabelPair, _finalizerInsertionsLabelPairSequenceLength, _finalizerInsertionsStatement, _finalizerInsertionsStatementSequenceLength); + return result; +} +KOALA_INTEROP_9(CreateTryStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KNativePointerArray, KUInt, KNativePointerArray, KUInt); + +KNativePointer impl_UpdateTryStatement(KNativePointer context, KNativePointer original, KNativePointer block, KNativePointerArray catchClauses, KUInt catchClausesSequenceLength, KNativePointer finalizer, KNativePointerArray finalizerInsertionsLabelPair, KUInt finalizerInsertionsLabelPairSequenceLength, KNativePointerArray finalizerInsertionsStatement, KUInt finalizerInsertionsStatementSequenceLength) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _block = reinterpret_cast(block); + const auto _catchClauses = reinterpret_cast(catchClauses); + const auto _catchClausesSequenceLength = static_cast(catchClausesSequenceLength); + const auto _finalizer = reinterpret_cast(finalizer); + const auto _finalizerInsertionsLabelPair = reinterpret_cast(finalizerInsertionsLabelPair); + const auto _finalizerInsertionsLabelPairSequenceLength = static_cast(finalizerInsertionsLabelPairSequenceLength); + const auto _finalizerInsertionsStatement = reinterpret_cast(finalizerInsertionsStatement); + const auto _finalizerInsertionsStatementSequenceLength = static_cast(finalizerInsertionsStatementSequenceLength); + auto result = GetImpl()->UpdateTryStatement(_context, _original, _block, _catchClauses, _catchClausesSequenceLength, _finalizer, _finalizerInsertionsLabelPair, _finalizerInsertionsLabelPairSequenceLength, _finalizerInsertionsStatement, _finalizerInsertionsStatementSequenceLength); + return result; +} +KOALA_INTEROP_10(UpdateTryStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KNativePointerArray, KUInt, KNativePointerArray, KUInt); + +KNativePointer impl_CreateTryStatement1(KNativePointer context, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->CreateTryStatement1(_context, _other); + return result; +} +KOALA_INTEROP_2(CreateTryStatement1, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateTryStatement1(KNativePointer context, KNativePointer original, KNativePointer other) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _other = reinterpret_cast(other); + auto result = GetImpl()->UpdateTryStatement1(_context, _original, _other); + return result; +} +KOALA_INTEROP_3(UpdateTryStatement1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + KNativePointer impl_TryStatementFinallyBlockConst(KNativePointer context, KNativePointer receiver) { const auto _context = reinterpret_cast(context); @@ -6639,16 +6671,6 @@ KNativePointer impl_ImportDeclarationSpecifiersConst(KNativePointer context, KNa } KOALA_INTEROP_2(ImportDeclarationSpecifiersConst, KNativePointer, KNativePointer, KNativePointer); -KNativePointer impl_ImportDeclarationSpecifiers(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - std::size_t length; - auto result = GetImpl()->ImportDeclarationSpecifiers(_context, _receiver, &length); - return new std::vector(result, result + length); -} -KOALA_INTEROP_2(ImportDeclarationSpecifiers, KNativePointer, KNativePointer, KNativePointer); - KBoolean impl_ImportDeclarationIsTypeKindConst(KNativePointer context, KNativePointer receiver) { const auto _context = reinterpret_cast(context); @@ -6735,15 +6757,6 @@ KNativePointer impl_UpdateETSImportDeclaration(KNativePointer context, KNativePo } KOALA_INTEROP_6(UpdateETSImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt); -KNativePointer impl_ETSImportDeclarationAssemblerName(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - auto result = GetImpl()->ETSImportDeclarationAssemblerName(_context, _receiver); - return new std::string(result); -} -KOALA_INTEROP_2(ETSImportDeclarationAssemblerName, KNativePointer, KNativePointer, KNativePointer); - KNativePointer impl_ETSImportDeclarationAssemblerNameConst(KNativePointer context, KNativePointer receiver) { const auto _context = reinterpret_cast(context); diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 78314c0cc..0c8bfb0a0 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -21,6 +21,7 @@ import { registerNativeModuleLibraryName, loadNativeModuleLibrary, KDouble, + KStringArrayPtr, } from '@koalaui/interop'; import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generated/Es2pandaNativeModule'; import * as path from 'path'; @@ -734,7 +735,12 @@ export class Es2pandaNativeModule { _ProgramExternalSources(context: KNativePointer, instance: KNativePointer): KNativePointer { throw new Error('Not implemented'); } - + _ProgramDirectExternalSources(context: KNativePointer, instance: KNativePointer): KNativePointer { + throw new Error('Not implemented'); + } + _AstNodeProgram(context: KNativePointer, instance: KNativePointer): KNativePointer { + throw new Error('Not implemented'); + } _ExternalSourceName(instance: KNativePointer): KNativePointer { throw new Error('Not implemented'); } @@ -793,6 +799,10 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _ProgramIsASTLoweredConst(context: KPtr, program: KPtr): KBoolean { + throw new Error('Not implemented'); + } + _ETSParserGetGlobalProgramAbsName(context: KNativePointer): KNativePointer { throw new Error('Not implemented'); } @@ -825,6 +835,10 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _ProgramModuleNameConst(context: KPtr, program: KPtr): KNativePointer { + throw new Error('Not implemented'); + } + _AstNodeRangeConst(context: KNativePointer, node: KNativePointer): KNativePointer { throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); } @@ -842,7 +856,37 @@ export class Es2pandaNativeModule { } _IsArrayExpression(node: KPtr): KBoolean { - throw new Error('Not implemented'); + throw new Error('IsArrayExpression was not overloaded by native module initialization'); + } + + _MemInitialize(): void { + throw new Error('MemInitialize was not overloaded by native module initialization'); + } + + _MemFinalize(): void { + throw new Error('MemFinalize was not overloaded by native module initialization'); + } + + _CreateGlobalContext(configPtr: KNativePointer, externalFileList: KStringArrayPtr, fileNum: KInt, + lspUsage: boolean): KNativePointer { + throw new Error('CreateGlobalContext was not overloaded by native module initialization'); + } + + _DestroyGlobalContext(contextPtr: KNativePointer): void { + throw new Error('DestroyGlobalContext was not overloaded by native module initialization'); + } + + _CreateCacheContextFromFile(configPtr: KNativePointer, filename: string, globalContext: KNativePointer, + isExternal: KBoolean): KNativePointer { + throw new Error('CreateCacheContextFromFile was not overloaded by native module initialization'); + } + + _InsertGlobalStructInfo(context: KNativePointer, str: String): void { + throw new Error('InsertGlobalStructInfo was not overloaded by native module initialization'); + } + + _HasGlobalStructInfo(context: KNativePointer, str: String): KBoolean { + throw new Error('HasGlobalStructInfo was not overloaded by native module initialization'); } } diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index 536c1ef3f..0f9c3e283 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { updateNodeByNode } from "../utilities/private" +import { updateNodeByNode } from '../utilities/private'; import { ArrowFunctionExpression, AssignmentExpression, @@ -29,10 +29,10 @@ import { StructDeclaration, VariableDeclaration, VariableDeclarator, - ETSStringLiteralType -} from "../types" -import { MemberExpression } from "../to-be-generated/MemberExpression" -import { AstNode } from "../peers/AstNode" + ETSStringLiteralType, +} from '../types'; +import { MemberExpression } from '../to-be-generated/MemberExpression'; +import { AstNode } from '../peers/AstNode'; import { AnnotationUsage, BinaryExpression, @@ -74,385 +74,464 @@ import { ObjectExpression, Property, TemplateLiteral, - ArrayExpression -} from "../../generated" -import { - Es2pandaModifierFlags -} from "../../generated/Es2pandaEnums" -import { - classPropertySetOptional, - hasModifierFlag -} from "../utilities/public" -import { updateIdentifier } from "../node-utilities/Identifier" -import { updateCallExpression } from "../node-utilities/CallExpression" -import { updateExpressionStatement } from "../node-utilities/ExpressionStatement" -import { updateMemberExpression } from "../node-utilities/MemberExpression" -import { updateFunctionDeclaration } from "../node-utilities/FunctionDeclaration" -import { updateBlockStatement } from "../node-utilities/BlockStatement" -import { updateArrowFunctionExpression } from "../node-utilities/ArrowFunctionExpression" -import { updateScriptFunction } from "../node-utilities/ScriptFunction" -import { updateStringLiteral } from "../node-utilities/StringLiteral" -import { updateNumberLiteral } from "../node-utilities/NumberLiteral" -import { updateETSParameterExpression } from "../node-utilities/ETSParameterExpression" -import { updateTSTypeParameter } from "../node-utilities/TSTypeParameter" -import { updateTSTypeParameterDeclaration } from "../node-utilities/TSTypeParameterDeclaration" -import { updateETSPrimitiveType } from "../node-utilities/ETSPrimitiveType" -import { updateETSTypeReference } from "../node-utilities/ETSTypeReference" -import { updateETSTypeReferencePart } from "../node-utilities/ETSTypeReferencePart" -import { updateETSImportDeclaration } from "../node-utilities/ETSImportDeclaration" -import { updateImportSpecifier } from "../node-utilities/ImportSpecifier" -import { updateVariableDeclaration } from "../node-utilities/VariableDeclaration" -import { updateVariableDeclarator } from "../node-utilities/VariableDeclarator" -import { updateETSUnionType } from "../node-utilities/ETSUnionType" -import { updateReturnStatement } from "../node-utilities/ReturnStatement" -import { updateIfStatement } from "../node-utilities/IfStatement" -import { updateBinaryExpression } from "../node-utilities/BinaryExpression" -import { updateClassDeclaration } from "../node-utilities/ClassDeclaration" -import { updateStructDeclaration } from "../node-utilities/StructDeclaration" -import { updateClassDefinition } from "../node-utilities/ClassDefinition" -import { updateClassProperty } from "../node-utilities/ClassProperty" -import { updateETSFunctionType } from "../node-utilities/ETSFunctionType" -import { updateFunctionExpression } from "../node-utilities/FunctionExpression" -import { updateMethodDefinition } from "../node-utilities/MethodDefinition" -import { updateSuperExpression } from "../node-utilities/SuperExpression" -import { updateTSTypeParameterInstantiation } from "../node-utilities/TSTypeParameterInstantiation" -import { updateTSInterfaceDeclaration } from "../node-utilities/TSInterfaceDeclaration" -import { updateTSInterfaceBody } from "../node-utilities/TSInterfaceBody" -import { updateUndefinedLiteral } from "../node-utilities/UndefinedLiteral" -import { updateAnnotationUsage, update1AnnotationUsage } from "../node-utilities/AnnotationUsage" -import { updateAssignmentExpression } from "../node-utilities/AssignmentExpression" -import { updateETSUndefinedType } from "../node-utilities/ETSUndefinedType" -import { updateConditionalExpression } from "../node-utilities/ConditionalExpression" -import { updateTSAsExpression } from "../node-utilities/TSAsExpression" -import { updateThisExpression } from "../node-utilities/ThisExpression" -import { updateTSTypeAliasDeclaration } from "../node-utilities/TSTypeAliasDeclaration" -import { updateTSNonNullExpression } from "../node-utilities/TSNonNullExpression" -import { updateChainExpression } from "../node-utilities/ChainExpression" -import { updateBlockExpression } from "../node-utilities/BlockExpression" -import { updateNullLiteral } from "../node-utilities/NullLiteral" -import { updateETSNewClassInstanceExpression } from "../node-utilities/ETSNewClassInstanceExpression" -import { updateObjectExpression } from "../node-utilities/ObjectExpression" -import { updateProperty } from "../node-utilities/Property" -import { updateTemplateLiteral } from "../node-utilities/TemplateLiteral" -import { updateArrayExpression } from "../node-utilities/ArrayExpression"; + ArrayExpression, + AnnotationDeclaration, + TryStatement, +} from '../../generated'; +import { Es2pandaModifierFlags } from '../../generated/Es2pandaEnums'; +import { classPropertySetOptional, hasModifierFlag } from '../utilities/public'; +import { updateIdentifier } from '../node-utilities/Identifier'; +import { updateCallExpression } from '../node-utilities/CallExpression'; +import { updateExpressionStatement } from '../node-utilities/ExpressionStatement'; +import { updateMemberExpression } from '../node-utilities/MemberExpression'; +import { updateFunctionDeclaration } from '../node-utilities/FunctionDeclaration'; +import { updateBlockStatement } from '../node-utilities/BlockStatement'; +import { updateArrowFunctionExpression } from '../node-utilities/ArrowFunctionExpression'; +import { updateScriptFunction } from '../node-utilities/ScriptFunction'; +import { updateStringLiteral } from '../node-utilities/StringLiteral'; +import { updateNumberLiteral } from '../node-utilities/NumberLiteral'; +import { updateETSParameterExpression } from '../node-utilities/ETSParameterExpression'; +import { updateTSTypeParameter } from '../node-utilities/TSTypeParameter'; +import { updateTSTypeParameterDeclaration } from '../node-utilities/TSTypeParameterDeclaration'; +import { updateETSPrimitiveType } from '../node-utilities/ETSPrimitiveType'; +import { updateETSTypeReference } from '../node-utilities/ETSTypeReference'; +import { updateETSTypeReferencePart } from '../node-utilities/ETSTypeReferencePart'; +import { updateETSImportDeclaration } from '../node-utilities/ETSImportDeclaration'; +import { updateImportSpecifier } from '../node-utilities/ImportSpecifier'; +import { updateVariableDeclaration } from '../node-utilities/VariableDeclaration'; +import { updateVariableDeclarator } from '../node-utilities/VariableDeclarator'; +import { updateETSUnionType } from '../node-utilities/ETSUnionType'; +import { updateReturnStatement } from '../node-utilities/ReturnStatement'; +import { updateIfStatement } from '../node-utilities/IfStatement'; +import { updateBinaryExpression } from '../node-utilities/BinaryExpression'; +import { updateClassDeclaration } from '../node-utilities/ClassDeclaration'; +import { updateStructDeclaration } from '../node-utilities/StructDeclaration'; +import { updateClassDefinition } from '../node-utilities/ClassDefinition'; +import { updateClassProperty } from '../node-utilities/ClassProperty'; +import { updateETSFunctionType } from '../node-utilities/ETSFunctionType'; +import { updateFunctionExpression } from '../node-utilities/FunctionExpression'; +import { updateMethodDefinition } from '../node-utilities/MethodDefinition'; +import { updateSuperExpression } from '../node-utilities/SuperExpression'; +import { updateTSTypeParameterInstantiation } from '../node-utilities/TSTypeParameterInstantiation'; +import { updateTSInterfaceDeclaration } from '../node-utilities/TSInterfaceDeclaration'; +import { updateTSInterfaceBody } from '../node-utilities/TSInterfaceBody'; +import { updateUndefinedLiteral } from '../node-utilities/UndefinedLiteral'; +import { updateAnnotationUsage, update1AnnotationUsage } from '../node-utilities/AnnotationUsage'; +import { updateAssignmentExpression } from '../node-utilities/AssignmentExpression'; +import { updateETSUndefinedType } from '../node-utilities/ETSUndefinedType'; +import { updateConditionalExpression } from '../node-utilities/ConditionalExpression'; +import { updateTSAsExpression } from '../node-utilities/TSAsExpression'; +import { updateThisExpression } from '../node-utilities/ThisExpression'; +import { updateTSTypeAliasDeclaration } from '../node-utilities/TSTypeAliasDeclaration'; +import { updateTSNonNullExpression } from '../node-utilities/TSNonNullExpression'; +import { updateChainExpression } from '../node-utilities/ChainExpression'; +import { updateBlockExpression } from '../node-utilities/BlockExpression'; +import { updateNullLiteral } from '../node-utilities/NullLiteral'; +import { updateETSNewClassInstanceExpression } from '../node-utilities/ETSNewClassInstanceExpression'; +import { updateObjectExpression } from '../node-utilities/ObjectExpression'; +import { updateProperty } from '../node-utilities/Property'; +import { updateTemplateLiteral } from '../node-utilities/TemplateLiteral'; +import { updateArrayExpression } from '../node-utilities/ArrayExpression'; +import { updateAnnotationDeclaration } from '../node-utilities/AnnotationDeclaration'; +import { updateTryStatement } from '../node-utilities/TryStatement'; export const factory = { - get createIdentifier() { - return Identifier.create2Identifier + get createIdentifier(): (...args: Parameters) => Identifier { + return Identifier.create2Identifier; + }, + get updateIdentifier(): (...args: Parameters) => Identifier { + return updateIdentifier; }, - get updateIdentifier() { - return updateIdentifier + get createCallExpression(): (...args: Parameters) => CallExpression { + return CallExpression.create; }, - get createCallExpression() { - return CallExpression.create + get updateCallExpression(): (...args: Parameters) => CallExpression { + return updateCallExpression; }, - get updateCallExpression() { - return updateCallExpression + get createExpressionStatement(): (...args: Parameters) => ExpressionStatement { + return ExpressionStatement.create; }, - get createExpressionStatement() { - return ExpressionStatement.create + get updateExpressionStatement(): (...args: Parameters) => ExpressionStatement { + return updateExpressionStatement; }, - get updateExpressionStatement() { - return updateExpressionStatement + get createMemberExpression(): (...args: Parameters) => MemberExpression { + return MemberExpression.create; }, - get createMemberExpression() { - return MemberExpression.create + get updateMemberExpression(): (...args: Parameters) => MemberExpression { + return updateMemberExpression; }, - get updateMemberExpression() { - return updateMemberExpression + get createEtsScript(): (...args: Parameters) => EtsScript { + return EtsScript.createFromSource; }, - get createEtsScript() { - return EtsScript.createFromSource + get updateEtsScript(): (...args: Parameters) => EtsScript { + return EtsScript.updateByStatements; }, - get updateEtsScript() { - return EtsScript.updateByStatements + get createFunctionDeclaration(): (...args: Parameters) => FunctionDeclaration { + return FunctionDeclaration.create; }, - get createFunctionDeclaration() { - return FunctionDeclaration.create + get updateFunctionDeclaration(): (...args: Parameters) => FunctionDeclaration { + return updateFunctionDeclaration; }, - get updateFunctionDeclaration() { - return updateFunctionDeclaration + get createBlock(): (...args: Parameters) => BlockStatement { + return BlockStatement.createBlockStatement; }, - get createBlock() { - return BlockStatement.createBlockStatement + get updateBlock(): (...args: Parameters) => BlockStatement { + return updateBlockStatement; }, - get updateBlock() { - return updateBlockStatement + get createArrowFunction(): (...args: Parameters) => ArrowFunctionExpression { + return ArrowFunctionExpression.create; }, - get createArrowFunction() { - return ArrowFunctionExpression.create + get updateArrowFunction(): (...args: Parameters) => ArrowFunctionExpression { + return updateArrowFunctionExpression; }, - get updateArrowFunction() { - return updateArrowFunctionExpression + get createScriptFunction(): (...args: Parameters) => ScriptFunction { + return ScriptFunction.createScriptFunction; }, - get createScriptFunction() { - return ScriptFunction.createScriptFunction + get updateScriptFunction(): (...args: Parameters) => ScriptFunction { + return updateScriptFunction; }, - get updateScriptFunction() { - return updateScriptFunction + get createStringLiteral(): (...args: Parameters) => StringLiteral { + return StringLiteral.create1StringLiteral; }, - get createStringLiteral() { - return StringLiteral.create1StringLiteral + get updateStringLiteral(): (...args: Parameters) => StringLiteral { + return updateStringLiteral; }, - get updateStringLiteral() { - return updateStringLiteral + get create1StringLiteral(): (...args: Parameters) => StringLiteral { + return StringLiteral.create1StringLiteral; }, - get create1StringLiteral() { - return StringLiteral.create1StringLiteral + get update1StringLiteral(): (...args: Parameters) => StringLiteral { + return updateStringLiteral; }, - get update1StringLiteral() { - return updateStringLiteral + get createNumericLiteral(): (...args: Parameters) => NumberLiteral { + return NumberLiteral.create; }, - get createNumericLiteral() { - return NumberLiteral.create + get updateNumericLiteral(): (...args: Parameters) => NumberLiteral { + return updateNumberLiteral; }, - get updateNumericLiteral() { - return updateNumberLiteral + get createParameterDeclaration(): ( + ...args: Parameters + ) => ETSParameterExpression { + return ETSParameterExpression.create; }, - get createParameterDeclaration() { - return ETSParameterExpression.create + get updateParameterDeclaration(): ( + ...args: Parameters + ) => ETSParameterExpression { + return updateETSParameterExpression; }, - get updateParameterDeclaration() { - return updateETSParameterExpression + get createTypeParameter(): (...args: Parameters) => TSTypeParameter { + return TSTypeParameter.createTSTypeParameter; }, - get createTypeParameter() { - return TSTypeParameter.createTSTypeParameter + get updateTypeParameter(): (...args: Parameters) => TSTypeParameter { + return updateTSTypeParameter; }, - get updateTypeParameter() { - return updateTSTypeParameter + get createTypeParameterDeclaration(): ( + ...args: Parameters + ) => TSTypeParameterDeclaration { + return TSTypeParameterDeclaration.createTSTypeParameterDeclaration; }, - get createTypeParameterDeclaration() { - return TSTypeParameterDeclaration.createTSTypeParameterDeclaration + get updateTypeParameterDeclaration(): ( + ...args: Parameters + ) => TSTypeParameterDeclaration { + return updateTSTypeParameterDeclaration; }, - get updateTypeParameterDeclaration() { - return updateTSTypeParameterDeclaration + get createPrimitiveType(): ( + ...args: Parameters + ) => ETSPrimitiveType { + return ETSPrimitiveType.createETSPrimitiveType; }, - get createPrimitiveType() { - return ETSPrimitiveType.createETSPrimitiveType + get updatePrimitiveType(): (...args: Parameters) => ETSPrimitiveType { + return updateETSPrimitiveType; }, - get updatePrimitiveType() { - return updateETSPrimitiveType + get createTypeReference(): ( + ...args: Parameters + ) => ETSTypeReference { + return ETSTypeReference.createETSTypeReference; }, - get createTypeReference() { - return ETSTypeReference.createETSTypeReference + get updateTypeReference(): (...args: Parameters) => ETSTypeReference { + return updateETSTypeReference; }, - get updateTypeReference() { - return updateETSTypeReference + get createTypeReferencePart(): ( + ...args: Parameters + ) => ETSTypeReferencePart { + return ETSTypeReferencePart.createETSTypeReferencePart; }, - get createTypeReferencePart() { - return ETSTypeReferencePart.createETSTypeReferencePart + get updateTypeReferencePart(): (...args: Parameters) => ETSTypeReferencePart { + return updateETSTypeReferencePart; }, - get updateTypeReferencePart() { - return updateETSTypeReferencePart + get createImportDeclaration(): ( + ...args: Parameters + ) => ETSImportDeclaration { + return ETSImportDeclaration.createETSImportDeclaration; }, - get createImportDeclaration() { - return ETSImportDeclaration.createETSImportDeclaration + get updateImportDeclaration(): (...args: Parameters) => ETSImportDeclaration { + return updateETSImportDeclaration; }, - get updateImportDeclaration() { - return updateETSImportDeclaration + get createImportSpecifier(): ( + ...args: Parameters + ) => ImportSpecifier { + return ImportSpecifier.createImportSpecifier; }, - get createImportSpecifier() { - return ImportSpecifier.createImportSpecifier + get updateImportSpecifier(): (...args: Parameters) => ImportSpecifier { + return updateImportSpecifier; }, - get updateImportSpecifier() { - return updateImportSpecifier + get createVariableDeclaration(): (...args: Parameters) => VariableDeclaration { + return VariableDeclaration.create; }, - get createVariableDeclaration() { - return VariableDeclaration.create + get updateVariableDeclaration(): (...args: Parameters) => VariableDeclaration { + return updateVariableDeclaration; }, - get updateVariableDeclaration() { - return updateVariableDeclaration + get createVariableDeclarator(): (...args: Parameters) => VariableDeclarator { + return VariableDeclarator.create; }, - get createVariableDeclarator() { - return VariableDeclarator.create + get updateVariableDeclarator(): (...args: Parameters) => VariableDeclarator { + return updateVariableDeclarator; }, - get updateVariableDeclarator() { - return updateVariableDeclarator + get createUnionType(): (...args: Parameters) => ETSUnionType { + return ETSUnionType.createETSUnionType; }, - get createUnionType() { - return ETSUnionType.createETSUnionType + get updateUnionType(): (...args: Parameters) => ETSUnionType { + return updateETSUnionType; }, - get updateUnionType() { - return updateETSUnionType + get createReturnStatement(): ( + ...args: Parameters + ) => ReturnStatement { + return ReturnStatement.create1ReturnStatement; }, - get createReturnStatement() { - return ReturnStatement.create1ReturnStatement + get updateReturnStatement(): (...args: Parameters) => ReturnStatement { + return updateReturnStatement; }, - get updateReturnStatement() { - return updateReturnStatement + get createIfStatement(): (...args: Parameters) => IfStatement { + return IfStatement.create; }, - get createIfStatement() { - return IfStatement.create + get updateIfStatement(): (...args: Parameters) => IfStatement { + return updateIfStatement; }, - get updateIfStatement() { - return updateIfStatement + get createBinaryExpression(): ( + ...args: Parameters + ) => BinaryExpression { + return BinaryExpression.createBinaryExpression; }, - get createBinaryExpression() { - return BinaryExpression.createBinaryExpression + get updateBinaryExpression(): (...args: Parameters) => BinaryExpression { + return updateBinaryExpression; }, - get updateBinaryExpression() { - return updateBinaryExpression + get createClassDeclaration(): ( + ...args: Parameters + ) => ClassDeclaration { + return ClassDeclaration.createClassDeclaration; }, - get createClassDeclaration() { - return ClassDeclaration.createClassDeclaration + get updateClassDeclaration(): (...args: Parameters) => ClassDeclaration { + return updateClassDeclaration; }, - get updateClassDeclaration() { - return updateClassDeclaration + get createStructDeclaration(): (...args: Parameters) => StructDeclaration { + return StructDeclaration.create; }, - get createStructDeclaration() { - return StructDeclaration.create + get updateStructDeclaration(): (...args: Parameters) => StructDeclaration { + return updateStructDeclaration; }, - get updateStructDeclaration() { - return updateStructDeclaration + get createClassDefinition(): ( + ...args: Parameters + ) => ClassDefinition { + return ClassDefinition.createClassDefinition; }, - get createClassDefinition() { - return ClassDefinition.createClassDefinition + get updateClassDefinition(): (...args: Parameters) => ClassDefinition { + return updateClassDefinition; }, - get updateClassDefinition() { - return updateClassDefinition + get createClassProperty(): (...args: Parameters) => ClassProperty { + return ClassProperty.createClassProperty; }, - get createClassProperty() { - return ClassProperty.createClassProperty + get updateClassProperty(): (...args: Parameters) => ClassProperty { + return updateClassProperty; }, - get updateClassProperty() { - return updateClassProperty + get createFunctionType(): (...args: Parameters) => ETSFunctionType { + return ETSFunctionType.createETSFunctionType; }, - get createFunctionType() { - return ETSFunctionType.createETSFunctionType + get updateFunctionType(): (...args: Parameters) => ETSFunctionType { + return updateETSFunctionType; }, - get updateFunctionType() { - return updateETSFunctionType + get createFunctionExpression(): (...args: Parameters) => FunctionExpression { + return FunctionExpression.create; }, - get createFunctionExpression() { - return FunctionExpression.create + get updateFunctionExpression(): (...args: Parameters) => FunctionExpression { + return updateFunctionExpression; }, - get updateFunctionExpression() { - return updateFunctionExpression + get createMethodDefinition(): (...args: Parameters) => MethodDefinition { + return MethodDefinition.create; }, - get createMethodDefinition() { - return MethodDefinition.create + get updateMethodDefinition(): (...args: Parameters) => MethodDefinition { + return updateMethodDefinition; }, - get updateMethodDefinition() { - return updateMethodDefinition + get createSuperExpression(): ( + ...args: Parameters + ) => SuperExpression { + return SuperExpression.createSuperExpression; }, - get createSuperExpression() { - return SuperExpression.createSuperExpression + get updateSuperExpression(): (...args: Parameters) => SuperExpression { + return updateSuperExpression; }, - get updateSuperExpression() { - return updateSuperExpression + get createTSTypeParameterInstantiation(): ( + ...args: Parameters + ) => TSTypeParameterInstantiation { + return TSTypeParameterInstantiation.createTSTypeParameterInstantiation; }, - get createTSTypeParameterInstantiation() { - return TSTypeParameterInstantiation.createTSTypeParameterInstantiation + get updateTSTypeParameterInstantiation(): ( + ...args: Parameters + ) => TSTypeParameterInstantiation { + return updateTSTypeParameterInstantiation; }, - get updateTSTypeParameterInstantiation() { - return updateTSTypeParameterInstantiation + get createInterfaceDeclaration(): ( + ...args: Parameters + ) => TSInterfaceDeclaration { + return TSInterfaceDeclaration.createTSInterfaceDeclaration; }, - get createInterfaceDeclaration() { - return TSInterfaceDeclaration.createTSInterfaceDeclaration + get updateInterfaceDeclaration(): ( + ...args: Parameters + ) => TSInterfaceDeclaration { + return updateTSInterfaceDeclaration; }, - get updateInterfaceDeclaration() { - return updateTSInterfaceDeclaration + get createInterfaceBody(): (...args: Parameters) => TSInterfaceBody { + return TSInterfaceBody.createTSInterfaceBody; }, - get createInterfaceBody() { - return TSInterfaceBody.createTSInterfaceBody + get updateInterfaceBody(): (...args: Parameters) => TSInterfaceBody { + return updateTSInterfaceBody; }, - get updateInterfaceBody() { - return updateTSInterfaceBody + get createUndefinedLiteral(): ( + ...args: Parameters + ) => UndefinedLiteral { + return UndefinedLiteral.createUndefinedLiteral; }, - get createUndefinedLiteral() { - return UndefinedLiteral.createUndefinedLiteral + get updateUndefinedLiteral(): (...args: Parameters) => UndefinedLiteral { + return updateUndefinedLiteral; }, - get updateUndefinedLiteral() { - return updateUndefinedLiteral + get createAnnotationDeclaration(): ( + ...args: Parameters + ) => AnnotationDeclaration { + return AnnotationDeclaration.create1AnnotationDeclaration; }, - get createAnnotationUsage() { - return AnnotationUsage.createAnnotationUsage + get updateAnnotationDeclaration(): ( + ...args: Parameters + ) => AnnotationDeclaration { + return updateAnnotationDeclaration; }, - get updateAnnotationUsage() { - return updateAnnotationUsage + get createAnnotationUsage(): ( + ...args: Parameters + ) => AnnotationUsage { + return AnnotationUsage.createAnnotationUsage; }, - get create1AnnotationUsage(): (...args: Parameters) => AnnotationUsage { + get updateAnnotationUsage(): (...args: Parameters) => AnnotationUsage { + return updateAnnotationUsage; + }, + get create1AnnotationUsage(): ( + ...args: Parameters + ) => AnnotationUsage { return AnnotationUsage.create1AnnotationUsage; }, get update1AnnotationUsage(): (...args: Parameters) => AnnotationUsage { return update1AnnotationUsage; }, - get createAssignmentExpression() { - return AssignmentExpression.create + get createAssignmentExpression(): ( + ...args: Parameters + ) => AssignmentExpression { + return AssignmentExpression.create; }, - get updateAssignmentExpression() { - return updateAssignmentExpression + get updateAssignmentExpression(): (...args: Parameters) => AssignmentExpression { + return updateAssignmentExpression; }, - get createETSUndefinedType() { - return ETSUndefinedType.createETSUndefinedType + get createETSUndefinedType(): ( + ...args: Parameters + ) => ETSUndefinedType { + return ETSUndefinedType.createETSUndefinedType; }, - get updateETSUndefinedType() { - return updateETSUndefinedType + get updateETSUndefinedType(): (...args: Parameters) => ETSUndefinedType { + return updateETSUndefinedType; }, - get createFunctionSignature() { - return FunctionSignature.createFunctionSignature + get createFunctionSignature(): ( + ...args: Parameters + ) => FunctionSignature { + return FunctionSignature.createFunctionSignature; }, - get createConditionalExpression() { - return ConditionalExpression.createConditionalExpression + get createConditionalExpression(): ( + ...args: Parameters + ) => ConditionalExpression { + return ConditionalExpression.createConditionalExpression; }, - get updateConditionalExpression() { - return updateConditionalExpression + get updateConditionalExpression(): ( + ...args: Parameters + ) => ConditionalExpression { + return updateConditionalExpression; }, - get createTSAsExpression() { - return TSAsExpression.createTSAsExpression + get createTSAsExpression(): (...args: Parameters) => TSAsExpression { + return TSAsExpression.createTSAsExpression; }, - get updateTSAsExpression() { - return updateTSAsExpression + get updateTSAsExpression(): (...args: Parameters) => TSAsExpression { + return updateTSAsExpression; }, - get createThisExpression() { - return ThisExpression.createThisExpression + get createThisExpression(): (...args: Parameters) => ThisExpression { + return ThisExpression.createThisExpression; }, - get updateThisExpression() { - return updateThisExpression + get updateThisExpression(): (...args: Parameters) => ThisExpression { + return updateThisExpression; }, - get createTSTypeAliasDeclaration() { - return TSTypeAliasDeclaration.createTSTypeAliasDeclaration + get createTSTypeAliasDeclaration(): ( + ...args: Parameters + ) => TSTypeAliasDeclaration { + return TSTypeAliasDeclaration.createTSTypeAliasDeclaration; }, - get updateTSTypeAliasDeclaration() { - return updateTSTypeAliasDeclaration + get updateTSTypeAliasDeclaration(): ( + ...args: Parameters + ) => TSTypeAliasDeclaration { + return updateTSTypeAliasDeclaration; }, - get createTSNonNullExpression() { - return TSNonNullExpression.createTSNonNullExpression + get createTSNonNullExpression(): ( + ...args: Parameters + ) => TSNonNullExpression { + return TSNonNullExpression.createTSNonNullExpression; }, - get updateTSNonNullExpression() { - return updateTSNonNullExpression + get updateTSNonNullExpression(): (...args: Parameters) => TSNonNullExpression { + return updateTSNonNullExpression; }, - get createChainExpression() { - return ChainExpression.createChainExpression + get createChainExpression(): ( + ...args: Parameters + ) => ChainExpression { + return ChainExpression.createChainExpression; }, - get updateChainExpression() { - return updateChainExpression + get updateChainExpression(): (...args: Parameters) => ChainExpression { + return updateChainExpression; }, - get createBlockExpression() { - return BlockExpression.createBlockExpression + get createBlockExpression(): ( + ...args: Parameters + ) => BlockExpression { + return BlockExpression.createBlockExpression; }, - get updateBlockExpression() { - return updateBlockExpression + get updateBlockExpression(): (...args: Parameters) => BlockExpression { + return updateBlockExpression; }, - get createNullLiteral() { - return NullLiteral.createNullLiteral + get createNullLiteral(): (...args: Parameters) => NullLiteral { + return NullLiteral.createNullLiteral; }, - get updateNullLiteral() { - return updateNullLiteral + get updateNullLiteral(): (...args: Parameters) => NullLiteral { + return updateNullLiteral; }, - get createETSNewClassInstanceExpression() { - return ETSNewClassInstanceExpression.createETSNewClassInstanceExpression + get createETSNewClassInstanceExpression(): ( + ...args: Parameters + ) => ETSNewClassInstanceExpression { + return ETSNewClassInstanceExpression.createETSNewClassInstanceExpression; }, - get updateETSNewClassInstanceExpression() { - return updateETSNewClassInstanceExpression + get updateETSNewClassInstanceExpression(): ( + ...args: Parameters + ) => ETSNewClassInstanceExpression { + return updateETSNewClassInstanceExpression; }, - get createETSStringLiteralType() { + get createETSStringLiteralType(): ( + ...args: Parameters + ) => ETSStringLiteralType { return ETSStringLiteralType.create; }, get createBooleanLiteral(): (...args: Parameters) => BooleanLiteral { return BooleanLiteral.createBooleanLiteral; }, - get createObjectExpression(): (...args: Parameters) => ObjectExpression { + get createObjectExpression(): ( + ...args: Parameters + ) => ObjectExpression { return ObjectExpression.createObjectExpression; }, get updateObjectExpression(): (...args: Parameters) => ObjectExpression { @@ -464,20 +543,30 @@ export const factory = { get updateProperty(): (...args: Parameters) => Property { return updateProperty; }, - get createTemplateLiteral(): (...args: Parameters) => TemplateLiteral { + get createTemplateLiteral(): ( + ...args: Parameters + ) => TemplateLiteral { return TemplateLiteral.createTemplateLiteral; }, get updateTemplateLiteral(): (...args: Parameters) => TemplateLiteral { return updateTemplateLiteral; }, - get createArrayExpression(): (...args: Parameters) => ArrayExpression { + get createArrayExpression(): ( + ...args: Parameters + ) => ArrayExpression { return ArrayExpression.createArrayExpression; }, get updateArrayExpression(): (...args: Parameters) => ArrayExpression { return updateArrayExpression; }, + get createTryStatement(): (...args: Parameters) => TryStatement { + return TryStatement.createTryStatement; + }, + get updateTryStatement(): (...args: Parameters) => TryStatement { + return updateTryStatement; + }, /** @deprecated */ createTypeParameter1_(name: Identifier, constraint?: TypeNode, defaultType?: TypeNode) { - return TSTypeParameter.createTSTypeParameter(Identifier.create1Identifier(name.name), constraint, defaultType) + return TSTypeParameter.createTSTypeParameter(Identifier.create1Identifier(name.name), constraint, defaultType); }, -} +}; diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index 936a9b0f8..10f059ea1 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -15,6 +15,7 @@ export * from "../Es2pandaEnums" export * from "../generated/Es2pandaEnums" +export * from "../generated/peers/AnnotationDeclaration" export * from "../generated/peers/AnnotationUsage" export * from "../generated/peers/BlockStatement" export * from "../generated/peers/ETSPrimitiveType" @@ -59,8 +60,9 @@ export * from "../generated/peers/BlockExpression" export * from "../generated/peers/TSClassImplements" export * from "../generated/peers/BooleanLiteral" export * from "../generated/peers/TSArrayType" -export * from "../generated/peers/ArrayExpression"; -export * from "../generated/peers/ETSNullType"; +export * from "../generated/peers/ArrayExpression" +export * from "../generated/peers/TryStatement" +export * from "../generated/peers/ETSNullType" export * from "./types" export * from "./utilities/private" @@ -80,4 +82,4 @@ export * from "./peers/SourcePosition" export * from "./peers/SourceRange" export * from "./to-be-generated/MemberExpression" export * from "./static/globalUtils" -export { global as arktsGlobal } from "./static/global"; +export { global as arktsGlobal } from "./static/global" diff --git a/arkui-plugins/test/local/@ohos.arkui.component.column.d.ets b/koala-wrapper/src/arkts-api/node-utilities/AnnotationDeclaration.ts similarity index 39% rename from arkui-plugins/test/local/@ohos.arkui.component.column.d.ets rename to koala-wrapper/src/arkts-api/node-utilities/AnnotationDeclaration.ts index 915dc5ceb..345d95f21 100644 --- a/arkui-plugins/test/local/@ohos.arkui.component.column.d.ets +++ b/koala-wrapper/src/arkts-api/node-utilities/AnnotationDeclaration.ts @@ -1,10 +1,10 @@ /* - * Copyright (C) 2025 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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, @@ -13,29 +13,20 @@ * limitations under the License. */ -import { memo } from '../stateManagement/runtime'; -import { ComponentBuilder, CommonMethod, PointLightStyle } from './common'; -import { HorizontalAlign, FlexAlign } from './enums'; +import { AnnotationDeclaration, Expression } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; +import { AstNode } from '../peers/AstNode'; -export declare interface ColumnOptions { - space?: string | number; -} +export function updateAnnotationDeclaration( + original: AnnotationDeclaration, + expr: Expression | undefined, + properties: readonly AstNode[] +): AnnotationDeclaration { + if (isSameNativeObject(expr, original.expr) && isSameNativeObject(properties, original.properties)) { + return original; + } -export declare interface ColumnAttribute extends CommonMethod { - @memo - alignItems(value: HorizontalAlign): this; - @memo - justifyContent(value: FlexAlign): this; - @memo - pointLight(value: PointLightStyle): this; - @memo - reverse(isReversed?: boolean): this; + const update = updateThenAttach(AnnotationDeclaration.update1AnnotationDeclaration, attachModifiers); + return update(original, expr, properties); } - -@memo -@ComponentBuilder -export declare function Column ( - options?: ColumnOptions, - @memo - content?: () => void -): ColumnAttribute; \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts b/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts index 44afa1dbc..42006a300 100644 --- a/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts +++ b/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts @@ -19,12 +19,13 @@ import { AstNode } from '../peers/AstNode'; import { MethodDefinition } from '../types'; import { updateThenAttach } from '../utilities/private'; import { Es2pandaMethodDefinitionKind } from '../../generated/Es2pandaEnums'; +import { ScriptFunction } from '../../generated'; export function updateMethodDefinition( original: MethodDefinition, kind: Es2pandaMethodDefinitionKind, key: AstNode, - value: AstNode, + value: ScriptFunction, modifiers: KInt, isComputed: boolean ): MethodDefinition { diff --git a/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceDeclaration.ts index d268c5d82..1d607b245 100644 --- a/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceDeclaration.ts +++ b/koala-wrapper/src/arkts-api/node-utilities/TSInterfaceDeclaration.ts @@ -38,6 +38,10 @@ export function updateTSInterfaceDeclaration( return original; } - const update = updateThenAttach(TSInterfaceDeclaration.updateTSInterfaceDeclaration, attachModifiers); + const update = updateThenAttach( + TSInterfaceDeclaration.updateTSInterfaceDeclaration, + attachModifiers, + (node: TSInterfaceDeclaration, original: TSInterfaceDeclaration) => node.setAnnotations(original.annotations) + ); return update(original, _extends, id, typeParams, body, isStatic, isExternal); } diff --git a/koala-wrapper/src/arkts-api/node-utilities/TryStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/TryStatement.ts new file mode 100644 index 000000000..32512066c --- /dev/null +++ b/koala-wrapper/src/arkts-api/node-utilities/TryStatement.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { LabelPair } from '../../generated/peers/LabelPair'; +import { BlockStatement, CatchClause, Statement, TryStatement } from '../../generated'; +import { isSameNativeObject } from '../peers/ArktsObject'; +import { attachModifiers, updateThenAttach } from '../utilities/private'; + +export function updateTryStatement( + original: TryStatement, + block: BlockStatement | undefined, + catchClauses: readonly CatchClause[], + finalizer: BlockStatement | undefined, + finalizerInsertionsLabelPair: readonly LabelPair[], + finalizerInsertionsStatement: readonly Statement[] +): TryStatement { + if ( + isSameNativeObject(block, original.block) && + isSameNativeObject(catchClauses, original.catchClauses) && + isSameNativeObject(finalizer, original.finallyBlock) + /* TODO: no getter for finalizerInsertionsLabelPair */ + /* TODO: no getter for finalizerInsertionsStatement */ + ) { + return original; + } + + const update = updateThenAttach(TryStatement.updateTryStatement, attachModifiers); + return update(original, block, catchClauses, finalizer, finalizerInsertionsLabelPair, finalizerInsertionsStatement); +} diff --git a/koala-wrapper/src/arkts-api/peers/AstNode.ts b/koala-wrapper/src/arkts-api/peers/AstNode.ts index 62a0b78d2..e60cd5c06 100644 --- a/koala-wrapper/src/arkts-api/peers/AstNode.ts +++ b/koala-wrapper/src/arkts-api/peers/AstNode.ts @@ -13,122 +13,125 @@ * limitations under the License. */ -import { isNullPtr, KInt, KNativePointer as KPtr, KNativePointer, nullptr } from "@koalaui/interop" -import { global } from "../static/global" -import { allFlags, nodeType, unpackNodeArray, unpackNonNullableNode, unpackString } from "../utilities/private" -import { throwError } from "../../utils" -import { Es2pandaModifierFlags } from "../../generated/Es2pandaEnums" -import { ArktsObject } from "./ArktsObject" -import { Es2pandaAstNodeType } from "../../Es2pandaEnums" +import { isNullPtr, KInt, KNativePointer as KPtr, KNativePointer, nullptr } from '@koalaui/interop'; +import { global } from '../static/global'; +import { allFlags, nodeType, unpackNode, unpackNodeArray, unpackNonNullableNode, unpackString } from '../utilities/private'; +import { throwError } from '../../utils'; +import { Es2pandaModifierFlags } from '../../generated/Es2pandaEnums'; +import { ArktsObject } from './ArktsObject'; +import { Es2pandaAstNodeType } from '../../Es2pandaEnums'; export abstract class AstNode extends ArktsObject { protected constructor(peer: KNativePointer) { if (isNullPtr(peer)) { - throwError(`attempted to create AstNode from nullptr`) + throwError(`attempted to create AstNode from nullptr`); } - super(peer) - this.updateChildren() + super(peer); + this.updateChildren(); } public get originalPeer(): KNativePointer { - const result = global.generatedEs2panda._AstNodeOriginalNodeConst(global.context, this.peer) + const result = global.generatedEs2panda._AstNodeOriginalNodeConst(global.context, this.peer); if (result === nullptr) { - this.originalPeer = this.peer - return this.peer + this.originalPeer = this.peer; + return this.peer; } - return result + return result; } public set originalPeer(peer: KNativePointer) { - global.generatedEs2panda._AstNodeSetOriginalNode(global.context, this.peer, peer) + global.generatedEs2panda._AstNodeSetOriginalNode(global.context, this.peer, peer); } public getChildren(): readonly AstNode[] { - return unpackNodeArray(global.es2panda._AstNodeChildren(global.context, this.peer)) + return unpackNodeArray(global.es2panda._AstNodeChildren(global.context, this.peer)); } public getSubtree(): readonly AstNode[] { return this.getChildren().reduce( (prev: readonly AstNode[], curr) => { - return prev.concat(curr.getSubtree()) + return prev.concat(curr.getSubtree()); }, [this] - ) + ); } public updateChildren(): void { if (this.peer === nullptr) { - throwError('updateChildren called on NULLPTR') + throwError('updateChildren called on NULLPTR'); } - global.es2panda._AstNodeUpdateChildren(global.context, this.peer) + global.es2panda._AstNodeUpdateChildren(global.context, this.peer); } public updateModifiers(modifierFlags: KInt | undefined): this { - global.generatedEs2panda._AstNodeClearModifier(global.context, this.peer, allFlags) - global.generatedEs2panda._AstNodeAddModifier(global.context, this.peer, modifierFlags ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE) - return this + global.generatedEs2panda._AstNodeClearModifier(global.context, this.peer, allFlags); + global.generatedEs2panda._AstNodeAddModifier( + global.context, + this.peer, + modifierFlags ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); + return this; } public dump(indentation: number = 0): string { - const children = this.getChildren() - .map((it) => it.dump(indentation + 1)) - const msg = - `${indentation}_` - + ` ` - + this.dumpMessage() - return "> " + " ".repeat(4 * indentation) + msg + "\n" + children.join("") + const children = this.getChildren().map((it) => it.dump(indentation + 1)); + const msg = `${indentation}_` + ` ` + this.dumpMessage(); + return '> ' + ' '.repeat(4 * indentation) + msg + '\n' + children.join(''); } protected dumpMessage(): string { - return `` + return ``; } public dumpJson(): string { - return unpackString(global.generatedEs2panda._AstNodeDumpJSONConst(global.context, this.peer)) + return unpackString(global.generatedEs2panda._AstNodeDumpJSONConst(global.context, this.peer)); } public dumpSrc(): string { - return unpackString(global.generatedEs2panda._AstNodeDumpEtsSrcConst(global.context, this.peer)) + return unpackString(global.generatedEs2panda._AstNodeDumpEtsSrcConst(global.context, this.peer)); } public dumpModifiers(): string { - return unpackString(global.es2panda._AstNodeDumpModifiers(global.context, this.peer)) + return unpackString(global.es2panda._AstNodeDumpModifiers(global.context, this.peer)); } public clone(): this { - return unpackNonNullableNode(global.generatedEs2panda._AstNodeClone(global.context, this.peer, this.parent.peer)); + const clonedNode = unpackNonNullableNode( + global.generatedEs2panda._AstNodeClone(global.context, this.peer, this.parent?.peer ?? nullptr) + ); + clonedNode.parent = undefined; + return clonedNode as this; } - public get parent(): AstNode { - const parent = global.generatedEs2panda._AstNodeParent(global.context, this.peer) - if (parent === nullptr) { - throwError(`no parent`) - } - return unpackNonNullableNode(parent) + public get parent(): AstNode | undefined { + const parent = global.generatedEs2panda._AstNodeParent(global.context, this.peer); + return unpackNode(parent); } - public set parent(node: AstNode) { - global.generatedEs2panda._AstNodeSetParent(global.context, this.peer, node.peer) + public set parent(node: AstNode | undefined) { + global.generatedEs2panda._AstNodeSetParent(global.context, this.peer, node?.peer ?? nullptr); } public get modifiers(): KInt { - return global.generatedEs2panda._AstNodeModifiers(global.context, this.peer) + return global.generatedEs2panda._AstNodeModifiers(global.context, this.peer); } public set modifiers(flags: KInt | undefined) { - global.generatedEs2panda._AstNodeClearModifier(global.context, this.peer, allFlags) - global.generatedEs2panda._AstNodeAddModifier(global.context, this.peer, flags ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE) + global.generatedEs2panda._AstNodeClearModifier(global.context, this.peer, allFlags); + global.generatedEs2panda._AstNodeAddModifier( + global.context, + this.peer, + flags ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ); } public get isStatic(): boolean { - return global.generatedEs2panda._AstNodeIsStaticConst(global.context, this.peer) + return global.generatedEs2panda._AstNodeIsStaticConst(global.context, this.peer); } } - export class UnsupportedNode extends AstNode { constructor(peer: KPtr) { - super(peer) - + super(peer); } } diff --git a/koala-wrapper/src/arkts-api/peers/Context.ts b/koala-wrapper/src/arkts-api/peers/Context.ts index 81a1ec31f..b4bf7a203 100644 --- a/koala-wrapper/src/arkts-api/peers/Context.ts +++ b/koala-wrapper/src/arkts-api/peers/Context.ts @@ -13,39 +13,43 @@ * limitations under the License. */ -import { ArktsObject } from "./ArktsObject" -import { global } from "../static/global" -import { throwError, filterSource } from "../../utils" -import { passString } from "../utilities/private" -import { KNativePointer } from "@koalaui/interop" -import { AstNode } from "./AstNode" -import { Program } from "./Program" +import { ArktsObject } from './ArktsObject'; +import { global } from '../static/global'; +import { throwError, filterSource } from '../../utils'; +import { passString } from '../utilities/private'; +import { KBoolean, KNativePointer } from '@koalaui/interop'; +import { AstNode } from './AstNode'; +import { Program } from './Program'; export class Context extends ArktsObject { constructor(peer: KNativePointer) { - super(peer) + super(peer); } - static createFromString( - source: string - ): Context { + static createFromString(source: string): Context { if (!global.configIsInitialized()) { - throwError(`Config not initialized`) + throwError(`Config not initialized`); } return new Context( - global.es2panda._CreateContextFromString( - global.config, - passString(source), - passString(global.filePath) - ) - ) + global.es2panda._CreateContextFromString(global.config, passString(source), passString(global.filePath)) + ); } - static destroyAndRecreate( - ast: AstNode + + static createCacheContextFromFile( + configPtr: KNativePointer, + fileName: string, + globalContextPtr: KNativePointer, + isExternal: KBoolean ): Context { - console.log("[TS WRAPPER] DESTROY AND RECREATE"); - const source = filterSource(ast.dumpSrc()) - global.es2panda._DestroyContext(global.context) - global.compilerContext = Context.createFromString(source) + return new Context( + global.es2panda._CreateCacheContextFromFile(configPtr, passString(fileName), globalContextPtr, isExternal) + ); + } + + static destroyAndRecreate(ast: AstNode): Context { + console.log('[TS WRAPPER] DESTROY AND RECREATE'); + const source = filterSource(ast.dumpSrc()); + global.es2panda._DestroyContext(global.context); + global.compilerContext = Context.createFromString(source); return new Context(global.context); } @@ -53,4 +57,4 @@ export class Context extends ArktsObject { get program(): Program { return new Program(global.es2panda._ContextProgram(this.peer)); } -} \ No newline at end of file +} diff --git a/koala-wrapper/src/arkts-api/peers/Program.ts b/koala-wrapper/src/arkts-api/peers/Program.ts index 5f3afbed2..5734dc4a4 100644 --- a/koala-wrapper/src/arkts-api/peers/Program.ts +++ b/koala-wrapper/src/arkts-api/peers/Program.ts @@ -35,17 +35,32 @@ export class Program extends ArktsObject { ); } - get programFileName(): string { + get directExternalSources(): ExternalSource[] { + return acceptNativeObjectArrayResult( + global.es2panda._ProgramDirectExternalSources(global.context, this.peer), + (instance: KNativePointer) => new ExternalSource(instance) + ); + } + + get fileName(): string { return unpackString(global.es2panda._ProgramFileNameConst(global.context, this.peer)); } - get programFileNameWithExtension(): string { + get fileNameWithExtension(): string { return unpackString(global.es2panda._ProgramFileNameWithExtensionConst(global.context, this.peer)); } - get programGlobalAbsName(): string { + get globalAbsName(): string { return unpackString(global.es2panda._ETSParserGetGlobalProgramAbsName(global.context)); } + + get moduleName(): string { + return unpackString(global.es2panda._ProgramModuleNameConst(global.context, this.peer)); + } + + isASTLowered(): boolean { + return global.es2panda._ProgramIsASTLoweredConst(global.context, this.peer); + } } export class ExternalSource extends ArktsObject { diff --git a/koala-wrapper/src/arkts-api/types.ts b/koala-wrapper/src/arkts-api/types.ts index 7e97b8a7c..be1c31651 100644 --- a/koala-wrapper/src/arkts-api/types.ts +++ b/koala-wrapper/src/arkts-api/types.ts @@ -90,7 +90,7 @@ export class EtsScript extends AstNode { global.config = Config.createDefault().peer; } global.compilerContext = Context.createFromString(source); - proceedToState(state); + proceedToState(state, global.context); return new EtsScript( global.es2panda._ProgramAst(global.context, global.es2panda._ContextProgram(global.context)) ); @@ -666,9 +666,8 @@ export class MethodDefinition extends AstNode { assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION); super(peer); this.kind = global.generatedEs2panda._MethodDefinitionKindConst(global.context, this.peer); - this.scriptFunction = unpackNonNullableNode( - global.generatedEs2panda._MethodDefinitionFunction(global.context, this.peer) - ); + this.funcExpr = unpackNonNullableNode(global.generatedEs2panda._ClassElementValue(global.context, this.peer)); + this.scriptFunction = this.funcExpr.scriptFunction; assertValidPeer(this.scriptFunction.peer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION); // Somehow the scriptFunction cannot attach method's key to its ident after checker @@ -687,7 +686,7 @@ export class MethodDefinition extends AstNode { static create( kind: Es2pandaMethodDefinitionKind, key: AstNode, - value: AstNode, + value: ScriptFunction, modifiers: KInt, isComputed: boolean ): MethodDefinition { @@ -696,7 +695,7 @@ export class MethodDefinition extends AstNode { global.context, kind, passNode(key), - passNode(value), + passNode(FunctionExpression.create(value)), modifiers, isComputed ), @@ -708,7 +707,7 @@ export class MethodDefinition extends AstNode { node: MethodDefinition, kind: Es2pandaMethodDefinitionKind, key: AstNode, - value: AstNode, + value: ScriptFunction, modifiers: KInt, isComputed: boolean ): MethodDefinition { @@ -718,7 +717,7 @@ export class MethodDefinition extends AstNode { node.peer, kind, passNode(key), - passNode(value), + passNode(FunctionExpression.update(node.funcExpr, value)), modifiers, isComputed ), @@ -748,6 +747,7 @@ export class MethodDefinition extends AstNode { readonly kind: Es2pandaMethodDefinitionKind; readonly scriptFunction: ScriptFunction; readonly name: Identifier; + readonly funcExpr: FunctionExpression; } export class VariableDeclaration extends AstNode { diff --git a/koala-wrapper/src/arkts-api/utilities/performance.ts b/koala-wrapper/src/arkts-api/utilities/performance.ts index bafe9df5d..c938de34c 100644 --- a/koala-wrapper/src/arkts-api/utilities/performance.ts +++ b/koala-wrapper/src/arkts-api/utilities/performance.ts @@ -34,15 +34,22 @@ function pad(value: number, length: number): string { return value.toString().padStart(length, '0'); } +function round(value: number, index: number = 2): number { + const factor = Math.pow(10, index); + return Math.round(value * factor) / factor; +} + export class Performance { private static instance: Performance; private events: Map; + private historyEvents = new Map(); private scopes: string[]; private shouldSkip: boolean; private totalDuration: number; private constructor() { this.events = new Map(); + this.historyEvents = new Map(); this.scopes = []; this.shouldSkip = true; this.totalDuration = 0; @@ -60,7 +67,9 @@ export class Performance { } createEvent(name: string): Event { - if (this.shouldSkip) return { name: '', startTime: 0 }; + if (this.shouldSkip) { + return { name: '', startTime: 0 }; + } const startTime: number = performance.now(); const newEvent: Event = { name, startTime }; this.events.set(name, newEvent); @@ -69,7 +78,9 @@ export class Performance { } stopEvent(name: string, shouldLog: boolean = false): Event { - if (this.shouldSkip) return { name: '', startTime: 0 }; + if (this.shouldSkip) { + return { name: '', startTime: 0 }; + } if (!this.events.has(name) || this.scopes.length === 0) { throw new Error(`Event ${name} is not created.`); } @@ -82,19 +93,26 @@ export class Performance { const endTime: number = performance.now(); const parentEvent: string = this.scopes[this.scopes.length - 1]; const duration: number = endTime - event.startTime; - this.totalDuration += duration; + if (!parentEvent) { + this.totalDuration += duration; + } if (shouldLog) { console.log( - `[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}, total: ${formatTime(this.totalDuration)}` + `[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}(${round(duration)}), total: ${formatTime(this.totalDuration)}(${round(this.totalDuration)})` ); } - return { ...event, endTime, parentEvent, duration }; + const newEvent = { ...event, endTime, parentEvent, duration }; + const history = this.historyEvents.get(parentEvent ?? null) || []; + this.historyEvents.set(parentEvent ?? null, [...history, newEvent]); + return newEvent; } stopLastEvent(shouldLog: boolean = false): Event { - if (this.shouldSkip) return { name: '', startTime: 0 }; + if (this.shouldSkip) { + return { name: '', startTime: 0 }; + } if (this.scopes.length === 0) { throw new Error("No last event"); } @@ -107,19 +125,26 @@ export class Performance { const endTime: number = performance.now(); const parentEvent: string = this.scopes[this.scopes.length - 1]; const duration: number = endTime - event.startTime; - this.totalDuration += duration; + if (!parentEvent) { + this.totalDuration += duration; + } if (shouldLog) { console.log( - `[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}, total: ${formatTime(this.totalDuration)}` + `[PERFORMANCE] name: ${event.name}, parent: ${parentEvent}, duration: ${formatTime(duration)}(${round(duration)}), total: ${formatTime(this.totalDuration)}(${round(this.totalDuration)})` ); } - return { ...event, endTime, parentEvent, duration }; + const newEvent = { ...event, endTime, parentEvent, duration }; + const history = this.historyEvents.get(parentEvent ?? null) || []; + this.historyEvents.set(parentEvent ?? null, [...history, newEvent]); + return newEvent; } clearAllEvents(shouldLog: boolean = false): void { - if (this.shouldSkip) return; + if (this.shouldSkip) { + return; + } for (let i = 0; i < this.scopes.length; i ++) { this.stopLastEvent(shouldLog); } @@ -129,4 +154,37 @@ export class Performance { clearTotalDuration(): void { this.totalDuration = 0; } + + clearHistory(): void { + this.historyEvents = new Map(); + } + + visualizeEvents(shouldLog: boolean = false): void { + if (this.shouldSkip) { + return; + } + const that = this; + function buildVisualization(parentKey: string | null, indentLevel: number): [string, number] { + const children = that.historyEvents.get(parentKey) || []; + let result = ''; + + children.forEach(child => { + const indent = ' '.repeat(indentLevel); + const duration = child.duration ?? 0; + const [_result, count] = buildVisualization(child.name, indentLevel + 1); + result += `${indent}- ${child.name}: ${formatTime(duration)}(${round(duration)}), ${count}\n`; + result += _result; + }); + + return [result, children.length]; + } + + const [finalResult, _] = buildVisualization(null, 0); + if (shouldLog) { + console.log(`[PERFORMANCE] ===== FINAL RESULT ====`); + console.log(`TOTAL: ${formatTime(this.totalDuration)}(${round(this.totalDuration)})`); + console.log(finalResult.trimEnd()); + console.log(`[PERFORMANCE] ===== FINAL RESULT ====`); + } + } } \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index 1ebdd1b26..fee7203f6 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -16,7 +16,7 @@ import { global } from '../static/global'; import { isNumber, throwError, getEnumName } from '../../utils'; import { KNativePointer, KInt, nullptr, withStringResult } from '@koalaui/interop'; -import { passNode, passString, unpackNodeArray, unpackNonNullableNode } from './private'; +import { passNode, passString, passStringArray, unpackNodeArray, unpackNonNullableNode } from './private'; import { isFunctionDeclaration, isMemberExpression, isMethodDefinition, isNumberLiteral } from '../factory/nodeTests'; import { Es2pandaContextState, @@ -43,34 +43,32 @@ import { clearNodeCache } from '../class-by-peer'; import { SourcePosition } from '../peers/SourcePosition'; import { MemberExpression } from '../to-be-generated/MemberExpression'; -export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { +export function proceedToState(state: Es2pandaContextState, context: KNativePointer, forceDtsEmit = false): void { console.log('[TS WRAPPER] PROCEED TO STATE: ', getEnumName(Es2pandaContextState, state)); - if (global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR) { - processErrorState(state, forceDtsEmit); + if (global.es2panda._ContextState(context) === Es2pandaContextState.ES2PANDA_STATE_ERROR) { + clearNodeCache(); + processErrorState(state, context, forceDtsEmit); } - if (state <= global.es2panda._ContextState(global.context)) { + if (state <= global.es2panda._ContextState(context)) { console.log('[TS WRAPPER] PROCEED TO STATE: SKIPPING'); return; } clearNodeCache(); - global.es2panda._ProceedToState(global.context, state); - processErrorState(state, forceDtsEmit); + global.es2panda._ProceedToState(context, state); + processErrorState(state, context, forceDtsEmit); } -function processErrorState(state: Es2pandaContextState, forceDtsEmit = false): void { +function processErrorState(state: Es2pandaContextState, context: KNativePointer, forceDtsEmit = false): void { try { - if ( - global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && - !forceDtsEmit - ) { - const errorMessage = withStringResult(global.es2panda._ContextErrorMessage(global.context)); + if (global.es2panda._ContextState(context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && !forceDtsEmit) { + const errorMessage = withStringResult(global.es2panda._ContextErrorMessage(context)); if (errorMessage === undefined) { throwError(`Could not get ContextErrorMessage`); } throwError([`Failed to proceed to ${Es2pandaContextState[state]}`, errorMessage].join(`\n`)); } } catch (e) { - global.es2panda._DestroyContext(global.context); + global.es2panda._DestroyContext(context); throw e; } } @@ -98,7 +96,7 @@ export function getDecl(node: AstNode): AstNode | undefined { if (!!decl) { return decl; } - if (isProperty(node.parent)) { + if (!!node.parent && isProperty(node.parent)) { return getDeclFromProperty(node.parent); } return undefined; @@ -108,7 +106,7 @@ function getDeclFromProperty(node: Property): AstNode | undefined { if (!node.key) { return undefined; } - if (!isObjectExpression(node.parent)) { + if (!!node.parent && !isObjectExpression(node.parent)) { return getPeerDecl(passNode(node.key)); } return getDeclFromObjectExpressionProperty(node); @@ -210,6 +208,10 @@ export function importDeclarationInsert(node: ETSImportDeclaration, program: Pro global.es2panda._InsertETSImportDeclarationAndParse(global.context, program.peer, node.peer); } +export function getProgramFromAstNode(node: AstNode): Program { + return new Program(global.es2panda._AstNodeProgram(global.context, node.peer)); +} + export function hasModifierFlag(node: AstNode, flag: Es2pandaModifierFlags): boolean { if (!node) return false; @@ -246,7 +248,7 @@ export function destroyConfig(config: KNativePointer): void { global.resetConfig(); } -export function setAllParents(ast: AstNode) { +export function setAllParents(ast: AstNode): void { global.es2panda._AstNodeUpdateAll(global.context, ast.peer); } @@ -270,3 +272,41 @@ export function getStartPosition(node: AstNode): SourcePosition { export function getEndPosition(node: AstNode): SourcePosition { return new SourcePosition(global.es2panda._AstNodeEndConst(global.context, node.peer)); } + +export function MemInitialize(): void { + global.es2panda._MemInitialize(); +} + +export function MemFinalize(): void { + global.es2panda._MemFinalize(); +} + +export function CreateGlobalContext( + config: KNativePointer, + externalFileList: string[], + fileNum: KInt, + lspUsage: boolean +): KNativePointer { + return global.es2panda._CreateGlobalContext(config, passStringArray(externalFileList), fileNum, lspUsage); +} + +export function DestroyGlobalContext(context: KNativePointer): void { + global.es2panda._DestroyGlobalContext(context); +} + +export function CreateCacheContextFromFile( + configPtr: KNativePointer, + filename: string, + globalContext: KNativePointer, + isExternal: Boolean +): KNativePointer { + return global.es2panda._CreateCacheContextFromFile(configPtr, passString(filename), globalContext, isExternal); +} + +export function insertGlobalStructInfo(structName: string): void { + global.es2panda._InsertGlobalStructInfo(global.context, passString(structName)); +} + +export function hasGlobalStructInfo(structName: string): boolean { + return global.es2panda._HasGlobalStructInfo(global.context, passString(structName)); +} diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index becf519db..b2bca2336 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -46,6 +46,8 @@ import { isBlockExpression, isReturnStatement, isArrayExpression, + isTryStatement, + isBinaryExpression, } from '../generated'; import { isEtsScript, @@ -67,64 +69,6 @@ import { Es2pandaAstNodeType } from '../Es2pandaEnums'; type Visitor = (node: AstNode) => AstNode; -export interface StructVariableMetadata { - name: string; - properties: string[]; - modifiers: Es2pandaModifierFlags; - hasStateManagementType?: boolean; -} - -export class StructInfo { - metadata: Record = {}; - initializeBody: AstNode[] = []; - updateBody: AstNode[] = []; - isReusable: boolean = false; - toRecordBody: Property[] = []; -} - -export class GlobalInfo { - private _structCollection: Set; - private static instance: GlobalInfo; - private _structMap: Map; - - private constructor() { - this._structCollection = new Set(); - this._structMap = new Map(); - } - - public static getInfoInstance(): GlobalInfo { - if (!this.instance) { - this.instance = new GlobalInfo(); - } - return this.instance; - } - - public add(str: string): void { - this._structCollection.add(str); - } - - public getStructCollection(): Set { - return this._structCollection; - } - - public getStructInfo(structName: string): StructInfo { - const structInfo = this._structMap.get(structName); - if (!structInfo) { - return new StructInfo(); - } - return structInfo; - } - - public setStructInfo(structName: string, info: StructInfo): void { - this._structMap.set(structName, info); - } - - public reset(): void { - this._structMap.clear(); - this._structCollection.clear(); - } -} - // TODO: rethink (remove as) function nodeVisitor(node: T, visitor: Visitor): T { if (node === undefined) { @@ -156,6 +100,7 @@ export function visitEachChild(node: AstNode, visitor: Visitor): AstNode { script = visitStatement(script, visitor); script = visitOuterExpression(script, visitor); script = visitInnerExpression(script, visitor); + script = visitTrivialExpression(script, visitor); script = visitLiteral(script, visitor); // TODO return visitWithoutUpdate(script, visitor); @@ -263,6 +208,23 @@ function visitInnerExpression(node: AstNode, visitor: Visitor): AstNode { return node; } +function visitTrivialExpression(node: AstNode, visitor: Visitor): AstNode { + if (updated) { + return node; + } + if (isBinaryExpression(node)) { + updated = true; + return factory.updateBinaryExpression( + node, + nodeVisitor(node.left, visitor), + nodeVisitor(node.right, visitor), + node.operatorType + ); + } + // TODO + return node; +} + function visitDeclaration(node: AstNode, visitor: Visitor): AstNode { if (updated) { return node; @@ -335,7 +297,7 @@ function visitDefinition(node: AstNode, visitor: Visitor): AstNode { node, node.kind, node.name, - factory.createFunctionExpression(nodeVisitor(node.scriptFunction, visitor)), + nodeVisitor(node.scriptFunction, visitor), node.modifiers, false ); @@ -381,6 +343,17 @@ function visitStatement(node: AstNode, visitor: Visitor): AstNode { updated = true; return factory.updateReturnStatement(node, nodeVisitor(node.argument, visitor)); } + if (isTryStatement(node)) { + updated = true; + return factory.updateTryStatement( + node, + nodeVisitor(node.block, visitor), + nodesVisitor(node.catchClauses, visitor), + nodeVisitor(node.finallyBlock, visitor), + [], + [] + ); + } // TODO return node; } diff --git a/koala-wrapper/src/generated/Es2pandaNativeModule.ts b/koala-wrapper/src/generated/Es2pandaNativeModule.ts index 8e4126db9..7dcfda5a9 100644 --- a/koala-wrapper/src/generated/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/generated/Es2pandaNativeModule.ts @@ -877,9 +877,6 @@ export class Es2pandaNativeModule { _TSTypeAliasDeclarationSetTypeParameters(context: KNativePointer, receiver: KNativePointer, typeParams: KNativePointer): void { throw new Error("'TSTypeAliasDeclarationSetTypeParameters was not overloaded by native module initialization") } - _TSTypeAliasDeclarationAnnotations(context: KNativePointer, receiver: KNativePointer): KNativePointer { - throw new Error("'TSTypeAliasDeclarationAnnotations was not overloaded by native module initialization") - } _TSTypeAliasDeclarationAnnotationsConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { throw new Error("'TSTypeAliasDeclarationAnnotationsConst was not overloaded by native module initialization") } @@ -1075,9 +1072,6 @@ export class Es2pandaNativeModule { _ScriptFunctionAddFlag(context: KNativePointer, receiver: KNativePointer, flags: KInt): void { throw new Error("'ScriptFunctionAddFlag was not overloaded by native module initialization") } - _ScriptFunctionAddModifier(context: KNativePointer, receiver: KNativePointer, flags: KInt): void { - throw new Error("'ScriptFunctionAddModifier was not overloaded by native module initialization") - } _ScriptFunctionFormalParamsLengthConst(context: KNativePointer, receiver: KNativePointer): KUInt { throw new Error("'ScriptFunctionFormalParamsLengthConst was not overloaded by native module initialization") } @@ -1498,6 +1492,18 @@ export class Es2pandaNativeModule { _ETSTupleSetTypeAnnotationsList(context: KNativePointer, receiver: KNativePointer, typeNodeList: BigUint64Array, typeNodeListSequenceLength: KUInt): void { throw new Error("'ETSTupleSetTypeAnnotationsList was not overloaded by native module initialization") } + _CreateTryStatement(context: KNativePointer, block: KNativePointer, catchClauses: BigUint64Array, catchClausesSequenceLength: KUInt, finalizer: KNativePointer, finalizerInsertionsLabelPair: BigUint64Array, finalizerInsertionsLabelPairSequenceLength: KUInt, finalizerInsertionsStatement: BigUint64Array, finalizerInsertionsStatementSequenceLength: KUInt): KNativePointer { + throw new Error("'CreateTryStatement was not overloaded by native module initialization") + } + _UpdateTryStatement(context: KNativePointer, original: KNativePointer, block: KNativePointer, catchClauses: BigUint64Array, catchClausesSequenceLength: KUInt, finalizer: KNativePointer, finalizerInsertionsLabelPair: BigUint64Array, finalizerInsertionsLabelPairSequenceLength: KUInt, finalizerInsertionsStatement: BigUint64Array, finalizerInsertionsStatementSequenceLength: KUInt): KNativePointer { + throw new Error("'UpdateTryStatement was not overloaded by native module initialization") + } + _CreateTryStatement1(context: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'CreateTryStatement1 was not overloaded by native module initialization") + } + _UpdateTryStatement1(context: KNativePointer, original: KNativePointer, other: KNativePointer): KNativePointer { + throw new Error("'UpdateTryStatement1 was not overloaded by native module initialization") + } _TryStatementFinallyBlockConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { throw new Error("'TryStatementFinallyBlockConst was not overloaded by native module initialization") } @@ -2116,9 +2122,6 @@ export class Es2pandaNativeModule { _ImportDeclarationSpecifiersConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { throw new Error("'ImportDeclarationSpecifiersConst was not overloaded by native module initialization") } - _ImportDeclarationSpecifiers(context: KNativePointer, receiver: KNativePointer): KNativePointer { - throw new Error("'ImportDeclarationSpecifiers was not overloaded by native module initialization") - } _ImportDeclarationIsTypeKindConst(context: KNativePointer, receiver: KNativePointer): KBoolean { throw new Error("'ImportDeclarationIsTypeKindConst was not overloaded by native module initialization") } @@ -2152,9 +2155,6 @@ export class Es2pandaNativeModule { _ETSImportDeclarationIsPureDynamicConst(context: KNativePointer, receiver: KNativePointer): KBoolean { throw new Error("'ETSImportDeclarationIsPureDynamicConst was not overloaded by native module initialization") } - _ETSImportDeclarationAssemblerName(context: KNativePointer, receiver: KNativePointer): KStringPtr { - throw new Error("'ETSImportDeclarationAssemblerName was not overloaded by native module initialization") - } _ETSImportDeclarationAssemblerNameConst(context: KNativePointer, receiver: KNativePointer): KStringPtr { throw new Error("'ETSImportDeclarationAssemblerNameConst was not overloaded by native module initialization") } diff --git a/arkui-plugins/test/local/@ohos.arkui.component.units.d.ets b/koala-wrapper/src/generated/peers/LabelPair.ts similarity index 49% rename from arkui-plugins/test/local/@ohos.arkui.component.units.d.ets rename to koala-wrapper/src/generated/peers/LabelPair.ts index c6a98e628..c949e6fc1 100644 --- a/arkui-plugins/test/local/@ohos.arkui.component.units.d.ets +++ b/koala-wrapper/src/generated/peers/LabelPair.ts @@ -1,10 +1,10 @@ /* - * Copyright (C) 2025 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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, @@ -13,17 +13,23 @@ * limitations under the License. */ -import { Resource } from "@ohos.arkui.external.resource" -import { Color } from "@ohos.arkui.component.enums"; +import { + global, + passNode, + passNodeArray, + unpackNonNullableNode, + unpackNode, + unpackNodeArray, + assertValidPeer, + AstNode, + KNativePointer, + nodeByType, + ArktsObject, + unpackString +} from "../../reexport-for-generated" -export type PX = string; -export type VP = string | number; -export type FP = string; -export type LPX = string; -export type Percentage = string; - -export type Dimension = PX | VP | FP | LPX | Percentage | Resource; - -export type Length = string | number | Resource; - -export type ResourceColor = Color | number | string | Resource; \ No newline at end of file +export class LabelPair extends AstNode { + constructor(pointer: KNativePointer) { + super(pointer) + } +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ScriptFunction.ts b/koala-wrapper/src/generated/peers/ScriptFunction.ts index 42c4c9343..69389b8d5 100644 --- a/koala-wrapper/src/generated/peers/ScriptFunction.ts +++ b/koala-wrapper/src/generated/peers/ScriptFunction.ts @@ -179,7 +179,7 @@ export class ScriptFunction extends AstNode { } /** @deprecated */ addModifier(flags: Es2pandaModifierFlags): this { - global.generatedEs2panda._ScriptFunctionAddModifier(global.context, this.peer, flags) + global.generatedEs2panda._AstNodeAddModifier(global.context, this.peer, flags) return this } get annotations(): readonly AnnotationUsage[] { diff --git a/koala-wrapper/src/generated/peers/TryStatement.ts b/koala-wrapper/src/generated/peers/TryStatement.ts index dd3a7571d..93bde0b00 100644 --- a/koala-wrapper/src/generated/peers/TryStatement.ts +++ b/koala-wrapper/src/generated/peers/TryStatement.ts @@ -22,21 +22,30 @@ import { unpackNodeArray, assertValidPeer, AstNode, - Es2pandaAstNodeType, KNativePointer, nodeByType, ArktsObject, - unpackString + unpackString, + Es2pandaAstNodeType } from "../../reexport-for-generated" -import { Statement } from "./Statement" import { BlockStatement } from "./BlockStatement" import { CatchClause } from "./CatchClause" +import { LabelPair } from "./LabelPair" +import { Statement } from "./Statement" export class TryStatement extends Statement { - constructor(pointer: KNativePointer) { + constructor(pointer: KNativePointer) { assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT) super(pointer) - + } + static createTryStatement(block: BlockStatement | undefined, catchClauses: readonly CatchClause[], finalizer: BlockStatement | undefined, finalizerInsertionsLabelPair: readonly LabelPair[], finalizerInsertionsStatement: readonly Statement[]): TryStatement { + return new TryStatement(global.generatedEs2panda._CreateTryStatement(global.context, passNode(block), passNodeArray(catchClauses), catchClauses.length, passNode(finalizer), passNodeArray(finalizerInsertionsLabelPair), finalizerInsertionsLabelPair.length, passNodeArray(finalizerInsertionsStatement), finalizerInsertionsStatement.length)) + } + static updateTryStatement(original: TryStatement | undefined, block: BlockStatement | undefined, catchClauses: readonly CatchClause[], finalizer: BlockStatement | undefined, finalizerInsertionsLabelPair: readonly LabelPair[], finalizerInsertionsStatement: readonly Statement[]): TryStatement { + return new TryStatement(global.generatedEs2panda._UpdateTryStatement(global.context, passNode(original), passNode(block), passNodeArray(catchClauses), catchClauses.length, passNode(finalizer), passNodeArray(finalizerInsertionsLabelPair), finalizerInsertionsLabelPair.length, passNodeArray(finalizerInsertionsStatement), finalizerInsertionsStatement.length)) + } + static update1TryStatement(original?: TryStatement, other?: TryStatement): TryStatement { + return new TryStatement(global.generatedEs2panda._UpdateTryStatement1(global.context, passNode(original), passNode(other))) } get finallyBlock(): BlockStatement | undefined { return unpackNode(global.generatedEs2panda._TryStatementFinallyBlockConst(global.context, this.peer)) @@ -47,6 +56,9 @@ export class TryStatement extends Statement { get hasFinalizer(): boolean { return global.generatedEs2panda._TryStatementHasFinalizerConst(global.context, this.peer) } + get hasDefaultCatchClause(): boolean { + return global.generatedEs2panda._TryStatementHasDefaultCatchClauseConst(global.context, this.peer); + } get catchClauses(): readonly CatchClause[] { return unpackNodeArray(global.generatedEs2panda._TryStatementCatchClausesConst(global.context, this.peer)) } @@ -59,9 +71,9 @@ export class TryStatement extends Statement { return this } } -export function isTryStatement(node: AstNode): node is TryStatement { +export function isTryStatement(node: object | undefined): node is TryStatement { return node instanceof TryStatement } if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT)) { nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT, TryStatement) -} +} \ No newline at end of file -- Gitee From 31cd1ceb91b665245e367a29a69845fb707b54a7 Mon Sep 17 00:00:00 2001 From: chenyiyuan Date: Thu, 15 May 2025 20:35:25 +0800 Subject: [PATCH 105/123] Integrate BcHar declgen into koala wrapper Issue: https://gitee.com/openharmony/developtools_ace_ets2bundle/issues/ICBY7V Signed-off-by: chenyiyuan Change-Id: Iefaf774db524af7c8e36a735015d2e64f7cc36e2 --- koala-wrapper/native/src/bridges.cc | 7 +++++++ koala-wrapper/src/Es2pandaNativeModule.ts | 7 +++++++ koala-wrapper/src/arkts-api/utilities/public.ts | 7 +++++++ 3 files changed, 21 insertions(+) diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index ce062418c..9f3b4537e 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -304,6 +304,13 @@ KInt impl_GenerateTsDeclarationsFromContext(KNativePointer contextPtr, KStringPt } KOALA_INTEROP_4(GenerateTsDeclarationsFromContext, KInt, KNativePointer, KStringPtr, KStringPtr, KBoolean) +KInt impl_GenerateStaticDeclarationsFromContext(KNativePointer contextPtr, KStringPtr &outputPath) +{ + auto context = reinterpret_cast(contextPtr); + return GetImpl()->GenerateStaticDeclarationsFromContext(context, outputPath.data()); +} +KOALA_INTEROP_2(GenerateStaticDeclarationsFromContext, KInt, KNativePointer, KStringPtr) + void impl_InsertETSImportDeclarationAndParse(KNativePointer context, KNativePointer program, KNativePointer importDeclaration) { diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 551481a4f..f777188be 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -752,6 +752,13 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _GenerateStaticDeclarationsFromContext( + config: KPtr, + outputPath: String + ): KPtr { + throw new Error('Not implemented'); + } + _InsertETSImportDeclarationAndParse( context: KNativePointer, program: KNativePointer, diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index 2b21e625b..f2fbe9597 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -252,6 +252,13 @@ export function generateTsDeclarationsFromContext(outputDeclEts: string, outputE ); } +export function generateStaticDeclarationsFromContext(outputPath: string): KInt { + return global.es2panda._GenerateStaticDeclarationsFromContext( + global.context, + passString(outputPath) + ); +} + export function isDefaultAccessModifierClassProperty(property: ClassProperty): boolean { return global.es2panda._ClassPropertyIsDefaultAccessModifierConst(global.context, property.peer); } -- Gitee From d68b0c9a0610e84cf2b2e1cc54e2171634ab8377 Mon Sep 17 00:00:00 2001 From: Jiakai Shi Date: Wed, 28 May 2025 09:13:33 +0800 Subject: [PATCH 106/123] kit import Signed-off-by: Jiakai Shi Change-Id: I7e4431a8bf930a5d73b03b6b59c75c52e9153d9b --- arkui-plugins/common/arkts-utils.ts | 22 ++ arkui-plugins/common/declaration-collector.ts | 55 ++++- .../import-collector.ts | 4 +- arkui-plugins/common/predefines.ts | 227 +++++++++++++----- arkui-plugins/common/program-visitor.ts | 21 +- arkui-plugins/jest-test.config.js | 2 + .../test/demo/mock/imports/kit-import.ets | 34 +++ arkui-plugins/test/localtest_config.js | 34 +++ .../argument-call.test.ts | 6 +- .../type-reference.test.ts | 2 +- .../lambda-literals/trailing-lambdas.test.ts | 12 +- .../lambda-literals/with-receiver.test.ts | 6 +- .../method-declarations/callable.test.ts | 4 +- .../internal-calls.test.ts | 8 +- .../non-void-method.test.ts | 4 +- .../animation/animation-basic.test.ts | 2 +- .../custom-component-call.test.ts | 4 +- .../style-with-receiver.test.ts | 2 +- .../decorators/builder/local-builder.test.ts | 2 +- .../decorators/link/link-basic-type.test.ts | 4 +- .../decorators/link/link-complex-type.test.ts | 4 +- .../link/link-to-link-prop-state.test.ts | 8 +- .../decorators/link/state-to-link.test.ts | 8 +- .../observed-track/observed-only.test.ts | 8 +- .../observed-track-class-property.test.ts | 12 +- .../observed-track-complex-type.test.ts | 12 +- .../observed-track-extends.test.ts | 8 +- .../observed-track-implements.test.ts | 8 +- .../observed-track/observed-track.test.ts | 8 +- .../observed-track/track-only.test.ts | 8 +- .../decorators/prop/prop-basic-type.test.ts | 2 +- .../decorators/prop/prop-complex-type.test.ts | 2 +- .../decorators/prop/state-to-prop.test.ts | 6 +- .../provide-annotation-usage.test.ts | 2 +- .../provide-basic-type.test.ts | 2 +- .../provide-complex-type.test.ts | 2 +- .../resource/resource-in-build.test.ts | 8 +- .../resource/resource-in-property.test.ts | 4 +- .../reusable/reusable-basic.test.ts | 4 +- .../reusable/reusable-complex.test.ts | 8 +- .../decorators/state/state-basic-type.test.ts | 2 +- .../state/state-complex-type.test.ts | 2 +- .../decorators/state/state-to-state.test.ts | 2 +- .../storagelink-appstorage.test.ts | 4 +- .../storagelink-complex-type.test.ts | 2 +- .../storagelink-primitive-type.test.ts | 2 +- .../storageprop-appstorage.test.ts | 4 +- .../storageprop-complex-type.test.ts | 2 +- .../storageprop-primitive-type.test.ts | 2 +- .../decorators/watch/watch-basic.test.ts | 18 +- .../ut/ui-plugins/imports/kit-import.test.ts | 173 +++++++++++++ .../xcomponent/xcomponent-basic.test.ts | 2 +- arkui-plugins/test/utils/artkts-config.ts | 15 +- arkui-plugins/test/utils/shared-types.ts | 3 +- .../builder-lambda-transformer.ts | 2 +- .../builder-lambda-translators/factory.ts | 23 +- .../builder-lambda-translators/utils.ts | 56 +++-- .../ui-plugins/checked-transformer.ts | 5 +- .../ui-plugins/component-transformer.ts | 39 +-- .../ui-plugins/entry-translators/factory.ts | 11 +- .../ui-plugins/entry-translators/utils.ts | 5 +- .../ui-plugins/preprocessor-transform.ts | 126 +--------- .../ui-plugins/property-translators/base.ts | 4 +- .../property-translators/builderParam.ts | 4 +- .../property-translators/consume.ts | 5 +- .../property-translators/factory.ts | 21 +- .../ui-plugins/property-translators/index.ts | 3 +- .../ui-plugins/property-translators/link.ts | 7 +- .../property-translators/localstoragelink.ts | 5 +- .../property-translators/localstorageprop.ts | 9 +- .../property-translators/objectlink.ts | 5 +- .../property-translators/observedTrack.ts | 7 +- .../ui-plugins/property-translators/prop.ts | 7 +- .../property-translators/provide.ts | 5 +- .../ui-plugins/property-translators/state.ts | 12 +- .../property-translators/storageProp.ts | 5 +- .../property-translators/storagelink.ts | 5 +- .../ui-plugins/property-translators/utils.ts | 106 +------- .../ui-plugins/struct-translators/factory.ts | 33 +-- .../struct-translators/struct-transformer.ts | 5 +- .../ui-plugins/struct-translators/utils.ts | 34 ++- arkui-plugins/ui-plugins/ui-factory.ts | 26 +- arkui-plugins/ui-plugins/utils.ts | 57 ++--- 83 files changed, 784 insertions(+), 660 deletions(-) rename arkui-plugins/{ui-plugins => common}/import-collector.ts (95%) create mode 100644 arkui-plugins/test/demo/mock/imports/kit-import.ets create mode 100644 arkui-plugins/test/ut/ui-plugins/imports/kit-import.test.ts diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index 9f2eb7a01..bf056c788 100644 --- a/arkui-plugins/common/arkts-utils.ts +++ b/arkui-plugins/common/arkts-utils.ts @@ -15,6 +15,28 @@ import * as arkts from '@koalaui/libarkts'; + +/** + * create and insert `import { as } from ` to the top of script's statements. + */ +export function createAndInsertImportDeclaration( + source: arkts.StringLiteral, + imported: arkts.Identifier, + local: arkts.Identifier, + importKind: arkts.Es2pandaImportKinds, + program: arkts.Program +): void { + const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + source, + [arkts.factory.createImportSpecifier(imported, local)], + importKind, + program, + arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE + ); + arkts.importDeclarationInsert(importDecl, program); + return; +} + export function annotation(name: string): arkts.AnnotationUsage { const ident: arkts.Identifier = arkts.factory.createIdentifier(name).setAnnotationUsage(); const annotation: arkts.AnnotationUsage = arkts.factory.createAnnotationUsage(ident); diff --git a/arkui-plugins/common/declaration-collector.ts b/arkui-plugins/common/declaration-collector.ts index 81a1160bc..d65f0d40d 100644 --- a/arkui-plugins/common/declaration-collector.ts +++ b/arkui-plugins/common/declaration-collector.ts @@ -13,13 +13,17 @@ * limitations under the License. */ import * as arkts from '@koalaui/libarkts'; +import { IMPORT_SOURCE_MAP_V2, INTERMEDIATE_IMPORT_SOURCE } from './predefines'; +import { ImportCollector } from './import-collector'; export class DeclarationCollector { - public fromExternalSourceNames: Set; + private fromExternalSourceNameMap: Map; + private fromExternalSourceNodePeerMap: Map; static instance: DeclarationCollector; private constructor() { - this.fromExternalSourceNames = new Set(); + this.fromExternalSourceNameMap = new Map(); + this.fromExternalSourceNodePeerMap = new Map(); } static getInstance(): DeclarationCollector { @@ -29,15 +33,54 @@ export class DeclarationCollector { return this.instance; } + private collectIntermediateImportSource(symbol: string, declSourceName: string): void { + let sourceName: string; + if (IMPORT_SOURCE_MAP_V2.has(symbol)) { + sourceName = IMPORT_SOURCE_MAP_V2.get(symbol)!; + } else { + sourceName = declSourceName; + } + ImportCollector.getInstance().collectSource(symbol, sourceName); + } + collect(decl: arkts.AstNode | undefined): void { if (!decl) { return; } - const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; - this.fromExternalSourceNames.add(moduleName); + let declName: string | undefined; + if (arkts.isAnnotationDeclaration(decl) && !!decl.expr && arkts.isIdentifier(decl.expr)) { + declName = decl.expr.name; + } else if (arkts.isMethodDefinition(decl)) { + declName = decl.name.name; + } else if (arkts.isIdentifier(decl)) { + declName = decl.name; + } else if (arkts.isClassProperty(decl) && !!decl.key && arkts.isIdentifier(decl.key)) { + declName = decl.key.name; + } else if (arkts.isEtsParameterExpression(decl)) { + declName = decl.identifier.name; + } + if (!declName) { + return; + } + let sourceName: string = arkts.getProgramFromAstNode(decl).moduleName; + this.fromExternalSourceNameMap.set(declName, sourceName); + this.fromExternalSourceNodePeerMap.set(decl.peer, sourceName); + + INTERMEDIATE_IMPORT_SOURCE.get(declName)?.forEach((symbol) => { + this.collectIntermediateImportSource(symbol, sourceName); + }); + } + + findExternalSourceFromName(declName: string): string | undefined { + return this.fromExternalSourceNameMap.get(declName); + } + + findExternalSourceFromNode(decl: arkts.AstNode): string | undefined { + return this.fromExternalSourceNodePeerMap.get(decl.peer); } reset(): void { - this.fromExternalSourceNames.clear(); + this.fromExternalSourceNameMap.clear(); + this.fromExternalSourceNodePeerMap.clear(); } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/import-collector.ts b/arkui-plugins/common/import-collector.ts similarity index 95% rename from arkui-plugins/ui-plugins/import-collector.ts rename to arkui-plugins/common/import-collector.ts index c16c6cdb0..935b339af 100644 --- a/arkui-plugins/ui-plugins/import-collector.ts +++ b/arkui-plugins/common/import-collector.ts @@ -14,7 +14,7 @@ */ import * as arkts from '@koalaui/libarkts'; -import { factory } from './ui-factory'; +import { createAndInsertImportDeclaration } from './arkts-utils'; interface ImportInfo { imported: string; @@ -31,7 +31,7 @@ function insertImport(importInfo: ImportInfo, program?: arkts.Program): void { if (!program) { throw Error('Failed to insert import: Transformer has no program'); } - factory.createAndInsertImportDeclaration(source, imported, local, importInfo.kind, program); + createAndInsertImportDeclaration(source, imported, local, importInfo.kind, program); } export class ImportCollector { diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index f2644856a..044a48b95 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -28,77 +28,145 @@ export const EXTERNAL_SOURCE_PREFIX_NAMES: (string | RegExp)[] = [ /ability\..*/, ]; -export const ARKUI_IMPORT_PREFIX_NAMES: (string | RegExp)[] = [/@ohos\..*/, /arkui\..*/]; +export const ARKUI_IMPORT_PREFIX_NAMES: (string | RegExp)[] = [/arkui\..*/, /@ohos\..*/, /@kit\..*/]; -export const ARKUI_COMPONENT_IMPORT_NAME: string = '@ohos.arkui.component'; -export const ARKUI_STATEMANAGEMENT_IMPORT_NAME: string = '@ohos.arkui.stateManagement'; -export const KIT_ARKUI_NAME: string = '@kit.ArkUI'; +export const MEMO_IMPORT_SOURCE_NAME: string = 'arkui.stateManagement.runtime'; +export const CUSTOM_COMPONENT_IMPORT_SOURCE_NAME: string = 'arkui.component.customComponent'; +export const ENTRY_POINT_IMPORT_SOURCE_NAME: string = 'arkui.UserView'; +export const ARKUI_COMPONENT_COMMON_SOURCE_NAME: string = 'arkui.component.common'; -export const KOALAUI_COMMON_IMPORT_NAME: string = '@koalaui.runtime.common'; +export enum Dollars { + DOLLAR_RESOURCE = '$r', + DOLLAR_RAWFILE = '$rawfile', + DOLLAR_DOLLAR = '$$', + TRANSFORM_DOLLAR_RESOURCE = '_r', + TRANSFORM_DOLLAR_RAWFILE = '_rawfile', +} -export const IMPORT_SOURCE_MAP: Map> = new Map>([ - ['arkui.stateManagement.runtime', new Set(['memo', '__memo_context_type', '__memo_id_type'])] -]); +export enum BindableDecl { + BINDABLE = 'Bindable', +} -export const IMPORT_SOURCE_MAP_V2: Map = new Map([ - ['$r', ARKUI_COMPONENT_IMPORT_NAME], - ['$rawfile', ARKUI_COMPONENT_IMPORT_NAME], - ['_r', ARKUI_COMPONENT_IMPORT_NAME], - ['_rawfile', ARKUI_COMPONENT_IMPORT_NAME], - ['Bindable', ARKUI_COMPONENT_IMPORT_NAME], - ['State', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['Prop', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['Provide', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['Consume', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['StorageLink', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['StorageProp', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['LocalStorageLink', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['LocalStorageProp', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['Watch', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['ObjectLink', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['StateDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['MutableState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['contextLocalStateOf', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['contextLocal', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['observableProxy', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['SyncedProperty', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['objectLinkState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['propState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['AppStorageLinkState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['StorageLinkState', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['DecoratedV1VariableBase', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['LinkDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['PropDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['StorageLinkDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['StoragePropDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['ProvideDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['ConsumeDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['ObjectLinkDecoratedVariable', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['MutableStateMeta', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['BackingValue', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['setObservationDepth', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['IObservedObject', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['WatchIdType', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['SubscribedWatches', ARKUI_STATEMANAGEMENT_IMPORT_NAME], - ['int32', KOALAUI_COMMON_IMPORT_NAME], +export enum StructDecoratorNames { + ENTRY = 'Entry', + COMPONENT = 'Component', + RESUABLE = 'Reusable', +} + +export enum DecoratorNames { + STATE = 'State', + STORAGE_LINK = 'StorageLink', + STORAGE_PROP = 'StorageProp', + LINK = 'Link', + PROP = 'Prop', + PROVIDE = 'Provide', + CONSUME = 'Consume', + OBJECT_LINK = 'ObjectLink', + OBSERVED = 'Observed', + WATCH = 'Watch', + BUILDER_PARAM = 'BuilderParam', + BUILDER = 'Builder', + CUSTOM_DIALOG = 'CustomDialog', + LOCAL_STORAGE_PROP = 'LocalStorageProp', + LOCAL_STORAGE_LINK = 'LocalStorageLink', + REUSABLE = 'Reusable', + TRACK = 'Track', +} + +export enum DecoratorIntrinsicNames { + LINK = '__Link_intrinsic', +} + +export enum StateManagementTypes { + STATE_DECORATED = 'StateDecoratedVariable', + LINK_DECORATED = 'LinkDecoratedVariable', + STORAGE_LINK_DECORATED = 'StorageLinkDecoratedVariable', + STORAGE_PROP_DECORATED = 'StoragePropDecoratedVariable', + DECORATED_V1 = 'DecoratedV1VariableBase', + PROP_DECORATED = 'PropDecoratedVariable', + MUTABLE_STATE = 'MutableState', + MUTABLE_STATE_META = 'MutableStateMeta', + SYNCED_PROPERTY = 'SyncedProperty', + PROVIDE_DECORATED = 'ProvideDecoratedVariable', + CONSUME_DECORATED = 'ConsumeDecoratedVariable', + OBJECT_LINK_DECORATED = 'ObjectLinkDecoratedVariable', + BACKING_VALUE = 'BackingValue', + SET_OBSERVATION_DEPTH = 'setObservationDepth', + OBSERVED_OBJECT = 'IObservedObject', + WATCH_ID_TYPE = 'WatchIdType', + SUBSCRIBED_WATCHES = 'SubscribedWatches', + STORAGE_LINK_STATE = 'StorageLinkState', + OBSERVABLE_PROXY = 'observableProxy', + PROP_STATE = 'propState', + INT_32 = 'int32', +} + +export const DECORATOR_TYPE_MAP = new Map([ + [DecoratorNames.STATE, StateManagementTypes.STATE_DECORATED], + [DecoratorNames.LINK, StateManagementTypes.DECORATED_V1], + [DecoratorNames.PROP, StateManagementTypes.PROP_DECORATED], + [DecoratorNames.STORAGE_LINK, StateManagementTypes.STORAGE_LINK_DECORATED], + [DecoratorNames.STORAGE_PROP, StateManagementTypes.STORAGE_PROP_DECORATED], + [DecoratorNames.LOCAL_STORAGE_PROP, StateManagementTypes.SYNCED_PROPERTY], + [DecoratorNames.LOCAL_STORAGE_LINK, StateManagementTypes.MUTABLE_STATE], + [DecoratorNames.OBJECT_LINK, StateManagementTypes.OBJECT_LINK_DECORATED], + [DecoratorNames.PROVIDE, StateManagementTypes.PROVIDE_DECORATED], + [DecoratorNames.CONSUME, StateManagementTypes.CONSUME_DECORATED], ]); -export const OUTPUT_DEPENDENCY_MAP: Map = new Map([ - ['$r', []], - ['$rawfile', []], - ['State', []], - ['Link', []], - ['Prop', []], - ['Provide', []], - ['Consume', []], - ['StorageProp', []], - ['StorageLink', []], - ['LocalStorageLink', []], - ['LocalStorageProp', []], - ['ObjectLink', []], - ['Observed', []], - ['Track', []], - ['$$', []], +export const INTERMEDIATE_IMPORT_SOURCE: Map = new Map([ + [Dollars.DOLLAR_RESOURCE, [Dollars.TRANSFORM_DOLLAR_RESOURCE]], + [Dollars.DOLLAR_RAWFILE, [Dollars.TRANSFORM_DOLLAR_RAWFILE]], + [Dollars.DOLLAR_DOLLAR, [BindableDecl.BINDABLE]], + [DecoratorNames.STATE, [StateManagementTypes.STATE_DECORATED]], + [DecoratorNames.LINK, [StateManagementTypes.LINK_DECORATED, StateManagementTypes.DECORATED_V1]], + [DecoratorNames.PROP, [StateManagementTypes.PROP_DECORATED]], + [DecoratorNames.PROVIDE, [StateManagementTypes.PROVIDE_DECORATED]], + [DecoratorNames.CONSUME, [StateManagementTypes.CONSUME_DECORATED]], + [DecoratorNames.STORAGE_PROP, [StateManagementTypes.STORAGE_PROP_DECORATED]], + [DecoratorNames.STORAGE_LINK, [StateManagementTypes.STORAGE_LINK_DECORATED]], + [DecoratorNames.OBJECT_LINK, [StateManagementTypes.OBJECT_LINK_DECORATED]], + [ + DecoratorNames.LOCAL_STORAGE_LINK, + [ + StateManagementTypes.STORAGE_LINK_STATE, + StateManagementTypes.MUTABLE_STATE, + StateManagementTypes.OBSERVABLE_PROXY, + ], + ], + [ + DecoratorNames.LOCAL_STORAGE_PROP, + [ + StateManagementTypes.STORAGE_LINK_STATE, + StateManagementTypes.SYNCED_PROPERTY, + StateManagementTypes.OBSERVABLE_PROXY, + StateManagementTypes.PROP_STATE, + ], + ], + [ + DecoratorNames.OBSERVED, + [ + StateManagementTypes.MUTABLE_STATE_META, + StateManagementTypes.BACKING_VALUE, + StateManagementTypes.SET_OBSERVATION_DEPTH, + StateManagementTypes.OBSERVED_OBJECT, + StateManagementTypes.INT_32, + StateManagementTypes.WATCH_ID_TYPE, + StateManagementTypes.SUBSCRIBED_WATCHES, + ], + ], + [ + DecoratorNames.TRACK, + [ + StateManagementTypes.MUTABLE_STATE_META, + StateManagementTypes.BACKING_VALUE, + StateManagementTypes.SET_OBSERVATION_DEPTH, + StateManagementTypes.OBSERVED_OBJECT, + StateManagementTypes.INT_32, + StateManagementTypes.WATCH_ID_TYPE, + StateManagementTypes.SUBSCRIBED_WATCHES, + ], + ], ]); export enum InteroperAbilityNames { @@ -128,3 +196,32 @@ export enum InteroperAbilityNames { INTEROPCOMPONENT = 'interopComponent', OHMURL = '@normalized:N&entry&com.example.Interop2use1&har1/src/main/ets/components/MainPage&1.0.0', } + +/** + * @deprecated + */ +export const IMPORT_SOURCE_MAP_V2: Map = new Map([ + [Dollars.TRANSFORM_DOLLAR_RESOURCE, 'arkui.component.resources'], + [Dollars.TRANSFORM_DOLLAR_RAWFILE, 'arkui.component.resources'], + [StateManagementTypes.STATE_DECORATED, 'arkui.stateManagement.decorators.decoratorState'], + [StateManagementTypes.LINK_DECORATED, 'arkui.stateManagement.decorators.decoratorLink'], + [StateManagementTypes.STORAGE_LINK_DECORATED, 'arkui.stateManagement.decorators.decoratorStorageLink'], + [StateManagementTypes.STORAGE_PROP_DECORATED, 'arkui.stateManagement.decorators.decoratorStorageProp'], + [StateManagementTypes.DECORATED_V1, 'arkui.stateManagement.base.decoratorBase'], + [StateManagementTypes.PROP_DECORATED, 'arkui.stateManagement.decorators.decoratorProp'], + [StateManagementTypes.MUTABLE_STATE, 'arkui.stateManagement.runtime'], + [StateManagementTypes.MUTABLE_STATE_META, 'arkui.stateManagement.base.mutableStateMeta'], + [StateManagementTypes.SYNCED_PROPERTY, 'arkui.stateManagement.runtime'], + [StateManagementTypes.PROVIDE_DECORATED, 'arkui.stateManagement.decorators.decoratorProvide'], + [StateManagementTypes.CONSUME_DECORATED, 'arkui.stateManagement.decorators.decoratorConsume'], + [StateManagementTypes.OBJECT_LINK_DECORATED, 'arkui.stateManagement.decorators.decoratorObjectLink'], + [StateManagementTypes.BACKING_VALUE, 'arkui.stateManagement.base.backingValue'], + [StateManagementTypes.SET_OBSERVATION_DEPTH, 'arkui.stateManagement.base.iObservedObject'], + [StateManagementTypes.OBSERVED_OBJECT, 'arkui.stateManagement.base.iObservedObject'], + [StateManagementTypes.WATCH_ID_TYPE, 'arkui.stateManagement.decorators.decoratorWatch'], + [StateManagementTypes.SUBSCRIBED_WATCHES, 'arkui.stateManagement.decorators.decoratorWatch'], + [StateManagementTypes.STORAGE_LINK_STATE, 'arkui.stateManagement.runtime'], + [StateManagementTypes.OBSERVABLE_PROXY, 'arkui.stateManagement.runtime'], + [StateManagementTypes.PROP_STATE, 'arkui.stateManagement.runtime'], + [StateManagementTypes.INT_32, '@koalaui.runtime.common'], +]); diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 946ce5723..c73e00073 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -17,7 +17,7 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor, VisitorOptions } from './abstract-visitor'; import { matchPrefix } from './arkts-utils'; import { debugDump, getDumpFileName } from './debug'; -import { InteroperAbilityNames, ARKUI_COMPONENT_IMPORT_NAME, KIT_ARKUI_NAME } from './predefines'; +import { InteroperAbilityNames } from './predefines'; import { PluginContext } from './plugin-context'; import { LegacyTransformer } from '../ui-plugins/legacy-transformer'; import { ComponentTransformer } from '../ui-plugins/component-transformer'; @@ -59,25 +59,6 @@ function flattenVisitorsInHooks( ]; } -function sortExternalSources(externalSources: arkts.ExternalSource[]): arkts.ExternalSource[] { - return externalSources.sort((a, b) => { - const prefix = ARKUI_COMPONENT_IMPORT_NAME || KIT_ARKUI_NAME; - const hasPrefixA = a.getName().startsWith(prefix); - const hasPrefixB = b.getName().startsWith(prefix); - - // If both have the prefix, maintain their original order - if (hasPrefixA && hasPrefixB) { - return 0; - } - // If neither has the prefix, maintain their original order - if (!hasPrefixA && !hasPrefixB) { - return 0; - } - // If only one has the prefix, the one with the prefix comes first - return hasPrefixA ? -1 : 1; - }); -} - export interface StructMap { [key: string]: string; } diff --git a/arkui-plugins/jest-test.config.js b/arkui-plugins/jest-test.config.js index 541b1dc39..98b801f70 100644 --- a/arkui-plugins/jest-test.config.js +++ b/arkui-plugins/jest-test.config.js @@ -19,6 +19,7 @@ const rootPath = path.resolve(__dirname, '../../../'); const sdkPath = path.resolve(rootPath, './out/sdk/ohos-sdk/linux/ets/ets1.2'); const pandaSdkPath = path.resolve(sdkPath, './build-tools/ets2panda'); const apiPath = path.resolve(sdkPath, './api'); +const kitPath = path.resolve(sdkPath, './kits'); module.exports = { testEnvironment: 'node', @@ -52,5 +53,6 @@ module.exports = { SDK_PATH: sdkPath, PANDA_SDK_PATH: pandaSdkPath, API_PATH: apiPath, + KIT_PATH: kitPath }, }; diff --git a/arkui-plugins/test/demo/mock/imports/kit-import.ets b/arkui-plugins/test/demo/mock/imports/kit-import.ets new file mode 100644 index 000000000..5cd7771b2 --- /dev/null +++ b/arkui-plugins/test/demo/mock/imports/kit-import.ets @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Prop, Column, Entry } from "@kit.ArkUI"; +import { Text, Component, ClickEvent } from "@ohos.arkui.component"; +import { State } from "@ohos.arkui.stateManagement"; +import { Button } from "arkui.component.button"; +import hilog from "@ohos.hilog"; + +@Entry +@Component +struct A { + @State a: string = "str"; + @Prop b: string; + + build() { + Column() { + Button("button").onClick((e: ClickEvent) => { }) + Text("text").fontSize(20) + } + } +} diff --git a/arkui-plugins/test/localtest_config.js b/arkui-plugins/test/localtest_config.js index 87fd2e7ee..6372cbc8c 100644 --- a/arkui-plugins/test/localtest_config.js +++ b/arkui-plugins/test/localtest_config.js @@ -16,6 +16,10 @@ const fs = require('fs'); const path = require('path'); +function changePathToAbsPath(p) { + return path.resolve(p); +} + // 获取当前目录 const currentDirectory = process.cwd(); let workSpace = currentDirectory; @@ -44,6 +48,36 @@ try { jsonData.plugins.memo_plugin = jsonData.plugins.memo_plugin.replace(/workspace/g, workSpace); } + // compileFiles + if (jsonData.compileFiles) { + jsonData.compileFiles = jsonData.compileFiles.map((file) => changePathToAbsPath(file)); + } + + // entryFiles + if (jsonData.entryFiles) { + jsonData.entryFiles = jsonData.entryFiles.map((file) => changePathToAbsPath(file)); + } + + // moduleRootPath + if (jsonData.moduleRootPath) { + jsonData.moduleRootPath = changePathToAbsPath(jsonData.moduleRootPath); + } + + // sourceRoots + if (jsonData.sourceRoots) { + jsonData.sourceRoots = jsonData.sourceRoots.map((file) => changePathToAbsPath(file)); + } + + // loaderOutPath + if (jsonData.loaderOutPath) { + jsonData.loaderOutPath = changePathToAbsPath(jsonData.loaderOutPath); + } + + // loaderOutPath + if (jsonData.cachePath) { + jsonData.cachePath = changePathToAbsPath(jsonData.cachePath); + } + // 将修改后的内容写回 JSON 文件 fs.writeFileSync(outJsonFilePath, JSON.stringify(jsonData, null, 2), 'utf8'); } catch (error) { diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts index 4ff8099b2..c24e48d0a 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts @@ -32,7 +32,7 @@ const expectedScript: string = ` import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} -@functions.OptionalParametersAnnotation({minArgCount:3}) function memo_arg_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg2: ((x: number)=> number), @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number), arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { +function memo_arg_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg2: ((x: number)=> number), @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number), arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 5); const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_arg3 = __memo_scope.param(2, arg3), __memo_parameter_arg4 = __memo_scope.param(3, arg4), __memo_parameter_arg5 = __memo_scope.param(4, arg5); if (__memo_scope.unchanged) { @@ -50,7 +50,7 @@ function main() {} return; } } -@functions.OptionalParametersAnnotation({minArgCount:1}) function memo_arg_call_with_lowering(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { +function memo_arg_call_with_lowering(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 3); const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg4 = __memo_scope.param(1, arg4), __memo_parameter_arg5 = __memo_scope.param(2, arg5); if (__memo_scope.unchanged) { @@ -70,7 +70,7 @@ function main() {} return; } } -@functions.OptionalParametersAnnotation({minArgCount:0}) function args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: int, @memo() gensym%%_?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int), gensym%%_?: int, arg4?: int): void { +function args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: int, @memo() gensym%%_?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int), gensym%%_?: int, arg4?: int): void { let arg1: int = (((gensym%%_) !== (undefined)) ? gensym%%_ : (10 as int)); let arg2: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int) = (((gensym%%_) !== (undefined)) ? gensym%%_ : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): int => { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts index 541b48a72..0490eef81 100644 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts @@ -34,7 +34,7 @@ const expectedScript: string = ` import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; import { memo as memo } from \"arkui.stateManagement.runtime\"; function main() {} -@memo() function A(__memo_context: __memo_context_type, __memo_id: __memo_id_type): Attribute +@memo() export function A(__memo_context: __memo_context_type, __memo_id: __memo_id_type): Attribute function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): ItemBuilder { const __memo_scope = __memo_context.scope>(((__memo_id) + ()), 0); if (__memo_scope.unchanged) { diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts index 311746f58..ffb1c2cfa 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts @@ -100,7 +100,7 @@ function main() {} return; } }); -@functions.OptionalParametersAnnotation({minArgCount:0}) function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, f?: (()=> void)): void { +function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, f?: (()=> void)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); const __memo_parameter_f = __memo_scope.param(0, f); if (__memo_scope.unchanged) { @@ -112,8 +112,8 @@ function main() {} return; } } -@functions.OptionalParametersAnnotation({minArgCount:0}) function par(f?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} -@functions.OptionalParametersAnnotation({minArgCount:0}) function kar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() f?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { +function par(f?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +function kar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() f?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); const __memo_parameter_f = __memo_scope.param(0, f); if (__memo_scope.unchanged) { @@ -126,7 +126,7 @@ function main() {} } } class A { - @functions.OptionalParametersAnnotation({minArgCount:0}) public foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, p?: (()=> void)): void { + public foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, p?: (()=> void)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); const __memo_parameter_p = __memo_scope.param(0, p); if (__memo_scope.unchanged) { @@ -138,8 +138,8 @@ class A { return; } } - @functions.OptionalParametersAnnotation({minArgCount:0}) public goo(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} - @functions.OptionalParametersAnnotation({minArgCount:0}) public koo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { + public goo(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} + public koo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); const __memo_parameter_p = __memo_scope.param(0, p); if (__memo_scope.unchanged) { diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts index 82f9f6a61..ce9477f75 100644 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts @@ -96,11 +96,11 @@ function main() {} return; } }); -@functions.OptionalParametersAnnotation({minArgCount:1}) function fullName(this: Person, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { +function fullName(this: Person, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { return; } -@functions.OptionalParametersAnnotation({minArgCount:1}) function foo(this: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} -@functions.OptionalParametersAnnotation({minArgCount:1}) function goo(a: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +function foo(this: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} +function goo(a: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} class Person { public constructor() {} } diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts index 249406cef..77b786332 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts @@ -76,7 +76,7 @@ class A { public constructor() {} } class B { - @functions.OptionalParametersAnnotation({minArgCount:0}) public static $_invoke(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} + public static $_invoke(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} public constructor() {} } class C { @@ -91,7 +91,7 @@ class C { public constructor() {} } class D { - @functions.OptionalParametersAnnotation({minArgCount:1}) public static $_instantiate(factory: (()=> D), @memo() content?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): D { + public static $_instantiate(factory: (()=> D), @memo() content?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): D { return factory(); } public constructor() {} diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts index 4064b0e65..022c01ac0 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts @@ -32,8 +32,8 @@ const expectedScript: string = ` import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; function main() {} -function __context(): __memo_context_type -function __id(): __memo_id_type +export function __context(): __memo_context_type +export function __id(): __memo_id_type type MemoType = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); class Test { public void_method(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { @@ -120,7 +120,7 @@ class Test { return; } } - @functions.OptionalParametersAnnotation({minArgCount:0}) public args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_1?: int, gensym%%_2?: (()=> int), gensym%%_3?: int, arg4?: int): void { + public args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_1?: int, gensym%%_2?: (()=> int), gensym%%_3?: int, arg4?: int): void { let arg1: int = (((gensym%%_1) !== (undefined)) ? gensym%%_1 : (10 as int)); let arg2: (()=> int) = (((gensym%%_2) !== (undefined)) ? gensym%%_2 : ((() => { return 20; @@ -139,7 +139,7 @@ class Test { return; } } - @functions.OptionalParametersAnnotation({minArgCount:0}) public optional_args(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1?: int, arg2?: (()=> int)): void { + public optional_args(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1?: int, arg2?: (()=> int)): void { const __memo_scope = __memo_context.scope(((__memo_id) + ()), 2); const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2); if (__memo_scope.unchanged) { diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts index 780080c9a..962129e7d 100644 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts +++ b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts @@ -32,8 +32,8 @@ const expectedScript: string = ` import { __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"arkui.stateManagement.runtime\"; function main() {} -function __context(): __memo_context_type -function __id(): __memo_id_type +export function __context(): __memo_context_type +export function __id(): __memo_id_type @Retention({policy:"SOURCE"}) @interface memo_intrinsic {} @Retention({policy:"SOURCE"}) @interface memo_entry {} class Test { diff --git a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts index 3193402b8..88322c353 100644 --- a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts @@ -39,7 +39,7 @@ const pluginTester = new PluginTester('test basic animation transform', buildCon const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "arkui.component.text"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Text as Text, Column as Column, Component as Component, Color as Color, Curve as Curve } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts index a7fb599c0..705886859 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts @@ -89,8 +89,8 @@ const expectedBuilderLambdaScript: string = ` import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UIColumnAttribute as UIColumnAttribute } from "arkui.component.column"; +import { UITextAttribute as UITextAttribute } from "arkui.component.text"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Text as Text, Column as Column, Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts index 52fe30ed6..507986736 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "arkui.component.text"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { memo as memo } from "@ohos.arkui.stateManagement"; import { Text as Text, UITextAttribute as UITextAttribute, Column as Column, Component as Component } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts index e991d3b2f..54b1ae5b0 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts @@ -37,7 +37,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "arkui.component.text"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, Builder as Builder, Text as Text } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts index 08c06f2bf..67906db21 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts @@ -38,9 +38,9 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from \"@ohos.arkui.stateManagement\"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "arkui.stateManagement.base.decoratorBase"; import { memo as memo } from \"arkui.stateManagement.runtime\"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from \"@ohos.arkui.stateManagement\"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from "arkui.stateManagement.decorators.decoratorLink"; import { CustomComponent as CustomComponent } from \"arkui.component.customComponent\"; import { Component as Component } from \"@ohos.arkui.component\"; import { Link as Link } from \"@ohos.arkui.stateManagement\"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts index 1fb0b1918..fc1a40a2d 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts @@ -38,9 +38,9 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from \"@ohos.arkui.stateManagement\"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "arkui.stateManagement.base.decoratorBase"; import { memo as memo } from \"arkui.stateManagement.runtime\"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from \"@ohos.arkui.stateManagement\"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from "arkui.stateManagement.decorators.decoratorLink"; import { CustomComponent as CustomComponent } from \"arkui.component.customComponent\"; import { Component as Component } from \"@ohos.arkui.component\"; import { Link as Link } from \"@ohos.arkui.stateManagement\"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts index 30cfecbd8..bc491c7bc 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts @@ -38,11 +38,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "arkui.stateManagement.base.decoratorBase"; +import { PropDecoratedVariable as PropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProp"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from "arkui.stateManagement.decorators.decoratorLink"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, TextInput as TextInput } from "@ohos.arkui.component"; import { Link as Link, State as State, Prop as Prop } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts index 614d946c1..6bd6d0a59 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts @@ -38,11 +38,11 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "arkui.stateManagement.base.decoratorBase"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; +import { LinkDecoratedVariable as LinkDecoratedVariable } from "arkui.stateManagement.decorators.decoratorLink"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; +import { UIButtonAttribute as UIButtonAttribute } from "arkui.component.button"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Column as Column, Button as Button, DatePicker as DatePicker, ClickEvent as ClickEvent } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts index 0398b5489..447548b05 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts @@ -39,11 +39,11 @@ const pluginTester = new PluginTester('test observed only transform', buildConfi const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { IObservedObject as IObservedObject } from "arkui.stateManagement.base.iObservedObject"; +import { MutableStateMeta as MutableStateMeta } from "arkui.stateManagement.base.mutableStateMeta"; import { int32 as int32 } from "@koalaui.runtime.common"; -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; +import { WatchIdType as WatchIdType } from "arkui.stateManagement.decorators.decoratorWatch"; +import { SubscribedWatches as SubscribedWatches } from "arkui.stateManagement.decorators.decoratorWatch"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Observed as Observed } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts index f3e046dbb..bb8416190 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts @@ -39,13 +39,13 @@ const pluginTester = new PluginTester('test observed track transform with class const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { IObservedObject as IObservedObject } from "arkui.stateManagement.base.iObservedObject"; +import { setObservationDepth as setObservationDepth } from "arkui.stateManagement.base.iObservedObject"; +import { BackingValue as BackingValue } from "arkui.stateManagement.base.backingValue"; +import { MutableStateMeta as MutableStateMeta } from "arkui.stateManagement.base.mutableStateMeta"; import { int32 as int32 } from "@koalaui.runtime.common"; -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; +import { WatchIdType as WatchIdType } from "arkui.stateManagement.decorators.decoratorWatch"; +import { SubscribedWatches as SubscribedWatches } from "arkui.stateManagement.decorators.decoratorWatch"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts index 996b8fa73..182a288c9 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts @@ -39,13 +39,13 @@ const pluginTester = new PluginTester('test observed track transform with comple const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { IObservedObject as IObservedObject } from "arkui.stateManagement.base.iObservedObject"; +import { setObservationDepth as setObservationDepth } from "arkui.stateManagement.base.iObservedObject"; +import { BackingValue as BackingValue } from "arkui.stateManagement.base.backingValue"; +import { MutableStateMeta as MutableStateMeta } from "arkui.stateManagement.base.mutableStateMeta"; import { int32 as int32 } from "@koalaui.runtime.common"; -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; +import { WatchIdType as WatchIdType } from "arkui.stateManagement.decorators.decoratorWatch"; +import { SubscribedWatches as SubscribedWatches } from "arkui.stateManagement.decorators.decoratorWatch"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts index ea59f29f9..dc566ba32 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts @@ -39,11 +39,11 @@ const pluginTester = new PluginTester('test observed track transform with extend const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { IObservedObject as IObservedObject } from "arkui.stateManagement.base.iObservedObject"; +import { MutableStateMeta as MutableStateMeta } from "arkui.stateManagement.base.mutableStateMeta"; import { int32 as int32 } from "@koalaui.runtime.common"; -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; +import { WatchIdType as WatchIdType } from "arkui.stateManagement.decorators.decoratorWatch"; +import { SubscribedWatches as SubscribedWatches } from "arkui.stateManagement.decorators.decoratorWatch"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts index b8769ae20..5525cb1ae 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts @@ -39,11 +39,11 @@ const pluginTester = new PluginTester('test observed track transform with implem const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { IObservedObject as IObservedObject } from "arkui.stateManagement.base.iObservedObject"; +import { MutableStateMeta as MutableStateMeta } from "arkui.stateManagement.base.mutableStateMeta"; import { int32 as int32 } from "@koalaui.runtime.common"; -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; +import { WatchIdType as WatchIdType } from "arkui.stateManagement.decorators.decoratorWatch"; +import { SubscribedWatches as SubscribedWatches } from "arkui.stateManagement.decorators.decoratorWatch"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Observed as Observed } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts index 914e784d3..997dffc13 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts @@ -39,11 +39,11 @@ const pluginTester = new PluginTester('test observed with track transform', buil const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { IObservedObject as IObservedObject } from "arkui.stateManagement.base.iObservedObject"; +import { MutableStateMeta as MutableStateMeta } from "arkui.stateManagement.base.mutableStateMeta"; import { int32 as int32 } from "@koalaui.runtime.common"; -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; +import { WatchIdType as WatchIdType } from "arkui.stateManagement.decorators.decoratorWatch"; +import { SubscribedWatches as SubscribedWatches } from "arkui.stateManagement.decorators.decoratorWatch"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts index 9ad6c2453..c6ce73cb7 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts @@ -39,11 +39,11 @@ const pluginTester = new PluginTester('test track only transform', buildConfig); const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { IObservedObject as IObservedObject } from "arkui.stateManagement.base.iObservedObject"; +import { MutableStateMeta as MutableStateMeta } from "arkui.stateManagement.base.mutableStateMeta"; import { int32 as int32 } from "@koalaui.runtime.common"; -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; +import { WatchIdType as WatchIdType } from "arkui.stateManagement.decorators.decoratorWatch"; +import { SubscribedWatches as SubscribedWatches } from "arkui.stateManagement.decorators.decoratorWatch"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Track as Track } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts index 783f36ca7..9d1b1849a 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { PropDecoratedVariable as PropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProp"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Prop as Prop } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts index e269ddbad..7555db6af 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { PropDecoratedVariable as PropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProp"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Prop as Prop } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts index 967998dd2..a08c3589d 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts @@ -38,10 +38,10 @@ const parsedTransform: Plugins = { }; const expectedScript: string = ` -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; +import { PropDecoratedVariable as PropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProp"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; +import { UIButtonAttribute as UIButtonAttribute } from "arkui.component.button"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Text as Text, Button as Button, Column as Column, ClickEvent as ClickEvent } from "@ohos.arkui.component"; import { Prop as Prop, State as State } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts index 22f589470..963774e69 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProvide"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Provide as Provide } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts index aecf110fb..86e4942f1 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProvide"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Provide as Provide } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts index 3aea5e1d8..33d6fc204 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProvide"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { Provide as Provide } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts index e17be814d..d9e4c80c5 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts @@ -39,10 +39,10 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { _rawfile as _rawfile } from "@ohos.arkui.component"; -import { _r as _r } from "@ohos.arkui.component"; -import { UIImageAnimatorAttribute as UIImageAnimatorAttribute } from "@ohos.arkui.component"; -import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; +import { _rawfile as _rawfile } from "arkui.component.resources"; +import { _r as _r } from "arkui.component.resources"; +import { UIImageAnimatorAttribute as UIImageAnimatorAttribute } from "arkui.component.imageAnimator"; +import { UIImageAttribute as UIImageAttribute } from "arkui.component.image"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, TextInput as TextInput, Select as Select, SelectOption as SelectOption, Margin as Margin, ImageAnimator as ImageAnimator } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts index 7b5dc45a3..323eb124a 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts @@ -39,8 +39,8 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { _rawfile as _rawfile } from "@ohos.arkui.component"; -import { _r as _r } from "@ohos.arkui.component"; +import { _rawfile as _rawfile } from "arkui.component.resources"; +import { _r as _r } from "arkui.component.resources"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, Resource as Resource } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts index 654108e4f..c7e19d0d3 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts @@ -38,8 +38,8 @@ const reusableTransform: Plugins = { const pluginTester = new PluginTester('test basic reusable', buildConfig); const expectedScript: string = ` -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; +import { PropDecoratedVariable as PropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProp"; import { memo as memo } from "arkui.stateManagement.runtime"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Reusable as Reusable } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts index b4bee34c8..84d208c71 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts @@ -38,11 +38,11 @@ const reusableTransform: Plugins = { const pluginTester = new PluginTester('test complex reusable', buildConfig); const expectedScript: string = ` -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { UITextAttribute as UITextAttribute } from "arkui.component.text"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; +import { UIButtonAttribute as UIButtonAttribute } from "arkui.component.button"; +import { UIColumnAttribute as UIColumnAttribute } from "arkui.component.column"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Reusable as Reusable, Column as Column, Text as Text, Button as Button, ClickEvent as ClickEvent, FontWeight as FontWeight } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts index 909569f6d..b23bdec21 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { State as State } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts index c139596d1..bfc4bf334 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component } from "@ohos.arkui.component"; import { State as State } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts index 48b2fb849..c9caf1b0a 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts @@ -39,7 +39,7 @@ const parsedTransform: Plugins = { const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Column as Column, Text as Text } from "@ohos.arkui.component"; import { State as State } from "@ohos.arkui.stateManagement"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts index 23778c902..eedfa0a43 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts @@ -38,9 +38,9 @@ const storageLinkTransform: Plugins = { const pluginTester = new PluginTester('test storagelink with appstorage', buildConfig); const expectedScript: string = ` -import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "arkui.stateManagement.decorators.decoratorStorageLink"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "arkui.component.text"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts index f4f881a92..6ce66a065 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts @@ -40,7 +40,7 @@ const pluginTester = new PluginTester('test storagelink complex type transform', const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "arkui.stateManagement.decorators.decoratorStorageLink"; import { EntryPoint as EntryPoint } from "arkui.UserView"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts index 8a63c5ccd..1d0c605c3 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts @@ -40,7 +40,7 @@ const pluginTester = new PluginTester('test storagelink primitive type transform const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "arkui.stateManagement.decorators.decoratorStorageLink"; import { EntryPoint as EntryPoint } from "arkui.UserView"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts index 859fcfd48..e36e4f899 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts @@ -38,9 +38,9 @@ const storagePropTransform: Plugins = { const pluginTester = new PluginTester('test storageprop with appstorage', buildConfig); const expectedScript: string = ` -import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorStorageProp"; import { memo as memo } from "arkui.stateManagement.runtime"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; +import { UITextAttribute as UITextAttribute } from "arkui.component.text"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts index de771b3ec..cdc384aa9 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts @@ -40,7 +40,7 @@ const pluginTester = new PluginTester('test storageprop complex type transform', const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorStorageProp"; import { EntryPoint as EntryPoint } from "arkui.UserView"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts index 248becda0..a346288be 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts @@ -40,7 +40,7 @@ const pluginTester = new PluginTester('test storageprop primitive type transform const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; +import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorStorageProp"; import { EntryPoint as EntryPoint } from "arkui.UserView"; diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts index 609d89725..f28e43d82 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts @@ -39,16 +39,16 @@ const pluginTester = new PluginTester('test basic watch transform', buildConfig) const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; +import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProvide"; +import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorStorageProp"; +import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "arkui.stateManagement.decorators.decoratorStorageLink"; +import { PropDecoratedVariable as PropDecoratedVariable } from "arkui.stateManagement.decorators.decoratorProp"; +import { StateDecoratedVariable as StateDecoratedVariable } from "arkui.stateManagement.decorators.decoratorState"; +import { IObservedObject as IObservedObject } from "arkui.stateManagement.base.iObservedObject"; +import { MutableStateMeta as MutableStateMeta } from "arkui.stateManagement.base.mutableStateMeta"; import { int32 as int32 } from "@koalaui.runtime.common"; -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; +import { WatchIdType as WatchIdType } from "arkui.stateManagement.decorators.decoratorWatch"; +import { SubscribedWatches as SubscribedWatches } from "arkui.stateManagement.decorators.decoratorWatch"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/ut/ui-plugins/imports/kit-import.test.ts b/arkui-plugins/test/ut/ui-plugins/imports/kit-import.test.ts new file mode 100644 index 000000000..0ea1ca2ad --- /dev/null +++ b/arkui-plugins/test/ut/ui-plugins/imports/kit-import.test.ts @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as path from 'path'; +import { PluginTester } from '../../../utils/plugin-tester'; +import { mockBuildConfig } from '../../../utils/artkts-config'; +import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; +import { parseDumpSrc } from '../../../utils/parse-string'; +import { recheck, uiNoRecheck } from '../../../utils/plugins'; +import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; +import { uiTransform } from '../../../../ui-plugins'; +import { Plugins } from '../../../../common/plugin-context'; + +const IMPORT_DIR_PATH: string = 'imports'; + +const buildConfig: BuildConfig = mockBuildConfig(); +buildConfig.compileFiles = [ + path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, IMPORT_DIR_PATH, 'kit-import.ets'), +]; + +const importParsed: Plugins = { + name: 'import-parsed', + parsed: uiTransform().parsed, +}; + +const pluginTester = new PluginTester('test import transform', buildConfig); + +const expectedParsedScript: string = ` +import { EntryPoint as EntryPoint } from \"arkui.UserView\"; +import { CustomComponent as CustomComponent } from \"arkui.component.customComponent\"; +import { Prop as Prop, Column as Column, Entry as Entry } from \"@kit.ArkUI\"; +import { Text as Text, Component as Component, ClickEvent as ClickEvent } from \"@ohos.arkui.component\"; +import { State as State } from \"@ohos.arkui.stateManagement\"; +import { Button as Button } from \"arkui.component.button\"; +import hilog from \"@ohos.hilog\"; + +@Entry() @Component() final class A extends CustomComponent { + @State() public a: string = \"str\"; + @Prop() public b!: string; + + public build() { + Column(){ + Button(\"button\").onClick(((e: ClickEvent) => {})); + Text(\"text\").fontSize(20); + }; + } + public constructor() {} +} + +@Entry() @Component() export interface __Options_A { + a?: string; + @State() __backing_a?: string; + b?: string; + @Prop() __backing_b?: string; +} + +class __EntryWrapper extends EntryPoint { + public entry(): void { + A(); + } + public constructor() {} +} +`; + +const expectedCheckedScript: string = ` +import { PropDecoratedVariable as PropDecoratedVariable } from \"arkui.stateManagement.decorators.decoratorProp\"; +import { StateDecoratedVariable as StateDecoratedVariable } from \"arkui.stateManagement.decorators.decoratorState\"; +import { memo as memo } from \"arkui.stateManagement.runtime\"; +import { UITextAttribute as UITextAttribute } from \"arkui.component.text\"; +import { UIButtonAttribute as UIButtonAttribute } from \"arkui.component.button\"; +import { EntryPoint as EntryPoint } from \"arkui.UserView\"; +import { CustomComponent as CustomComponent } from \"arkui.component.customComponent\"; +import { Prop as Prop, Column as Column, Entry as Entry } from \"@kit.ArkUI\"; +import { Text as Text, Component as Component, ClickEvent as ClickEvent } from \"@ohos.arkui.component\"; +import { State as State } from \"@ohos.arkui.stateManagement\"; +import { Button as Button } from \"arkui.component.button\"; +import hilog from \"@ohos.hilog\"; + +function main() {} + +@Entry({useSharedStorage:false,storage:\"\",routeName:\"\"}) @Component({freezeWhenInactive:false}) final class A extends CustomComponent { + public __initializeStruct(initializers: __Options_A | undefined, @memo() content: (()=> void) | undefined): void { + this.__backing_a = new StateDecoratedVariable(\"a\", ((({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.a)})) ?? (\"str\"))); + this.__backing_b = new PropDecoratedVariable(\"b\", (initializers!.b as string)); + } + public __updateStruct(initializers: __Options_A | undefined): void { + if (((({let gensym___ = initializers; + (((gensym___) == (null)) ? undefined : gensym___.b)})) !== (undefined))) { + this.__backing_b!.update((initializers!.b as string)); + } + } + private __backing_a?: StateDecoratedVariable; + public get a(): string { + return this.__backing_a!.get(); + } + public set a(value: string) { + this.__backing_a!.set(value); + } + private __backing_b?: PropDecoratedVariable; + public get b(): string { + return this.__backing_b!.get(); + } + public set b(value: string) { + this.__backing_b!.set(value); + } + @memo() public _build(@memo() style: ((instance: A)=> A) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_A | undefined): void { + Column(undefined, (() => { + Button(@memo() ((instance: UIButtonAttribute): void => { + instance.onClick(((e: ClickEvent) => {})); + return; + }), \"button\"); + Text(@memo() ((instance: UITextAttribute): void => { + instance.fontSize(20); + return; + }), \"text\"); + })); + } + private constructor() {} +} + +@Entry({useSharedStorage:false,storage:\"\",routeName:\"\"}) @Component({freezeWhenInactive:false}) export interface __Options_A { + set a(a: string | undefined) + get a(): string | undefined + set __backing_a(__backing_a: StateDecoratedVariable | undefined) + get __backing_a(): StateDecoratedVariable | undefined + set b(b: string | undefined) + get b(): string | undefined + set __backing_b(__backing_b: PropDecoratedVariable | undefined) + get __backing_b(): PropDecoratedVariable | undefined +} + +class __EntryWrapper extends EntryPoint { + @memo() public entry(): void { + A._instantiateImpl(undefined, (() => { + return new A(); + })); + } + public constructor() {} +} +`; + +function testImportParsed(this: PluginTestContext): void { + expect(parseDumpSrc(this?.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedParsedScript)); +} + +function testImportChecked(this: PluginTestContext): void { + expect(parseDumpSrc(this?.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedCheckedScript)); +} + +pluginTester.run( + 'test imports from different sources', + [importParsed, uiNoRecheck, recheck], + { + parsed: [testImportParsed], + 'checked:ui-no-recheck': [testImportChecked], + }, + { + stopAfter: 'checked', + } +); diff --git a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts index d73385ec4..7a38d7544 100644 --- a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts @@ -39,7 +39,7 @@ const pluginTester = new PluginTester('test basic XComponent transform', buildCo const expectedScript: string = ` import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIFlexAttribute as UIFlexAttribute } from "@ohos.arkui.component"; +import { UIFlexAttribute as UIFlexAttribute } from "arkui.component.flex"; import { EntryPoint as EntryPoint } from "arkui.UserView"; import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; import { Component as Component, Flex as Flex, XComponent as XComponent, FlexDirection as FlexDirection, XComponentType as XComponentType, Entry as Entry, XComponentController as XComponentController, ItemAlign as ItemAlign, FlexAlign as FlexAlign, XComponentParameter as XComponentParameter } from "@ohos.arkui.component"; diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index 0eab2241e..c218c9086 100644 --- a/arkui-plugins/test/utils/artkts-config.ts +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -64,7 +64,8 @@ export interface ArktsConfigBuilder { outputDir: string; cacheDir: string; pandaSdkPath: string; - buildSdkPath: string; + apiPath: string; + kitsPath: string; packageName: string; sourceRoots: string[]; moduleRootPath: string; @@ -151,7 +152,8 @@ function mockBuildConfig(): BuildConfig { loaderOutPath: path.resolve(getRootPath(), MOCK_OUTPUT_DIR_PATH), cachePath: path.resolve(getRootPath(), MOCK_OUTPUT_CACHE_PATH), pandaSdkPath: global.PANDA_SDK_PATH, - buildSdkPath: global.API_PATH, + apiPath: global.API_PATH, + kitsPath: global.KIT_PATH, depAnalyzerPath: path.resolve(global.PANDA_SDK_PATH, MOCK_DEP_ANALYZER_PATH), sourceRoots: [getRootPath()], moduleRootPath: path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH), @@ -167,7 +169,8 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { outputDir: string; cacheDir: string; pandaSdkPath: string; - buildSdkPath: string; + apiPath: string; + kitsPath: string; packageName: string; sourceRoots: string[]; moduleRootPath: string; @@ -185,7 +188,8 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { this.outputDir = _buildConfig.loaderOutPath as string; this.cacheDir = _buildConfig.cachePath as string; this.pandaSdkPath = path.resolve(_buildConfig.pandaSdkPath as string); - this.buildSdkPath = path.resolve(_buildConfig.buildSdkPath as string); + this.apiPath = path.resolve(_buildConfig.apiPath as string); + this.kitsPath = path.resolve(_buildConfig.kitsPath as string); this.packageName = _buildConfig.packageName as string; this.sourceRoots = _buildConfig.sourceRoots as string[]; this.moduleRootPath = path.resolve(_buildConfig.moduleRootPath as string); @@ -276,7 +280,8 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { const pathSection: Record = {}; pathSection['std'] = [path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_STD_PATH)]; pathSection['escompat'] = [path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_ESCOMPAT_PATH)]; - traverseSDK(this.buildSdkPath, pathSection); + traverseSDK(this.apiPath, pathSection); + traverseSDK(this.kitsPath, pathSection); this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { pathSection[moduleInfo.packageName] = [path.resolve(moduleRootPath, moduleInfo.sourceRoots[0])]; diff --git a/arkui-plugins/test/utils/shared-types.ts b/arkui-plugins/test/utils/shared-types.ts index b795e9c79..d713420e5 100644 --- a/arkui-plugins/test/utils/shared-types.ts +++ b/arkui-plugins/test/utils/shared-types.ts @@ -55,7 +55,8 @@ export interface BuildConfig { loaderOutPath: string; cachePath: string; pandaSdkPath: string; - buildSdkPath: string; + apiPath: string; + kitsPath: string; depAnalyzerPath: string; sourceRoots: string[]; moduleRootPath: string; diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts index 7a821bd74..d4fdf5269 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts @@ -14,9 +14,9 @@ */ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../../common/abstract-visitor'; +import { ImportCollector } from '../../common/import-collector'; import { isBuilderLambda, isBuilderLambdaMethodDecl } from './utils'; import { factory } from './factory'; -import { ImportCollector } from '../import-collector'; import { ProjectConfig } from '../../common/plugin-context'; export class BuilderLambdaTransformer extends AbstractVisitor { diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index b3eaa5870..7171c74dd 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -19,11 +19,9 @@ import { BuilderLambdaNames, CustomComponentNames, findCanAddMemoFromParamExpression, - findImportSource, - getCustomComponentOptionsName, isCustomComponentAnnotation, } from '../utils'; -import { annotation, backingField, filterDefined, removeAnnotationByName } from '../../common/arkts-utils'; +import { backingField, filterDefined, removeAnnotationByName } from '../../common/arkts-utils'; import { BuilderLambdaDeclInfo, builderLambdaFunctionName, @@ -36,7 +34,6 @@ import { isBuilderLambdaFunctionCall, isSafeType, replaceBuilderLambdaDeclMethodName, - BindableDecl, getDecalTypeFromValue, hasBindableProperty, isDoubleDollarCall, @@ -45,10 +42,11 @@ import { isStyleWithReceiverCall, builderLambdaType, } from './utils'; -import { DecoratorIntrinsicNames, DecoratorNames, isDecoratorIntrinsicAnnotation } from '../property-translators/utils'; +import { isDecoratorIntrinsicAnnotation } from '../property-translators/utils'; import { factory as PropertyFactory } from '../property-translators/factory'; import { ProjectConfig } from '../../common/plugin-context'; -import { ImportCollector } from '../import-collector'; +import { BindableDecl, DecoratorIntrinsicNames, StructDecoratorNames } from '../../common/predefines'; +import { ImportCollector } from '../../common/import-collector'; export class factory { /** @@ -217,12 +215,13 @@ export class factory { */ static createStyleArgInBuilderLambda( lambdaBody: arkts.Expression | undefined, - typeNode: arkts.TypeNode | undefined + typeNode: arkts.TypeNode | undefined, + moduleName: string ): arkts.UndefinedLiteral | arkts.ArrowFunctionExpression { if (!lambdaBody) { return arkts.factory.createUndefinedLiteral(); } - collectComponentAttributeImport(typeNode); + collectComponentAttributeImport(typeNode, moduleName); const safeType: arkts.TypeNode | undefined = isSafeType(typeNode) ? typeNode : undefined; const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( @@ -407,7 +406,7 @@ export class factory { declInfo: BuilderLambdaDeclInfo, projectConfig: ProjectConfig | undefined ): (arkts.AstNode | undefined)[] { - const { isFunctionCall, params, returnType } = declInfo; + const { isFunctionCall, params, returnType, moduleName } = declInfo; const type: arkts.Identifier | undefined = builderLambdaType(leaf); let isReusable: boolean | undefined; let reuseId: arkts.StringLiteral | undefined; @@ -417,11 +416,11 @@ export class factory { !!customComponentDecl && arkts.isClassDefinition(customComponentDecl) && customComponentDecl.annotations.some((anno) => - isCustomComponentAnnotation(anno, CustomComponentNames.RESUABLE_ANNOTATION) + isCustomComponentAnnotation(anno, StructDecoratorNames.RESUABLE) ); reuseId = isReusable ? arkts.factory.createStringLiteral(type.name) : undefined; } - const args: (arkts.AstNode | undefined)[] = [this.createStyleArgInBuilderLambda(lambdaBody, returnType)]; + const args: (arkts.AstNode | undefined)[] = [this.createStyleArgInBuilderLambda(lambdaBody, returnType, moduleName)]; let index = 0; while (index < params.length) { if (isReusable && index === params.length - 1) { @@ -724,8 +723,6 @@ export class factory { */ static createBindableType(valueType: arkts.TypeNode): arkts.ETSTypeReference { const transformedKey = BindableDecl.BINDABLE; - const source = findImportSource(transformedKey); - ImportCollector.getInstance().collectSource(transformedKey, source); ImportCollector.getInstance().collectImport(transformedKey); return arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index 4b9f4b9ba..7aac15fc1 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -14,22 +14,19 @@ */ import * as arkts from '@koalaui/libarkts'; -import { isAnnotation } from '../../common/arkts-utils'; -import { BuilderLambdaNames, Dollars } from '../utils'; -import { ImportCollector } from '../import-collector'; +import { isAnnotation, matchPrefix } from '../../common/arkts-utils'; +import { BuilderLambdaNames } from '../utils'; import { DeclarationCollector } from '../../common/declaration-collector'; -import { ARKUI_COMPONENT_IMPORT_NAME } from '../../common/predefines'; +import { ARKUI_IMPORT_PREFIX_NAMES, BindableDecl, Dollars } from '../../common/predefines'; +import { ImportCollector } from '../../common/import-collector'; export type BuilderLambdaDeclInfo = { isFunctionCall: boolean; // isFunctionCall means it is from $_instantiate. params: readonly arkts.Expression[]; returnType: arkts.TypeNode | undefined; + moduleName: string; }; -export enum BindableDecl { - BINDABLE = 'Bindable', -} - export type BuilderLambdaAstNode = arkts.ScriptFunction | arkts.ETSParameterExpression | arkts.FunctionDeclaration; export type InstanceCallInfo = { @@ -273,6 +270,10 @@ export function findBuilderLambdaDecl(node: arkts.CallExpression | arkts.Identif if (!decl) { return undefined; } + const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; + if (!moduleName || !matchPrefix(ARKUI_IMPORT_PREFIX_NAMES, moduleName)) { + return undefined; + } DeclarationCollector.getInstance().collect(decl); return decl; } @@ -297,12 +298,15 @@ export function findBuilderLambdaDeclInfo(decl: arkts.AstNode | undefined): Buil if (!decl) { return undefined; } - + const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; + if (!moduleName || !matchPrefix(ARKUI_IMPORT_PREFIX_NAMES, moduleName)) { + return undefined; + } if (arkts.isMethodDefinition(decl)) { const params = decl.scriptFunction.params.map((p) => p.clone()); const returnType = decl.scriptFunction.returnTypeAnnotation?.clone(); const isFunctionCall = isBuilderLambdaFunctionCall(decl); - return { isFunctionCall, params, returnType }; + return { isFunctionCall, params, returnType, moduleName }; } return undefined; @@ -407,16 +411,30 @@ export function hasBindableProperty(type: arkts.AstNode, bindableDecl: BindableD * * @param value expression node */ -export function isDoubleDollarCall(value: arkts.Expression): value is arkts.CallExpression { +export function isDoubleDollarCall( + value: arkts.Expression, + ignoreDecl: boolean = false +): value is arkts.CallExpression { + if (!arkts.isCallExpression(value)) { + return false; + } if ( - arkts.isCallExpression(value) && - value.expression && - arkts.isIdentifier(value.expression) && - value.expression.name + !(!!value.expression && arkts.isIdentifier(value.expression) && value.expression.name === Dollars.DOLLAR_DOLLAR) ) { - return value.expression.name === Dollars.DOLLAR_DOLLAR; + return false; } - return false; + if (!ignoreDecl) { + const decl = arkts.getDecl(value); + if (!decl) { + return false; + } + const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; + if (!moduleName || !matchPrefix(ARKUI_IMPORT_PREFIX_NAMES, moduleName)) { + return false; + } + DeclarationCollector.getInstance().collect(decl); + } + return true; } /** @@ -472,7 +490,7 @@ export function getElementTypeFromArray(arrayType: arkts.TypeNode): arkts.TypeNo return undefined; } -export function collectComponentAttributeImport(type: arkts.TypeNode | undefined): void { +export function collectComponentAttributeImport(type: arkts.TypeNode | undefined, moduleName: string): void { if ( !type || !arkts.isETSTypeReference(type) || @@ -488,7 +506,7 @@ export function collectComponentAttributeImport(type: arkts.TypeNode | undefined const match: RegExpExecArray | null = regex.exec(name); const attributeName: string | undefined = match?.groups?.source; if (!!attributeName) { - ImportCollector.getInstance().collectSource(attributeName, ARKUI_COMPONENT_IMPORT_NAME); + ImportCollector.getInstance().collectSource(attributeName, moduleName); ImportCollector.getInstance().collectImport(attributeName); } } diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 890414658..cde68e6c9 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -33,7 +33,8 @@ import { } from './struct-translators/utils'; import { isBuilderLambda, isBuilderLambdaMethodDecl } from './builder-lambda-translators/utils'; import { isEntryWrapperClass } from './entry-translators/utils'; -import { ImportCollector } from './import-collector'; +import { ImportCollector } from '../common/import-collector'; +import { DeclarationCollector } from '../common/declaration-collector'; import { PropertyCache } from './property-translators/utils'; import { isArkUICompatible, updateArkUICompatible } from './interop'; @@ -52,6 +53,7 @@ export class CheckedTransformer extends AbstractVisitor { this.scope = { customComponents: [] }; PropertyCache.getInstance().reset(); ImportCollector.getInstance().reset(); + DeclarationCollector.getInstance().reset(); } enter(node: arkts.AstNode): void { @@ -66,7 +68,6 @@ export class CheckedTransformer extends AbstractVisitor { const scopeInfo = this.scope.customComponents.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; - scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; this.scope.customComponents.push(scopeInfo); } } diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index cf856101a..4485bc9bd 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -26,20 +26,27 @@ import { collectCustomComponentScopeInfo, isComponentStruct, } from './utils'; -import { backingField, expectName, annotation, filterDefined, collect } from '../common/arkts-utils'; +import { + backingField, + expectName, + annotation, + filterDefined, + collect, + createAndInsertImportDeclaration, +} from '../common/arkts-utils'; import { EntryWrapperNames, findEntryWithStorageInClassAnnotations } from './entry-translators/utils'; import { factory as entryFactory } from './entry-translators/factory'; -import { - hasDecoratorName, - DecoratorNames, - findDecoratorInfos, - isDecoratorAnnotation, - decoratorTypeMap, - DecoratorIntrinsicNames, -} from './property-translators/utils'; +import { hasDecoratorName, findDecoratorInfos, isDecoratorAnnotation } from './property-translators/utils'; import { factory } from './ui-factory'; import { factory as propertyFactory } from './property-translators/factory'; import { StructMap } from '../common/program-visitor'; +import { + CUSTOM_COMPONENT_IMPORT_SOURCE_NAME, + DecoratorIntrinsicNames, + DecoratorNames, + DECORATOR_TYPE_MAP, + ENTRY_POINT_IMPORT_SOURCE_NAME, +} from '../common/predefines'; import { generateTempCallFunction } from './interop'; export interface ComponentTransformerOptions extends VisitorOptions { @@ -60,7 +67,6 @@ export class ComponentTransformer extends AbstractVisitor { private scopeInfos: ScopeInfo[] = []; private componentInterfaceCollection: arkts.TSInterfaceDeclaration[] = []; private entryNames: string[] = []; - private readonly arkui?: string; private structMembersMap: Map = new Map(); private isCustomComponentImported: boolean = false; private isEntryPointImported: boolean = false; @@ -72,7 +78,6 @@ export class ComponentTransformer extends AbstractVisitor { constructor(options?: ComponentTransformerOptions) { const _options: ComponentTransformerOptions = options ?? {}; super(_options); - this.arkui = _options.arkui; } reset(): void { @@ -99,14 +104,14 @@ export class ComponentTransformer extends AbstractVisitor { if (arkts.isETSImportDeclaration(node) && !this.isCustomComponentImported) { this.isCustomComponentImported = !!findLocalImport( node, - CustomComponentNames.COMPONENT_DEFAULT_IMPORT, + CUSTOM_COMPONENT_IMPORT_SOURCE_NAME, CustomComponentNames.COMPONENT_CLASS_NAME ); } if (arkts.isETSImportDeclaration(node) && !this.isEntryPointImported) { this.isEntryPointImported = !!findLocalImport( node, - EntryWrapperNames.ENTRY_DEFAULT_IMPORT, + ENTRY_POINT_IMPORT_SOURCE_NAME, EntryWrapperNames.ENTRY_POINT_CLASS_NAME ); } @@ -122,15 +127,13 @@ export class ComponentTransformer extends AbstractVisitor { } createImportDeclaration(): void { - const source: arkts.StringLiteral = arkts.factory.create1StringLiteral( - this.arkui ?? CustomComponentNames.COMPONENT_DEFAULT_IMPORT - ); + const source: arkts.StringLiteral = arkts.factory.create1StringLiteral(CUSTOM_COMPONENT_IMPORT_SOURCE_NAME); const imported: arkts.Identifier = arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_CLASS_NAME); // Insert this import at the top of the script's statements. if (!this.program) { throw Error('Failed to insert import: Transformer has no program'); } - factory.createAndInsertImportDeclaration( + createAndInsertImportDeclaration( source, imported, imported, @@ -347,7 +350,7 @@ export class ComponentTransformer extends AbstractVisitor { originMember.setAnnotations([buildParamInfo.annotation.clone()]); return [originMember]; } - const targetInfo = infos.find((it) => decoratorTypeMap.has(it.name)); + const targetInfo = infos.find((it) => DECORATOR_TYPE_MAP.has(it.name)); if (!!targetInfo) { const newName: string = backingField(originalName); const newMember: arkts.ClassProperty = propertyFactory diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index 1e395923a..09d1c85b7 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -14,12 +14,9 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getInteropPath } from '../../path'; -const interop = require(getInteropPath()); -const nullptr = interop.nullptr; import { EntryWrapperNames } from './utils'; -import { annotation } from '../../common/arkts-utils'; -import { factory as uiFactory } from '../ui-factory'; +import { annotation, createAndInsertImportDeclaration } from '../../common/arkts-utils'; +import { ENTRY_POINT_IMPORT_SOURCE_NAME } from '../../common/predefines'; export class factory { /** @@ -270,13 +267,13 @@ export class factory { * to the top of script's statements. */ static createAndInsertEntryPointImport(program?: arkts.Program) { - const source: arkts.StringLiteral = arkts.factory.create1StringLiteral(EntryWrapperNames.ENTRY_DEFAULT_IMPORT); + const source: arkts.StringLiteral = arkts.factory.create1StringLiteral(ENTRY_POINT_IMPORT_SOURCE_NAME); const imported: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME); // Insert this import at the top of the script's statements. if (!program) { throw Error('Failed to insert import: Transformer has no program'); } - uiFactory.createAndInsertImportDeclaration( + createAndInsertImportDeclaration( source, imported, imported, diff --git a/arkui-plugins/ui-plugins/entry-translators/utils.ts b/arkui-plugins/ui-plugins/entry-translators/utils.ts index 2788e987c..a987f631b 100644 --- a/arkui-plugins/ui-plugins/entry-translators/utils.ts +++ b/arkui-plugins/ui-plugins/entry-translators/utils.ts @@ -16,14 +16,13 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './factory'; import { isAnnotation } from '../../common/arkts-utils'; -import { CustomComponentNames } from '../utils'; +import { StructDecoratorNames } from '../../common/predefines'; export enum EntryWrapperNames { ENTRY_FUNC = 'entry', WRAPPER_CLASS_NAME = '__EntryWrapper', ENTRY_STORAGE_ANNOTATION_KEY = 'storage', ENTRY_STORAGE_LOCAL_STORAGE_PROPERTY_NAME = '_entry_local_storage_', - ENTRY_DEFAULT_IMPORT = 'arkui.UserView', ENTRY_POINT_CLASS_NAME = 'EntryPoint', } @@ -73,7 +72,7 @@ export function isEntryWrapperClass(node: arkts.AstNode): node is arkts.ClassDec */ export function findEntryWithStorageInClassAnnotations(node: arkts.ClassDefinition): arkts.ClassProperty | undefined { const annotation = node.annotations.find((anno) => { - if (!isAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION)) return false; + if (!isAnnotation(anno, StructDecoratorNames.ENTRY)) return false; const property = anno.properties?.at(0); if (!property || !arkts.isClassProperty(property)) return false; if (!property.key || !arkts.isIdentifier(property.key)) return false; diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 35132fb5a..9a8cba2bd 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -14,36 +14,12 @@ */ import * as arkts from '@koalaui/libarkts'; -import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; +import { AbstractVisitor } from '../common/abstract-visitor'; import { CustomComponentNames } from './utils'; import { factory } from './ui-factory'; -import { - ARKUI_COMPONENT_IMPORT_NAME, - IMPORT_SOURCE_MAP, - OUTPUT_DEPENDENCY_MAP, - ARKUI_STATEMANAGEMENT_IMPORT_NAME, - KIT_ARKUI_NAME, -} from '../common/predefines'; -import { NameCollector } from './name-collector'; export class PreprocessorTransformer extends AbstractVisitor { - private outNameArr: string[] = []; private structInterfaceImport: arkts.ETSImportDeclaration[] = []; - private localComponentNames: string[] = []; - - private readonly nameCollector: NameCollector; - - constructor(options?: VisitorOptions) { - super(options); - this.nameCollector = NameCollector.getInstance(); - } - - reset(): void { - super.reset(); - this.outNameArr = []; - this.structInterfaceImport = []; - this.localComponentNames = []; - } isCustomConponentDecl(node: arkts.CallExpression): boolean { const nodeName: string = node.expression.dumpSrc(); @@ -53,11 +29,6 @@ export class PreprocessorTransformer extends AbstractVisitor { return false; } - isComponentFunctionCall(node: arkts.CallExpression): boolean { - if (!node || !arkts.isIdentifier(node.expression)) return false; - return this.localComponentNames.includes(node.expression.name); - } - transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { if (node.arguments.length === 0 && node.trailingBlock) { return node; @@ -81,38 +52,11 @@ export class PreprocessorTransformer extends AbstractVisitor { } } - transformComponentFunctionCall(node: arkts.CallExpression) { - if (!node || !arkts.isIdentifier(node.expression)) return node; - - const componentInfo = this.nameCollector.getComponentInfo(node.expression.name); - if (!componentInfo) return node; - if (componentInfo.argsNum === 0) return node; - if (node.arguments.length >= componentInfo.argsNum - 1) return node; - - const defaultArgs: arkts.UndefinedLiteral[] = []; - let count = 0; - while (count < componentInfo.argsNum - node.arguments.length - 1) { - defaultArgs.push(arkts.factory.createUndefinedLiteral()); - count++; - } - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ - ...node.arguments, - ...defaultArgs, - ]); - } - addDependencesImport(node: arkts.ETSImportDeclaration): void { if (!node.source) return; - - const isFromCompImport: boolean = node.source.str === ARKUI_COMPONENT_IMPORT_NAME || node.source.str === KIT_ARKUI_NAME; node.specifiers.forEach((item: arkts.AstNode) => { if (!arkts.isImportSpecifier(item) || !item.imported?.name) return; - const importName: string = item.imported.name; - if (isFromCompImport && this.nameCollector.getComponents().includes(importName)) { - this.localComponentNames.push(item.local?.name ?? importName); - } - if (arkts.hasGlobalStructInfo(importName)) { const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + importName; const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( @@ -123,57 +67,8 @@ export class PreprocessorTransformer extends AbstractVisitor { arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE ); this.structInterfaceImport.push(newImport); - } else { - this.addImportWithSpecifier(item, node.source!); - } - }); - } - - getSourceDependency(sourceName: string): string { - let dependencyName: string = ''; - IMPORT_SOURCE_MAP.forEach((value: Set, key: string) => { - if (value.has(sourceName)) { - dependencyName = key; } }); - return dependencyName; - } - - updateSourceDependencyMap(key: string, value: string[]): void { - const newValue: Set = IMPORT_SOURCE_MAP.get(key) ?? new Set(); - for (const v of value) { - newValue.add(v); - } - IMPORT_SOURCE_MAP.set(key, newValue); - } - - getOutDependencyName(inputName: string): string[] { - const sourceName: string[] = []; - if (OUTPUT_DEPENDENCY_MAP.has(inputName)) { - OUTPUT_DEPENDENCY_MAP.get(inputName)!.forEach((item: string) => { - sourceName.push(item); - }); - } - return sourceName; - } - - updateOutDependencyMap(key: string, value: string[]): void { - const oldValue: string[] = OUTPUT_DEPENDENCY_MAP.get(key) ?? []; - const newValue: string[] = [...value, ...oldValue]; - OUTPUT_DEPENDENCY_MAP.set(key, newValue); - } - - clearGenSymInOutDependencyMap(genSymKey: string): void { - if (OUTPUT_DEPENDENCY_MAP.has(genSymKey)) { - OUTPUT_DEPENDENCY_MAP.delete(genSymKey); - } - } - - addImportWithSpecifier(node: arkts.ImportSpecifier, source: arkts.StringLiteral): void { - if (!node.imported?.name) return; - - const outName: string[] = this.getOutDependencyName(node.imported?.name); - this.outNameArr.push(...outName); } updateScriptWithImport(): void { @@ -181,30 +76,11 @@ export class PreprocessorTransformer extends AbstractVisitor { throw Error('Failed to insert import: Transformer has no program'); } - const outNames = new Set([...this.outNameArr]); - outNames.forEach((item: string) => { - const source: string = this.getSourceDependency(item); - const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( - arkts.factory.create1StringLiteral(source), - [factory.createAdditionalImportSpecifier(item, item)], - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, - this.program!, - arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE - ); - arkts.importDeclarationInsert(newImport, this.program!); - }); this.structInterfaceImport.forEach((element: arkts.ETSImportDeclaration) => { arkts.importDeclarationInsert(element, this.program!); }); } - enter(node: arkts.AstNode): void { - if (this.isExternal && arkts.isFunctionDeclaration(node)) { - const component = this.nameCollector.findComponentFunction(node); - if (!!component) this.nameCollector.collectInfoFromComponentFunction(component); - } - } - visitor(node: arkts.AstNode): arkts.AstNode { const newNode = this.visitEachChild(node); if (arkts.isCallExpression(newNode) && this.isCustomConponentDecl(newNode)) { diff --git a/arkui-plugins/ui-plugins/property-translators/base.ts b/arkui-plugins/ui-plugins/property-translators/base.ts index 6601ab282..a553aaa7f 100644 --- a/arkui-plugins/ui-plugins/property-translators/base.ts +++ b/arkui-plugins/ui-plugins/property-translators/base.ts @@ -16,12 +16,11 @@ import * as arkts from '@koalaui/libarkts'; import { collectStateManagementTypeImport, - collectStateManagementTypeSource, createGetter, createSetter, - StateManagementTypes, } from './utils'; import { CustomComponentInfo } from '../utils'; +import { StateManagementTypes } from '../../common/predefines'; export interface PropertyTranslatorOptions { property: arkts.ClassProperty; @@ -57,7 +56,6 @@ export abstract class PropertyTranslator { undefined, [arkts.factory.createIdentifier('value')] ); - collectStateManagementTypeSource(StateManagementTypes.OBSERVABLE_PROXY); collectStateManagementTypeImport(StateManagementTypes.OBSERVABLE_PROXY); return createSetter(originalName, typeAnnotation, left, right); } diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts index 62b1f532b..44266f3d1 100644 --- a/arkui-plugins/ui-plugins/property-translators/builderParam.ts +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -15,18 +15,18 @@ import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames } from '../../common/predefines'; import { createGetter, createSetter, generateThisBacking, - DecoratorNames, hasDecorator, removeDecorator, PropertyCache, } from './utils'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { backingField, expectName } from '../../common/arkts-utils'; import { addMemoAnnotation, findCanAddMemoFromParamExpression, findCanAddMemoFromTypeAnnotation } from '../utils'; import { factory } from './factory'; diff --git a/arkui-plugins/ui-plugins/property-translators/consume.ts b/arkui-plugins/ui-plugins/property-translators/consume.ts index 553f586c8..d4f0176b2 100644 --- a/arkui-plugins/ui-plugins/property-translators/consume.ts +++ b/arkui-plugins/ui-plugins/property-translators/consume.ts @@ -15,6 +15,8 @@ import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { generateToRecord, createGetter, @@ -22,14 +24,11 @@ import { generateThisBacking, generateGetOrSetCall, getValueInAnnotation, - DecoratorNames, - StateManagementTypes, hasDecorator, PropertyCache, } from './utils'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; export class ConsumeTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts index 704dced97..904811f12 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -15,17 +15,9 @@ import * as arkts from '@koalaui/libarkts'; import { GenSymGenerator } from '../../common/gensym-generator'; +import { DecoratorNames, DECORATOR_TYPE_MAP, StateManagementTypes } from '../../common/predefines'; import { factory as UIFactory } from '../ui-factory'; -import { - collectStateManagementTypeImport, - collectStateManagementTypeSource, - DecoratorNames, - decoratorTypeMap, - getValueInAnnotation, - hasDecorator, - removeDecorator, - StateManagementTypes, -} from './utils'; +import { collectStateManagementTypeImport, getValueInAnnotation, hasDecorator, removeDecorator } from './utils'; import { addMemoAnnotation, findCanAddMemoFromTypeAnnotation } from '../utils'; export class factory { @@ -338,7 +330,6 @@ export class factory { stageManagementType: StateManagementTypes, property: arkts.ClassProperty ): arkts.ETSTypeReference { - collectStateManagementTypeSource(stageManagementType); collectStateManagementTypeImport(stageManagementType); return arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( @@ -369,7 +360,6 @@ export class factory { arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, false ); - collectStateManagementTypeSource(StateManagementTypes.SUBSCRIBED_WATCHES); collectStateManagementTypeImport(StateManagementTypes.SUBSCRIBED_WATCHES); const addWatchSubscriber = factory.createWatchMethod( @@ -386,7 +376,6 @@ export class factory { StateManagementTypes.WATCH_ID_TYPE, true ); - collectStateManagementTypeSource(StateManagementTypes.WATCH_ID_TYPE); collectStateManagementTypeImport(StateManagementTypes.WATCH_ID_TYPE); const executeOnSubscribingWatches = factory.createWatchMethod( @@ -555,8 +544,7 @@ export class factory { ): arkts.TypeNode | undefined { let newType: arkts.TypeNode | undefined; let wrapTypeName: StateManagementTypes | undefined; - if (!!type && !!(wrapTypeName = decoratorTypeMap.get(decoratorName))) { - collectStateManagementTypeSource(wrapTypeName); + if (!!type && !!(wrapTypeName = DECORATOR_TYPE_MAP.get(decoratorName))) { newType = factory.wrapInterfacePropertyType(type, wrapTypeName); collectStateManagementTypeImport(wrapTypeName); } @@ -569,8 +557,7 @@ export class factory { ): arkts.Expression | undefined { let newParam: arkts.Expression | undefined; let wrapTypeName: StateManagementTypes | undefined; - if (!!param && !!(wrapTypeName = decoratorTypeMap.get(decoratorName))) { - collectStateManagementTypeSource(wrapTypeName); + if (!!param && !!(wrapTypeName = DECORATOR_TYPE_MAP.get(decoratorName))) { newParam = factory.wrapInterfacePropertyParamExpr(param, wrapTypeName); collectStateManagementTypeImport(wrapTypeName); } diff --git a/arkui-plugins/ui-plugins/property-translators/index.ts b/arkui-plugins/ui-plugins/property-translators/index.ts index 7695a7f96..aa0c767c5 100644 --- a/arkui-plugins/ui-plugins/property-translators/index.ts +++ b/arkui-plugins/ui-plugins/property-translators/index.ts @@ -15,8 +15,9 @@ import * as arkts from '@koalaui/libarkts'; +import { DecoratorNames } from '../../common/predefines'; import { InterfacePropertyTranslator, PropertyTranslator } from './base'; -import { DecoratorNames, hasDecorator } from './utils'; +import { hasDecorator } from './utils'; import { StateInterfaceTranslator, StateTranslator } from './state'; import { PropInterfaceTranslator, PropTranslator } from './prop'; import { StorageLinkInterfaceTranslator, StorageLinkTranslator } from './storagelink'; diff --git a/arkui-plugins/ui-plugins/property-translators/link.ts b/arkui-plugins/ui-plugins/property-translators/link.ts index f3c903310..09a72cda4 100644 --- a/arkui-plugins/ui-plugins/property-translators/link.ts +++ b/arkui-plugins/ui-plugins/property-translators/link.ts @@ -15,22 +15,20 @@ import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { generateToRecord, createGetter, createSetter2, generateThisBacking, generateGetOrSetCall, - StateManagementTypes, - collectStateManagementTypeSource, collectStateManagementTypeImport, hasDecorator, - DecoratorNames, PropertyCache, } from './utils'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; export class LinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { @@ -64,7 +62,6 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon ), ]; factory.judgeIfAddWatchFunc(args, this.property); - collectStateManagementTypeSource(StateManagementTypes.LINK_DECORATED); collectStateManagementTypeImport(StateManagementTypes.LINK_DECORATED); const consequent = arkts.BlockStatement.createBlockStatement([ arkts.factory.createExpressionStatement( diff --git a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts index b61615400..cc1e0ba11 100755 --- a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts @@ -16,16 +16,14 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { collectStateManagementTypeImport, - collectStateManagementTypeSource, - DecoratorNames, generateToRecord, hasDecorator, PropertyCache, - StateManagementTypes, } from './utils'; import { factory } from './factory'; @@ -135,7 +133,6 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In this.property.value ?? arkts.factory.createUndefinedLiteral(), ] ); - collectStateManagementTypeSource(StateManagementTypes.STORAGE_LINK_STATE); collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_STATE); return arkts.factory.createAssignmentExpression( diff --git a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts index fb528539e..58eec31cc 100644 --- a/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstorageprop.ts @@ -15,18 +15,16 @@ import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { collectStateManagementTypeImport, - collectStateManagementTypeSource, - DecoratorNames, generateToRecord, hasDecorator, PropertyCache, - StateManagementTypes, } from './utils'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; function getLocalStorageporpValueStr(node: arkts.AstNode): string | undefined { @@ -137,7 +135,6 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In this.property.value ?? arkts.factory.createUndefinedLiteral(), ] ); - collectStateManagementTypeSource(StateManagementTypes.STORAGE_LINK_STATE); collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_STATE); const call = arkts.factory.createCallExpression( arkts.factory.createIdentifier(StateManagementTypes.PROP_STATE), @@ -152,7 +149,6 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In ), ] ); - collectStateManagementTypeSource(StateManagementTypes.PROP_STATE); collectStateManagementTypeImport(StateManagementTypes.PROP_STATE); return arkts.factory.createAssignmentExpression( arkts.factory.createMemberExpression( @@ -173,7 +169,6 @@ export class LocalStoragePropTranslator extends PropertyTranslator implements In throw new Error('StorageLink required only one value!!'); } const StorageLinkStateValue = factory.createStorageLinkStateValue(this.property, localStorageporpValueStr); - collectStateManagementTypeSource(StateManagementTypes.STORAGE_LINK_STATE); collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_STATE); const test = arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), diff --git a/arkui-plugins/ui-plugins/property-translators/objectlink.ts b/arkui-plugins/ui-plugins/property-translators/objectlink.ts index 5f7ee7d69..27e7af8fc 100644 --- a/arkui-plugins/ui-plugins/property-translators/objectlink.ts +++ b/arkui-plugins/ui-plugins/property-translators/objectlink.ts @@ -15,19 +15,18 @@ import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { createGetter, - DecoratorNames, generateGetOrSetCall, generateThisBacking, generateToRecord, hasDecorator, PropertyCache, - StateManagementTypes, } from './utils'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; export class ObjectLinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts index 0e84301aa..91e3fdf99 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -15,12 +15,10 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { collectStateManagementTypeImport, - collectStateManagementTypeSource, - DecoratorNames, hasDecorator, - StateManagementTypes, } from './utils'; import { ClassScopeInfo } from './types'; @@ -193,7 +191,6 @@ export class ObservedTrackTranslator { } propertyIsClassField(newName: string): arkts.ClassProperty { - collectStateManagementTypeSource(StateManagementTypes.BACKING_VALUE); collectStateManagementTypeImport(StateManagementTypes.BACKING_VALUE); return arkts.factory.createClassProperty( arkts.factory.createIdentifier(newName), @@ -224,7 +221,6 @@ export class ObservedTrackTranslator { } metaField(originalName: string): arkts.ClassProperty { - collectStateManagementTypeSource(StateManagementTypes.MUTABLE_STATE_META); collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); return arkts.factory.createClassProperty( arkts.factory.createIdentifier(`__meta_${originalName}`), @@ -286,7 +282,6 @@ export class ObservedTrackTranslator { } getterSetObservationDepth(newName: string): arkts.ExpressionStatement { - collectStateManagementTypeSource(StateManagementTypes.SET_OBSERVATION_DEPTH); collectStateManagementTypeImport(StateManagementTypes.SET_OBSERVATION_DEPTH); return arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts index f1b09a65d..8cfacd224 100644 --- a/arkui-plugins/ui-plugins/property-translators/prop.ts +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -15,22 +15,20 @@ import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { generateToRecord, createGetter, createSetter2, generateGetOrSetCall, generateThisBacking, - StateManagementTypes, - collectStateManagementTypeSource, collectStateManagementTypeImport, hasDecorator, - DecoratorNames, PropertyCache, } from './utils'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; export class PropTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { @@ -116,7 +114,6 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon ), ]; factory.judgeIfAddWatchFunc(args, this.property); - collectStateManagementTypeSource(StateManagementTypes.PROP_DECORATED); collectStateManagementTypeImport(StateManagementTypes.PROP_DECORATED); const right = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( diff --git a/arkui-plugins/ui-plugins/property-translators/provide.ts b/arkui-plugins/ui-plugins/property-translators/provide.ts index b084201c8..c765413cc 100644 --- a/arkui-plugins/ui-plugins/property-translators/provide.ts +++ b/arkui-plugins/ui-plugins/property-translators/provide.ts @@ -15,22 +15,21 @@ import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { createGetter, generateToRecord, - StateManagementTypes, createSetter2, generateThisBacking, generateGetOrSetCall, getValueInProvideAnnotation, ProvideOptions, hasDecorator, - DecoratorNames, PropertyCache, } from './utils'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; export class ProvideTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts index b072d83e9..731b0cd8c 100644 --- a/arkui-plugins/ui-plugins/property-translators/state.ts +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -15,6 +15,9 @@ import * as arkts from '@koalaui/libarkts'; +import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { CustomComponentNames } from '../utils'; import { generateToRecord, createGetter, @@ -22,20 +25,12 @@ import { generateThisBacking, generateGetOrSetCall, hasDecorator, - DecoratorNames, - removeDecorator, - decoratorTypeMap, - StateManagementTypes, collectStateManagementTypeImport, - collectStateManagementTypeSource, PropertyCache, } from './utils'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { backingField, expectName } from '../../common/arkts-utils'; -import { CustomComponentNames } from '../utils'; import { factory } from './factory'; -import { factory as uiFactory } from '../ui-factory'; export class StateTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -107,7 +102,6 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo ); const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), binaryItem]; factory.judgeIfAddWatchFunc(args, this.property); - collectStateManagementTypeSource(StateManagementTypes.STATE_DECORATED); collectStateManagementTypeImport(StateManagementTypes.STATE_DECORATED); const right = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( diff --git a/arkui-plugins/ui-plugins/property-translators/storageProp.ts b/arkui-plugins/ui-plugins/property-translators/storageProp.ts index d4861e5b2..2f33c03ed 100644 --- a/arkui-plugins/ui-plugins/property-translators/storageProp.ts +++ b/arkui-plugins/ui-plugins/property-translators/storageProp.ts @@ -16,17 +16,15 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { - DecoratorNames, generateToRecord, createGetter, createSetter2, generateThisBacking, generateGetOrSetCall, - StateManagementTypes, - collectStateManagementTypeSource, collectStateManagementTypeImport, hasDecorator, PropertyCache, @@ -92,7 +90,6 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; factory.judgeIfAddWatchFunc(args, this.property); - collectStateManagementTypeSource(StateManagementTypes.STORAGE_PROP_DECORATED); collectStateManagementTypeImport(StateManagementTypes.STORAGE_PROP_DECORATED); const newClass = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( diff --git a/arkui-plugins/ui-plugins/property-translators/storagelink.ts b/arkui-plugins/ui-plugins/property-translators/storagelink.ts index dadb5b297..68f3f7865 100644 --- a/arkui-plugins/ui-plugins/property-translators/storagelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/storagelink.ts @@ -16,17 +16,15 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; +import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { - DecoratorNames, generateToRecord, createGetter, createSetter2, generateThisBacking, generateGetOrSetCall, - StateManagementTypes, - collectStateManagementTypeSource, collectStateManagementTypeImport, hasDecorator, PropertyCache, @@ -92,7 +90,6 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; factory.judgeIfAddWatchFunc(args, this.property); - collectStateManagementTypeSource(StateManagementTypes.STORAGE_LINK_DECORATED); collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_DECORATED); const newClass = arkts.factory.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index feeef959b..c7421e7c0 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -15,98 +15,22 @@ import * as arkts from '@koalaui/libarkts'; import { DeclarationCollector } from '../../common/declaration-collector'; -import { ImportCollector } from '../import-collector'; -import { ARKUI_COMPONENT_IMPORT_NAME, ARKUI_STATEMANAGEMENT_IMPORT_NAME } from '../../common/predefines'; +import { ImportCollector } from '../../common/import-collector'; +import { matchPrefix } from '../../common/arkts-utils'; import { - addMemoAnnotation, - findCanAddMemoFromParamExpression, - findCanAddMemoFromTypeAnnotation, - findImportSource, -} from '../utils'; - -export enum DecoratorNames { - STATE = 'State', - STORAGE_LINK = 'StorageLink', - STORAGE_PROP = 'StorageProp', - LINK = 'Link', - PROP = 'Prop', - PROVIDE = 'Provide', - CONSUME = 'Consume', - OBJECT_LINK = 'ObjectLink', - OBSERVED = 'Observed', - WATCH = 'Watch', - BUILDER_PARAM = 'BuilderParam', - BUILDER = 'Builder', - CUSTOM_DIALOG = 'CustomDialog', - LOCAL_STORAGE_PROP = 'LocalStorageProp', - LOCAL_STORAGE_LINK = 'LocalStorageLink', - REUSABLE = 'Reusable', - TRACK = 'Track', -} - -export enum DecoratorIntrinsicNames { - LINK = '__Link_intrinsic', -} - -export enum DecoratorDeclarationNames { - STMT_COMMON = 'arkui.stateManagement.common', - COMP_COMMON = 'arkui.component.common', - CUSTOM_COMP = 'arkui.component.customComponent', -} - -export enum StateManagementTypes { - STATE_DECORATED = 'StateDecoratedVariable', - LINK_DECORATED = 'LinkDecoratedVariable', - STORAGE_LINK_DECORATED = 'StorageLinkDecoratedVariable', - STORAGE_PROP_DECORATED = 'StoragePropDecoratedVariable', - DECORATED_V1 = 'DecoratedV1VariableBase', - PROP_DECORATED = 'PropDecoratedVariable', - MUTABLE_STATE = 'MutableState', - MUTABLE_STATE_META = 'MutableStateMeta', - SYNCED_PROPERTY = 'SyncedProperty', - PROVIDE_DECORATED = 'ProvideDecoratedVariable', - CONSUME_DECORATED = 'ConsumeDecoratedVariable', - OBJECT_LINK_DECORATED = 'ObjectLinkDecoratedVariable', - BACKING_VALUE = 'BackingValue', - SET_OBSERVATION_DEPTH = 'setObservationDepth', - OBSERVED_OBJECT = 'IObservedObject', - WATCH_ID_TYPE = 'WatchIdType', - SUBSCRIBED_WATCHES = 'SubscribedWatches', - STORAGE_LINK_STATE = 'StorageLinkState', - OBSERVABLE_PROXY = 'observableProxy', - PROP_STATE = 'propState', - INT_32 = 'int32', -} + ARKUI_IMPORT_PREFIX_NAMES, + DecoratorIntrinsicNames, + DecoratorNames, + DECORATOR_TYPE_MAP, + StateManagementTypes, +} from '../../common/predefines'; +import { addMemoAnnotation, findCanAddMemoFromParamExpression, findCanAddMemoFromTypeAnnotation } from '../utils'; export interface DecoratorInfo { annotation: arkts.AnnotationUsage; name: DecoratorNames; } -export const decoratorTypeMap = new Map([ - [DecoratorNames.STATE, StateManagementTypes.STATE_DECORATED], - [DecoratorNames.LINK, StateManagementTypes.DECORATED_V1], - [DecoratorNames.PROP, StateManagementTypes.PROP_DECORATED], - [DecoratorNames.STORAGE_LINK, StateManagementTypes.STORAGE_LINK_DECORATED], - [DecoratorNames.STORAGE_PROP, StateManagementTypes.STORAGE_PROP_DECORATED], - [DecoratorNames.LOCAL_STORAGE_PROP, StateManagementTypes.SYNCED_PROPERTY], - [DecoratorNames.LOCAL_STORAGE_LINK, StateManagementTypes.MUTABLE_STATE], - [DecoratorNames.OBJECT_LINK, StateManagementTypes.OBJECT_LINK_DECORATED], - [DecoratorNames.PROVIDE, StateManagementTypes.PROVIDE_DECORATED], - [DecoratorNames.CONSUME, StateManagementTypes.CONSUME_DECORATED], -]); - -export function isFromDecoratorDeclaration(value: any): value is DecoratorDeclarationNames { - return Object.values(DecoratorDeclarationNames).includes(value); -} - -export function getImportSourceFromDeclarationName(name: DecoratorDeclarationNames): string { - if (name === DecoratorDeclarationNames.STMT_COMMON) { - return ARKUI_STATEMANAGEMENT_IMPORT_NAME; - } - return ARKUI_COMPONENT_IMPORT_NAME; -} - export function isDecoratorIntrinsicAnnotation( anno: arkts.AnnotationUsage, decoratorName: DecoratorIntrinsicNames @@ -128,10 +52,9 @@ export function isDecoratorAnnotation( return false; } const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; - if (!isFromDecoratorDeclaration(moduleName)) { + if (!moduleName || !matchPrefix(ARKUI_IMPORT_PREFIX_NAMES, moduleName)) { return false; } - ImportCollector.getInstance().collectSource(decoratorName, getImportSourceFromDeclarationName(moduleName)); DeclarationCollector.getInstance().collect(decl); } return true; @@ -230,7 +153,7 @@ export function findDecoratorInfos( export function getStateManagementType(decoratorInfo: DecoratorInfo): StateManagementTypes { const decoratorName = decoratorInfo.name; - const typeName = decoratorTypeMap.get(decoratorName); + const typeName = DECORATOR_TYPE_MAP.get(decoratorName); if (!!typeName) { return typeName; } @@ -241,11 +164,6 @@ export function collectStateManagementTypeImport(type: StateManagementTypes): vo ImportCollector.getInstance().collectImport(type); } -export function collectStateManagementTypeSource(type: StateManagementTypes): void { - const source = findImportSource(type); - ImportCollector.getInstance().collectSource(type, source); -} - export function createGetter( name: string, type: arkts.TypeNode | undefined, @@ -533,4 +451,4 @@ export class PropertyCache { const newToRecordBody = [...toRecordBody, ...toRecord]; this._cache.set(name, { ...this._cache.get(name), toRecordBody: newToRecordBody }); } -} \ No newline at end of file +} diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index d5f3dadff..f3f39c246 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -18,8 +18,6 @@ import { BuilderLambdaNames, addMemoAnnotation, CustomComponentNames, - Dollars, - findImportSource, getCustomComponentOptionsName, getGettersFromClassDecl, getTypeNameFromTypeParameter, @@ -38,20 +36,17 @@ import { PropertyTranslator, } from '../property-translators'; import { CustomComponentScopeInfo, isEtsGlobalClass, isKnownMethodDefinition } from './utils'; +import { collectStateManagementTypeImport, hasDecorator, PropertyCache } from '../property-translators/utils'; +import { ProjectConfig } from '../../common/plugin-context'; +import { DeclarationCollector } from '../../common/declaration-collector'; +import { ImportCollector } from '../../common/import-collector'; import { - collectStateManagementTypeImport, - collectStateManagementTypeSource, - DecoratorDeclarationNames, + ARKUI_COMPONENT_COMMON_SOURCE_NAME, DecoratorNames, - hasDecorator, - PropertyCache, - removeDecorator, + Dollars, StateManagementTypes, -} from '../property-translators/utils'; -import { ProjectConfig } from '../../common/plugin-context'; -import { DeclarationCollector } from '../../common/declaration-collector'; -import { ObservedTrackTranslator } from '../../ui-plugins/property-translators/observedTrack'; -import { ImportCollector } from '../../ui-plugins/import-collector'; +} from '../../common/predefines'; +import { ObservedTrackTranslator } from '../property-translators/observedTrack'; export class factory { /* @@ -115,8 +110,6 @@ export class factory { ): arkts.CallExpression { const transformedKey: string = key.name === Dollars.DOLLAR_RESOURCE ? Dollars.TRANSFORM_DOLLAR_RESOURCE : Dollars.TRANSFORM_DOLLAR_RAWFILE; - const source = findImportSource(transformedKey); - ImportCollector.getInstance().collectSource(transformedKey, source); ImportCollector.getInstance().collectImport(transformedKey); return arkts.factory.updateCallExpression( resourceNode, @@ -460,12 +453,9 @@ export class factory { resourceNode: arkts.CallExpression, projectConfig: ProjectConfig | undefined ): arkts.CallExpression { - let decl: arkts.AstNode | undefined; - if (!arkts.isIdentifier(resourceNode.expression) || !(decl = arkts.getDecl(resourceNode.expression))) { + if (!arkts.isIdentifier(resourceNode.expression)) { return resourceNode; } - DeclarationCollector.getInstance().collect(decl); - const newArgs: arkts.AstNode[] = [ arkts.factory.create1StringLiteral(projectConfig?.bundleName ? projectConfig.bundleName : ''), arkts.factory.create1StringLiteral(projectConfig?.moduleName ? projectConfig.moduleName : ''), @@ -484,7 +474,7 @@ export class factory { if (!node.id || !node.body) { return node; } - if (externalSourceName === DecoratorDeclarationNames.COMP_COMMON && node.id.name === 'UICommonMethod') { + if (externalSourceName === ARKUI_COMPONENT_COMMON_SOURCE_NAME && node.id.name === 'UICommonMethod') { return factory.modifyExternalComponentCommon(node); } if (isCustomComponentInterface(node)) { @@ -567,7 +557,6 @@ export class factory { node.modifiers, arkts.classDefinitionFlags(node) ); - collectStateManagementTypeSource(StateManagementTypes.OBSERVED_OBJECT); collectStateManagementTypeImport(StateManagementTypes.OBSERVED_OBJECT); return updateClassDef; } @@ -612,10 +601,8 @@ export class factory { ): arkts.AstNode[] { const watchMembers: arkts.AstNode[] = propertyFactory.createWatchMembers(); const permissibleAddRefDepth: arkts.ClassProperty = factory.createPermissibleAddRefDepthInObservedClass(); - collectStateManagementTypeSource(StateManagementTypes.INT_32); collectStateManagementTypeImport(StateManagementTypes.INT_32); const meta: arkts.ClassProperty = factory.createMutableStateMetaInObservedClass(); - collectStateManagementTypeSource(StateManagementTypes.MUTABLE_STATE_META); collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); const getters: arkts.MethodDefinition[] = getGettersFromClassDecl(definition); const classScopeInfo: ClassScopeInfo = { diff --git a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts index 920ce8270..05b470a09 100644 --- a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts +++ b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts @@ -26,7 +26,8 @@ import { CustomComponentScopeInfo, findCanAddMemoFromArrowFunction, isResourceNo import { factory } from './factory'; import { isEntryWrapperClass } from '../entry-translators/utils'; import { factory as entryFactory } from '../entry-translators/factory'; -import { ImportCollector } from '../import-collector'; +import { ImportCollector } from '../../common/import-collector'; +import { DeclarationCollector } from '../../common/declaration-collector'; import { PropertyCache } from '../property-translators/utils'; export class StructTransformer extends AbstractVisitor { @@ -44,6 +45,7 @@ export class StructTransformer extends AbstractVisitor { this.scope = { customComponents: [] }; PropertyCache.getInstance().reset(); ImportCollector.getInstance().reset(); + DeclarationCollector.getInstance().reset(); } enter(node: arkts.AstNode): void { @@ -58,7 +60,6 @@ export class StructTransformer extends AbstractVisitor { const scopeInfo = this.scope.customComponents.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; - scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; this.scope.customComponents.push(scopeInfo); } } diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts index a8b056534..7c68e9429 100644 --- a/arkui-plugins/ui-plugins/struct-translators/utils.ts +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -14,9 +14,11 @@ */ import * as arkts from '@koalaui/libarkts'; -import { CustomComponentInfo, Dollars, isMemoAnnotation, MemoNames } from '../utils'; -import { CustomComponentNames } from '../utils'; -import { DecoratorNames, isDecoratorAnnotation } from '../property-translators/utils'; +import { CustomComponentInfo, isMemoAnnotation, MemoNames } from '../utils'; +import { isDecoratorAnnotation } from '../property-translators/utils'; +import { matchPrefix } from '../../common/arkts-utils'; +import { ARKUI_IMPORT_PREFIX_NAMES, DecoratorNames, Dollars } from '../../common/predefines'; +import { DeclarationCollector } from '../../common/declaration-collector'; export type ScopeInfoCollection = { customComponents: CustomComponentScopeInfo[]; @@ -61,11 +63,27 @@ export function isEtsGlobalClass(node: arkts.ClassDeclaration): boolean { * * @param node call expression node */ -export function isResourceNode(node: arkts.CallExpression): boolean { - return ( - arkts.isIdentifier(node.expression) && - (node.expression.name === Dollars.DOLLAR_RESOURCE || node.expression.name === Dollars.DOLLAR_RAWFILE) - ); +export function isResourceNode(node: arkts.CallExpression, ignoreDecl: boolean = false): boolean { + if ( + !( + arkts.isIdentifier(node.expression) && + (node.expression.name === Dollars.DOLLAR_RESOURCE || node.expression.name === Dollars.DOLLAR_RAWFILE) + ) + ) { + return false; + } + if (!ignoreDecl) { + const decl = arkts.getDecl(node.expression); + if (!decl) { + return false; + } + const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; + if (!moduleName || !matchPrefix(ARKUI_IMPORT_PREFIX_NAMES, moduleName)) { + return false; + } + DeclarationCollector.getInstance().collect(decl); + } + return true; } export function isMemoCall(node: arkts.AstNode): node is arkts.CallExpression { diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index 26281073f..c5f735bf9 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -22,8 +22,9 @@ import { hasNullOrUndefinedType, hasPropertyInAnnotation, } from './utils'; -import { PartialExcept, PartialNested, PartialNestedExcept, PickNested } from '../common/safe-types'; -import { DecoratorNames, needDefiniteOrOptionalModifier } from './property-translators/utils'; +import { PartialExcept, PartialNested, PartialNestedExcept } from '../common/safe-types'; +import { DecoratorNames } from '../common/predefines'; +import { needDefiniteOrOptionalModifier } from './property-translators/utils'; export interface ScriptFunctionConfiguration { key: arkts.Identifier | undefined; @@ -181,27 +182,6 @@ export class factory { ); } - /** - * create and insert `import { as } from ` to the top of script's statements. - */ - static createAndInsertImportDeclaration( - source: arkts.StringLiteral, - imported: arkts.Identifier, - local: arkts.Identifier, - importKind: arkts.Es2pandaImportKinds, - program: arkts.Program - ): void { - const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( - source, - [arkts.factory.createImportSpecifier(imported, local)], - importKind, - program, - arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE - ); - arkts.importDeclarationInsert(importDecl, program); - return; - } - /** * create `import { as } ...`. */ diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index f5870ac80..d23949753 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -14,24 +14,19 @@ */ import * as arkts from '@koalaui/libarkts'; -import { annotation } from '../common/arkts-utils'; -import { ImportCollector } from './import-collector'; -import { ARKUI_STATEMANAGEMENT_IMPORT_NAME, IMPORT_SOURCE_MAP_V2 } from '../common/predefines'; +import { annotation, matchPrefix } from '../common/arkts-utils'; +import { ARKUI_IMPORT_PREFIX_NAMES, MEMO_IMPORT_SOURCE_NAME, StructDecoratorNames } from '../common/predefines'; import { DeclarationCollector } from '../common/declaration-collector'; +import { ImportCollector } from '../common/import-collector'; export enum CustomComponentNames { - ENTRY_ANNOTATION = 'Entry', - COMPONENT_ANNOTATION = 'Component', - RESUABLE_ANNOTATION = 'Reusable', COMPONENT_BUILD_ORI = 'build', COMPONENT_CONSTRUCTOR_ORI = 'constructor', - COMPONENT_DEFAULT_IMPORT = 'arkui.component.customComponent', COMPONENT_CLASS_NAME = 'CustomComponent', COMPONENT_INTERFACE_PREFIX = '__Options_', COMPONENT_INITIALIZE_STRUCT = '__initializeStruct', COMPONENT_UPDATE_STRUCT = '__updateStruct', COMPONENT_BUILD = '_build', - REUSABLE_COMPONENT_REBIND_STATE = '__rebindStates', COMPONENT_INITIALIZERS_NAME = 'initializers', BUILDCOMPATIBLENODE = '_buildCompatibleNode', OPTIONS = 'options', @@ -49,23 +44,23 @@ export enum BuilderLambdaNames { ANIMATION_STOP = 'animationStop', } -export enum Dollars { - DOLLAR_RESOURCE = '$r', - DOLLAR_RAWFILE = '$rawfile', - DOLLAR_DOLLAR = '$$', - TRANSFORM_DOLLAR_RESOURCE = '_r', - TRANSFORM_DOLLAR_RAWFILE = '_rawfile', -} - export enum MemoNames { MEMO = 'memo', } // IMPORT -export function findImportSource(importName: string): string { - const source = IMPORT_SOURCE_MAP_V2.get(importName); +export function findImportSourceByName(importName: string): string { + const source = DeclarationCollector.getInstance().findExternalSourceFromName(importName); + if (!source) { + throw new Error(`cannot find import source by name: "${importName}".`); + } + return source; +} + +export function findImportSourceByNode(declNode: arkts.AstNode): string { + const source = DeclarationCollector.getInstance().findExternalSourceFromNode(declNode); if (!source) { - throw new Error(`cannot find "${importName}" in the import source map.`); + throw new Error(`cannot find import source by peer.`); } return source; } @@ -151,7 +146,7 @@ export type CustomComponentAnontations = { export function isCustomComponentAnnotation( anno: arkts.AnnotationUsage, - decoratorName: CustomComponentNames, + decoratorName: StructDecoratorNames, ignoreDecl?: boolean ): boolean { if (!(!!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === decoratorName)) { @@ -163,7 +158,7 @@ export function isCustomComponentAnnotation( return false; } const moduleName: string = arkts.getProgramFromAstNode(decl).moduleName; - if (!moduleName) { + if (!moduleName || !matchPrefix(ARKUI_IMPORT_PREFIX_NAMES, moduleName)) { return false; } DeclarationCollector.getInstance().collect(decl); @@ -189,17 +184,9 @@ export function collectCustomComponentScopeInfo( if (!isCustomComponentClassDecl) { let isCustomComponent: boolean = false; for (const anno of definition.annotations) { - const isComponent = isCustomComponentAnnotation( - anno, - CustomComponentNames.COMPONENT_ANNOTATION, - shouldIgnoreDecl - ); - const isEntry = isCustomComponentAnnotation(anno, CustomComponentNames.ENTRY_ANNOTATION, shouldIgnoreDecl); - const isReusable = isCustomComponentAnnotation( - anno, - CustomComponentNames.RESUABLE_ANNOTATION, - shouldIgnoreDecl - ); + const isComponent = isCustomComponentAnnotation(anno, StructDecoratorNames.COMPONENT, shouldIgnoreDecl); + const isEntry = isCustomComponentAnnotation(anno, StructDecoratorNames.ENTRY, shouldIgnoreDecl); + const isReusable = isCustomComponentAnnotation(anno, StructDecoratorNames.RESUABLE, shouldIgnoreDecl); isCustomComponent ||= isComponent; annotations = { ...annotations, @@ -242,7 +229,7 @@ export function isCustomComponentClass(node: arkts.ClassDeclaration, scopeInfo: export function isCustomComponentInterface(node: arkts.TSInterfaceDeclaration): boolean { const checkPrefix = !!node.id?.name.startsWith(CustomComponentNames.COMPONENT_INTERFACE_PREFIX); const checkComponent = node.annotations.some((anno) => - isCustomComponentAnnotation(anno, CustomComponentNames.COMPONENT_ANNOTATION) + isCustomComponentAnnotation(anno, StructDecoratorNames.COMPONENT) ); return checkPrefix && checkComponent; } @@ -270,9 +257,7 @@ export function collectMemoAnnotationImport(memoName: MemoNames = MemoNames.MEMO } export function collectMemoAnnotationSource(memoName: MemoNames = MemoNames.MEMO): void { - if (memoName === MemoNames.MEMO) { - ImportCollector.getInstance().collectSource(memoName, 'arkui.stateManagement.runtime'); - } + ImportCollector.getInstance().collectSource(memoName, MEMO_IMPORT_SOURCE_NAME); } export function findCanAddMemoFromTypeAnnotation( -- Gitee From e383f00f8c1a07ebff720440467c446c8def9209 Mon Sep 17 00:00:00 2001 From: wangweiyuan Date: Thu, 29 May 2025 17:42:44 +0800 Subject: [PATCH 107/123] add ui-syntax-plugins 6/22 Signed-off-by: wangweiyuan --- .../componentV2-state-usage-validation.ts | 365 ++++++++++++++++-- .../rules/decorators-in-ui-component-only.ts | 126 ++++-- .../rules/no-child-in-button.ts | 4 +- .../rules/no-same-as-built-in-attribute.ts | 20 +- .../observed-heritage-compatible-check.ts | 49 ++- .../rules/observed-observedV2-check.ts | 8 +- 6 files changed, 478 insertions(+), 94 deletions(-) diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts index b60587aee..36abf5792 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts @@ -14,9 +14,12 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getClassPropertyAnnotationNames, PresetDecorators, getAnnotationUsage } from '../utils'; +import { + getClassPropertyAnnotationNames, PresetDecorators, getAnnotationUsage, getClassPropertyName, getIdentifierName +} from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +const builtInDecorators = [PresetDecorators.LOCAL, PresetDecorators.PARAM, PresetDecorators.EVENT]; // Helper functions for rules const hasisComponentV2 = (node: arkts.StructDeclaration): boolean => !!getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); @@ -25,12 +28,13 @@ const hasComponent = (node: arkts.StructDeclaration): boolean => !!getAnnotation PresetDecorators.COMPONENT_V1); function checkMultipleBuiltInDecorators(context: UISyntaxRuleContext, member: arkts.ClassProperty, propertyDecorators: string[]): void { - const builtInDecorators = [PresetDecorators.LOCAL, PresetDecorators.PARAM, PresetDecorators.EVENT]; const appliedBuiltInDecorators = propertyDecorators.filter(d => builtInDecorators.includes(d)); if (appliedBuiltInDecorators.length > 1) { member.annotations?.forEach(annotation => { - const annotationsName = annotation.expr?.dumpSrc(); - reportMultipleBuiltInDecoratorsError(context, annotation, annotationsName, builtInDecorators); + if (annotation.expr && arkts.isIdentifier(annotation.expr)) { + const annotationsName = annotation.expr.name; + reportMultipleBuiltInDecoratorsError(context, annotation, annotationsName, builtInDecorators); + } }); } }; @@ -42,8 +46,8 @@ function reportMultipleBuiltInDecoratorsError(context: UISyntaxRuleContext, anno node: annotation, message: rule.messages.multipleBuiltInDecorators, fix: (annotation) => { - const startPosition = arkts.getStartPosition(annotation); - const endPosition = arkts.getEndPosition(annotation); + const startPosition = annotation.startPosition; + const endPosition = annotation.endPosition; return { range: [startPosition, endPosition], code: '', @@ -55,11 +59,12 @@ function reportMultipleBuiltInDecoratorsError(context: UISyntaxRuleContext, anno function checkDecoratorOnlyInisComponentV2(context: UISyntaxRuleContext, member: arkts.ClassProperty, node: arkts.StructDeclaration, hasisComponentV2: boolean, hasComponent: boolean): void { - const builtInDecorators = [PresetDecorators.LOCAL, PresetDecorators.PARAM, PresetDecorators.EVENT]; member.annotations?.forEach(annotation => { - const annotationsName = annotation.expr?.dumpSrc(); - if (annotationsName && builtInDecorators.includes(annotationsName) && !hasisComponentV2 && !hasComponent) { - reportDecoratorOnlyInisComponentV2Error(context, annotation, annotationsName, node); + if (annotation.expr && arkts.isIdentifier(annotation.expr)) { + const annotationsName = annotation.expr?.name; + if (annotationsName && builtInDecorators.includes(annotationsName) && !hasisComponentV2 && !hasComponent) { + reportDecoratorOnlyInisComponentV2Error(context, annotation, annotationsName, node); + } } }); }; @@ -71,7 +76,7 @@ function reportDecoratorOnlyInisComponentV2Error(context: UISyntaxRuleContext, a message: rule.messages.decoratorOnlyInisComponentV2, data: { annotationsName }, fix: (annotation) => { - const startPosition = arkts.getStartPosition(node); + const startPosition = node.definition.startPosition; return { range: [startPosition, startPosition], code: `@${PresetDecorators.COMPONENT_V2}\n`, @@ -89,7 +94,7 @@ function checkParamRequiresRequire(context: UISyntaxRuleContext, member: arkts.C node: memberKey, message: rule.messages.paramRequiresRequire, fix: (memberKey) => { - const startPosition = arkts.getStartPosition(memberKey); + const startPosition = memberKey.startPosition; return { range: [startPosition, startPosition], code: `@${PresetDecorators.REQUIRE} `, @@ -100,17 +105,17 @@ function checkParamRequiresRequire(context: UISyntaxRuleContext, member: arkts.C }; function checkRequireOnlyWithParam(context: UISyntaxRuleContext, member: arkts.ClassProperty, - propertyDecorators: string[]): void { + propertyDecorators: string[], isComponentV2: boolean): void { const requireDecorator = member.annotations?.find(annotation => - annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.REQUIRE + annotation.expr && arkts.isIdentifier(annotation.expr) && annotation.expr.name === PresetDecorators.REQUIRE ); - if (requireDecorator && !propertyDecorators.includes(PresetDecorators.PARAM)) { + if (isComponentV2 && requireDecorator && !propertyDecorators.includes(PresetDecorators.PARAM)) { context.report({ node: requireDecorator, message: rule.messages.requireOnlyWithParam, fix: (requireDecorator) => { - const startPosition = arkts.getStartPosition(requireDecorator); - const endPosition = arkts.getEndPosition(requireDecorator); + const startPosition = requireDecorator.startPosition; + const endPosition = requireDecorator.endPosition; return { range: [startPosition, endPosition], code: '', @@ -120,6 +125,138 @@ function checkRequireOnlyWithParam(context: UISyntaxRuleContext, member: arkts.C } }; +function checkuseStateDecoratorsWithProperty(context: UISyntaxRuleContext, method: arkts.MethodDefinition): void { + method.scriptFunction.annotations?.forEach(annotation => { + if (annotation.expr && arkts.isIdentifier(annotation.expr) && builtInDecorators.includes(annotation.expr.name)) { + const annotationName = annotation.expr.name; + reportInvalidDecoratorOnMethod(context, annotation, annotationName); + } + }); +} + +function reportInvalidDecoratorOnMethod(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage, + annotationName: string): void { + context.report({ + node: annotation, + message: rule.messages.useStateDecoratorsWithProperty, + data: { annotationName }, + fix: (annotation) => { + const startPosition = annotation.startPosition; + const endPosition = annotation.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +function checkMustInitialize( + node: arkts.AstNode, + context: UISyntaxRuleContext, + mustInitMap: Map> +): void { + if (!arkts.isIdentifier(node)) { + return; + } + const structName: string = getIdentifierName(node); + if (!mustInitMap.has(structName)) { + return; + } + const parentNode: arkts.AstNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + } + // Get all the properties of a record via StructName + const mustInitName: Map = mustInitMap.get(structName)!; + parentNode.arguments?.forEach((member) => { + const childkeyNameArray: string[] = getChildKeyNameArray(member); + mustInitName.forEach((value, key) => { + // If an attribute that must be initialized is not initialized, an error is reported + if (!childkeyNameArray.includes(key)) { + context.report({ + node: parentNode, + message: rule.messages.paramNeedInit, + data: { + name: key, + }, + }); + } + }); + }); +} + +function getChildKeyNameArray(member: arkts.AstNode): string[] { + const childkeyNameArray: string[] = []; + member.getChildren().forEach((property) => { + if (!arkts.isProperty(property) || !property.key || !arkts.isIdentifier(property.key)) { + return; + } + const childkeyName = property.key.name; + if (childkeyName !== '') { + childkeyNameArray.push(childkeyName); + } + }); + return childkeyNameArray; +} + +function initMap(node: arkts.AstNode, mustInitMap: Map>, mustInitArray: string[][], +): void { + if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + return; + } + node.getChildren().forEach((member) => { + if (!(arkts.isStructDeclaration(member) || + (arkts.isClassDeclaration(member) && !!member.definition && + arkts.classDefinitionIsFromStructConst(member.definition)) + )) { + return; + } + const structName: string = member.definition!.ident?.name ?? ''; + if (structName === '') { + return; + } + member.definition?.body.forEach((item) => { + checkPropertyByAnnotations(item, structName, mustInitMap, mustInitArray); + }); + }); +} + +function checkPropertyByAnnotations( + item: arkts.AstNode, + structName: string, + mustInitMap: Map>, + mustInitArray: string[][] +): void { + if (!arkts.isClassProperty(item) || !item.key || !arkts.isIdentifier(item.key)) { + return; + } + const propertyName: string = item.key.name; + if (item.annotations.length === 0 || propertyName === '') { + return; + } + const annotationArray: string[] = getClassPropertyAnnotationNames(item); + // If the member variable is decorated, it is added to the corresponding map + mustInitArray.forEach(arr => { + if (arr.every(annotation => annotationArray.includes(annotation))) { + const annotationName: string = arr[0]; + addProperty(mustInitMap, structName, propertyName, annotationName); + } + }); +} + +// Define a function to add property data to the property map +function addProperty(propertyMap: Map>, structName: string, + propertyName: string, annotationName: string): void { + if (!propertyMap.has(structName)) { + propertyMap.set(structName, new Map()); + } + const structProperties = propertyMap.get(structName); + if (structProperties) { + structProperties.set(propertyName, annotationName); + } +} + function validateClassPropertyDecorators(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { const isComponentV2 = hasisComponentV2(node); const isComponent = hasComponent(node); @@ -128,7 +265,6 @@ function validateClassPropertyDecorators(context: UISyntaxRuleContext, node: ark return; } const propertyDecorators = getClassPropertyAnnotationNames(member); - // Rule 1: Multiple built-in decorators checkMultipleBuiltInDecorators(context, member, propertyDecorators); @@ -139,23 +275,204 @@ function validateClassPropertyDecorators(context: UISyntaxRuleContext, node: ark checkParamRequiresRequire(context, member, propertyDecorators); // Rule 4: @Require must be used together with @Param - checkRequireOnlyWithParam(context, member, propertyDecorators); + checkRequireOnlyWithParam(context, member, propertyDecorators, isComponentV2); + }); +} + +function checkDecorator(annoArray: readonly arkts.AnnotationUsage[], decorator: string): boolean { + let flag = false; + annoArray.forEach((anno) => { + if (!anno.expr) { + return; + } + const annoName = getIdentifierName(anno.expr); + if (annoName === decorator) { + flag = true; + } }); + return flag; +} + +// Define a function to add property data to the property map +function addPropertyMap( + structName: string, + propertyName: string, + annotationName: string, + propertyMap: Map> +): void { + if (!propertyMap.has(structName)) { + propertyMap.set(structName, new Map()); + } + const structProperties = propertyMap.get(structName); + if (structProperties) { + structProperties.set(propertyName, annotationName); + } +} + +// Iterate through the incoming componentv2 node to see if there are any state variables for decorator decorations +function initComponentV2PropertyMap( + node: arkts.AstNode, + componentV2PropertyMap: Map> +): void { + if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + return; + } + node.getChildren().forEach((member) => { + if (!arkts.isStructDeclaration(member) || !member.definition.ident || + !checkDecorator(member?.definition.annotations, PresetDecorators.COMPONENT_V2)) { + return; + } + let structName: string = member.definition.ident?.name ?? ''; + member.definition?.body?.forEach((item) => { + processClassPropertyAnnotations(item, structName, componentV2PropertyMap); + }); + }); +} + +function processClassPropertyAnnotations( + item: arkts.AstNode, + structName: string, + componentV2PropertyMap: Map> +): void { + if (!arkts.isClassProperty(item) || !item.key) { + return; + } + let propertyName: string = getIdentifierName(item.key); + // If there is no decorator, it is a regular type + if (item.annotations.length === 0) { + let annotationName: string = PresetDecorators.REGULAR; + addPropertyMap(structName, propertyName, annotationName, componentV2PropertyMap); + } + item.annotations.forEach((annotation) => { + if (!annotation.expr) { + return; + } + let annotationName: string = getIdentifierName(annotation.expr); + if (annotationName === PresetDecorators.LOCAL) { + addPropertyMap(structName, propertyName, annotationName, componentV2PropertyMap); + } + }); +} + + +function checkInitializeRule( + node: arkts.AstNode, + context: UISyntaxRuleContext, + componentV2PropertyMap: Map>, +): void { + if (!arkts.isIdentifier(node) || !componentV2PropertyMap.has(getIdentifierName(node))) { + return; + } + let structName: string = getIdentifierName(node); + let parentNode: arkts.AstNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + } + let structNode = node.parent; + while (!arkts.isStructDeclaration(structNode)) { + if (!structNode.parent) { + return; + } + structNode = structNode.parent; + } + let parentPropertyMap: Map = new Map(); + structNode.definition.body.forEach((property) => { + if (!arkts.isClassProperty(property)) { + return; + } + let propertyArray: string[] = []; + property.annotations.forEach((annotation) => { + if (!annotation.expr || !arkts.isIdentifier(annotation.expr)) { + return; + } + propertyArray.push(annotation.expr.name); + }); + parentPropertyMap.set(getClassPropertyName(property), propertyArray); + }); + // Gets all the properties recorded by the struct + const childPropertyName: Map = componentV2PropertyMap.get(structName)!; + parentNode.arguments.forEach((argument) => { + if (!arkts.isObjectExpression(argument)) { + return; + } + argument.getChildren().forEach((property) => { + if (!arkts.isProperty(property) || !property.key) { + return; + } + const childkeyName = getIdentifierName(property.key); + if (!childPropertyName.has(childkeyName)) { + return; + } + reportLocalNeedInit(childPropertyName, childkeyName, context, property, structName); + }); + }); +} + +function reportLocalNeedInit(childPropertyName: Map, childkeyName: string, context: UISyntaxRuleContext, + property: arkts.Property, structName: string): void { + if (childPropertyName.get(childkeyName) === PresetDecorators.LOCAL) { + context.report({ + node: property, + message: rule.messages.localNeedNoInit, + data: { + decoratorName: '@' + childPropertyName.get(childkeyName)!, + key: childkeyName, + componentName: structName, + }, + fix: (property) => { + return { + range: [property.startPosition, property.endPosition], + code: '', + }; + } + }); + } + if (childPropertyName.get(childkeyName) === PresetDecorators.REGULAR) { + context.report({ + node: property, + message: rule.messages.localNeedNoInit, + data: { + decoratorName: PresetDecorators.REGULAR, + key: childkeyName, + componentName: structName, + }, + fix: (property) => { + return { + range: [property.startPosition, property.endPosition], + code: '', + }; + } + }); + } } const rule: UISyntaxRule = { - name: 'iscomponentV2-state-usage-validation', + name: 'componentV2-state-usage-validation', messages: { multipleBuiltInDecorators: `The member property or method cannot be decorated by multiple built-in decorators.`, - decoratorOnlyInisComponentV2: `The '@{{annotationsName}}' decorator can only be used in a 'struct' decorated with '@isComponentV2'.`, - paramRequiresRequire: `When a variable decorated with @Param is not assigned a default value, it must also be decorated with @Require.`, - requireOnlyWithParam: `In a struct decorated with @isComponentV2, @Require can only be used with @Param. ` + decoratorOnlyInisComponentV2: `The '@{{annotationsName}}' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, + paramRequiresRequire: `When a variable decorated with '@Param' is not assigned a default value, it must also be decorated with '@Require'.`, + requireOnlyWithParam: `In a struct decorated with '@ComponentV2', '@Require' can only be used with @Param.`, + localNeedNoInit: `The '{{decoratorName}}' property '{{key}}' in the custom component '{{componentName}}' cannot be initialized here (forbidden to specify).`, + paramNeedInit: `Property '{{name}}' must be initialized through the component constructor.`, + useStateDecoratorsWithProperty: `'@{{annotationName}}' can only decorate member property.`, }, setup(context) { + let mustInitMap: Map> = new Map(); + const mustInitArray: string[][] = [[PresetDecorators.REQUIRE, PresetDecorators.PARAM]]; + let componentV2PropertyMap: Map> = new Map(); return { parsed: (node): void => { - + initComponentV2PropertyMap(node, componentV2PropertyMap); + checkInitializeRule(node, context, componentV2PropertyMap); + initMap(node, mustInitMap, mustInitArray); + // Rule 6: Property with require and Param must be initialized through the component constructor + checkMustInitialize(node, context, mustInitMap); + if (arkts.isMethodDefinition(node)) { + // Rule 7: Local, Param, Event decorators must be used with Property + checkuseStateDecoratorsWithProperty(context, node); + } if (!arkts.isStructDeclaration(node)) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts b/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts index b01e0d40a..fe7fb6ae0 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts @@ -17,56 +17,84 @@ import * as arkts from '@koalaui/libarkts'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; import { PresetDecorators } from '../utils/index'; -// Helper function to find the '@Component' decorator in a ClassDeclaration and report errors. -function findComponentDecorator(context: UISyntaxRuleContext, node: arkts.ClassDeclaration): void { - const componentDecorator = node.definition?.annotations?.find( - (annotation) => - annotation.expr && - arkts.isIdentifier(annotation.expr) && - annotation.expr.name === PresetDecorators.COMPONENT_V1 - ); - if (componentDecorator) { - reportDecoratorError(context, componentDecorator, rule.messages.invalidComponentDecorator); - } +// Constants for allowed decorators on struct and within struct using PresetDecorators +const DECORATORS_ALLOWED_ON_STRUCT = [ + PresetDecorators.COMPONENT_V1, + PresetDecorators.ENTRY, + PresetDecorators.PREVIEW, + PresetDecorators.CUSTOM_DIALOG, + PresetDecorators.REUSABLE_V2, +]; + +const DECORATORS_ALLOWED_IN_STRUCT = [ + PresetDecorators.STATE, + PresetDecorators.PROP, + PresetDecorators.LINK, + PresetDecorators.PROVIDE, + PresetDecorators.CONSUME, + PresetDecorators.OBJECT_LINK, + PresetDecorators.STORAGE_LINK, + PresetDecorators.STORAGE_PROP, + PresetDecorators.LOCAL_STORAGE_LINK, + PresetDecorators.LOCAL_STORAGE_PROP, + PresetDecorators.WATCH, + PresetDecorators.BUILDER_PARAM, +]; + +// Helper function to find the decorator in a ClassDeclaration and report errors. +function findInvalidDecorator(context: UISyntaxRuleContext, node: arkts.ClassDeclaration): void { + node.definition!.annotations?.forEach(annotation => { + if (annotation.expr && arkts.isIdentifier(annotation.expr) && + DECORATORS_ALLOWED_ON_STRUCT.includes(annotation.expr.name)) { + reportDecoratorError(context, annotation, rule.messages.invalidDecoratorOnStruct); + } + }); } -// Helper function to find the '@Prop' decorator in a MethodDefinition or ClassProperty. -const findPropDecorator = (node: arkts.MethodDefinition | arkts.ClassProperty): arkts.AnnotationUsage | undefined => { - const annotations = 'scriptFunction' in node ? node.scriptFunction.annotations : node.annotations; - return annotations?.find( - (annotation) => - annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.PROP - ); +// Rule 2: Check for 'decorator' on MethodDefinition +function checkinvalidDecoratorInStruct(context: UISyntaxRuleContext, node: arkts.MethodDefinition): void { + node.scriptFunction.annotations?.forEach(annotation => { + if (annotation.expr && arkts.isIdentifier(annotation.expr) && + DECORATORS_ALLOWED_IN_STRUCT.includes(annotation.expr.name)) { + reportDecoratorError(context, annotation, rule.messages.invalidDecoratorInStruct); + } + }); }; -// Rule 2: Check for '@Prop' on MethodDefinition -function checkPropOnMethod(context: UISyntaxRuleContext, node: arkts.MethodDefinition): void { - const propDecorator = findPropDecorator(node); - if (propDecorator) { - reportDecoratorError(context, propDecorator, rule.messages.propOnMethod); - } +// Rule 3: Check for 'decorator' on ClassProperty within a ClassDeclaration +function checkDecoratorOnClassProperty(context: UISyntaxRuleContext, node: arkts.ClassProperty, + currentNode: arkts.AstNode): void { + node.annotations?.forEach(annotation => { + if (annotation.expr && arkts.isIdentifier(annotation.expr) && + DECORATORS_ALLOWED_IN_STRUCT.includes(annotation.expr.name)) { + reportIfDecoratorInClassDeclaration(context, annotation, currentNode); + } + }); }; -// Rule 3: Check for '@Prop' on ClassProperty within a ClassDeclaration -function checkPropOnClassProperty(context: UISyntaxRuleContext, node: arkts.ClassProperty, currentNode: arkts.AstNode) - : void { - const propDecorator = findPropDecorator(node); +function reportIfDecoratorInClassDeclaration(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage, + currentNode: arkts.AstNode): void { while (arkts.nodeType(currentNode) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { currentNode = currentNode.parent; - if (propDecorator && arkts.isClassDeclaration(currentNode)) { - reportDecoratorError(context, propDecorator, rule.messages.propOnMethod); + if (annotation && arkts.isClassDeclaration(currentNode)) { + reportDecoratorError(context, annotation, rule.messages.invalidDecoratorInStruct); } } -}; +} -function reportDecoratorError(context: UISyntaxRuleContext, Decorator: arkts.AnnotationUsage, message: string +function reportDecoratorError(context: UISyntaxRuleContext, decorator: arkts.AnnotationUsage, message: string ): void { + if (!decorator.expr || !arkts.isIdentifier(decorator.expr)) { + return; + } + const decoratorName = decorator.expr.name; context.report({ - node: Decorator, + node: decorator, message: message, + data: { decoratorName }, fix: () => { - const startPosition = arkts.getStartPosition(Decorator); - const endPosition = arkts.getEndPosition(Decorator); + const startPosition = decorator.startPosition; + const endPosition = decorator.endPosition; return { range: [startPosition, endPosition], code: '', @@ -75,24 +103,40 @@ function reportDecoratorError(context: UISyntaxRuleContext, Decorator: arkts.Ann }); } +function checkDecoratorWithFunctionDeclaration(node: arkts.FunctionDeclaration, context: UISyntaxRuleContext): void { + node.annotations?.forEach(annotation => { + if (annotation.expr && arkts.isIdentifier(annotation.expr) && + DECORATORS_ALLOWED_ON_STRUCT.includes(annotation.expr.name)) { + reportDecoratorError(context, annotation, rule.messages.invalidDecoratorOnStruct); + } + if (annotation.expr && arkts.isIdentifier(annotation.expr) && + DECORATORS_ALLOWED_IN_STRUCT.includes(annotation.expr.name)) { + reportDecoratorError(context, annotation, rule.messages.invalidDecoratorInStruct); + } + }); +} + const rule: UISyntaxRule = { - name: 'no-prop-on-method', + name: 'decorators-in-ui-component-only', messages: { - invalidComponentDecorator: `'@Component' can decorate only custom components.`, - propOnMethod: `'@Prop' can decorate only member variables of custom components.`, + invalidDecoratorOnStruct: `The '@{{decoratorName}}' decorator can only be used with 'struct'.`, + invalidDecoratorInStruct: `'@{{decoratorName}}' can not decorate the method.`, }, setup(context) { return { parsed: (node: arkts.AstNode): void => { + if (arkts.isFunctionDeclaration(node)) { + checkDecoratorWithFunctionDeclaration(node, context); + } if (arkts.isClassDeclaration(node)) { - findComponentDecorator(context, node); + findInvalidDecorator(context, node); } if (arkts.isMethodDefinition(node)) { - checkPropOnMethod(context, node); + checkinvalidDecoratorInStruct(context, node); } let currentNode = node; if (arkts.isClassProperty(node)) { - checkPropOnClassProperty(context, node, currentNode); + checkDecoratorOnClassProperty(context, node, currentNode); } }, }; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts b/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts index 6cf999a27..e6a93e3d7 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts @@ -43,8 +43,8 @@ function reportNoChildInButtonError(parentNode: arkts.AstNode, context: UISyntax node: parentNode, message: rule.messages.noChildInButton, fix: (parentNode) => { - const startPosition = arkts.getStartPosition(siblings[2]); - const endPosition = arkts.getEndPosition(siblings[2]); + const startPosition = siblings[2].startPosition; + const endPosition = siblings[2].endPosition; return { range: [startPosition, endPosition], code: '', diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts b/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts index e61af0b56..7afe1f354 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts @@ -15,28 +15,34 @@ import * as arkts from '@koalaui/libarkts'; import { UISyntaxRule } from './ui-syntax-rule'; +import { isBuiltInAttribute } from '../utils'; const rule: UISyntaxRule = { name: 'no-same-as-built-in-attribute', messages: { - duplicateName: `The struct name '{{structName}}' should not have the same name as a built-in attribute.`, + duplicateName: `The struct '{{structName}}' cannot have the same name as the built-in attribute '{{builtInName}}'.`, }, setup(context) { - const builtInAttributes = ['fontColor', 'width', 'height', 'size', 'border', 'backgroundColor', 'margin', - 'padding']; return { parsed: (node): void => { if (!arkts.isStructDeclaration(node)) { return; } - const structName = node.definition.ident?.name ?? ' '; + if (!node.definition) { + return; + } + if (!arkts.isClassDefinition(node.definition)) { + return; + } const structIdent = node.definition.ident; + const structName = node.definition.ident?.name ?? ' '; // If the struct name matches any built-in attribute, report an error - if (builtInAttributes.includes(structName) && structIdent) { + if (structIdent && isBuiltInAttribute(context, structName)) { + const builtInName = structName; context.report({ node: structIdent, message: rule.messages.duplicateName, - data: { structName } + data: { structName, builtInName } }); } }, @@ -44,4 +50,4 @@ const rule: UISyntaxRule = { }, }; -export default rule; +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts b/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts index 95b605f2c..b32a86f73 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts @@ -15,7 +15,7 @@ import * as arkts from '@koalaui/libarkts'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -import { PresetDecorators } from '../utils/index'; +import { getIdentifierName, PresetDecorators } from '../utils/index'; function getObservedDecorator(node: arkts.AstNode, observedClasses: string[], observedV2Classes: string[]): void { for (const child of node.getChildren()) { @@ -57,30 +57,45 @@ function checkInheritanceCompatibility(context: UISyntaxRuleContext, node: arkts ); //Get the name of the superClass - const superClassName = node.definition?.super?.dumpSrc(); - if (!superClassName) { + if (!node.definition?.super) { return; } - // Verify that the inheritance relationship is compatible - if (observedV1Decorator && observedV2Classes.includes(superClassName)) { - context.report({ - node: observedV1Decorator, - message: rule.messages.incompatibleHeritageObservedToObservedV2, - }); - } - if (observedV2Decorator && observedClasses.includes(superClassName)) { - context.report({ - node: observedV2Decorator, - message: rule.messages.incompatibleHeritageObservedV2ToObserved, - }); + if (arkts.isETSTypeReference(node.definition?.super)) { + if (!node.definition.super.part) { + return; + } + if (!arkts.isETSTypeReferencePart(node.definition?.super.part)) { + return; + } + if (!node.definition?.super.part.name) { + return; + } + const superClassName = getIdentifierName(node.definition?.super.part.name); + + if (!superClassName) { + return; + } + // Verify that the inheritance relationship is compatible + if (observedV1Decorator && observedV2Classes.includes(superClassName)) { + context.report({ + node: observedV1Decorator, + message: rule.messages.incompatibleHeritageObservedToObservedV2, + }); + } + if (observedV2Decorator && observedClasses.includes(superClassName)) { + context.report({ + node: observedV2Decorator, + message: rule.messages.incompatibleHeritageObservedV2ToObserved, + }); + } } } const rule: UISyntaxRule = { name: 'observed-heritage-compatible-check', messages: { - incompatibleHeritageObservedToObservedV2: `The current class is decorated by '@Observed', it cannot inherit a class decorated by '@ObservedV2'.`, - incompatibleHeritageObservedV2ToObserved: `The current class is decorated by '@ObservedV2', it cannot inherit a class decorated by '@Observed'.`, + incompatibleHeritageObservedToObservedV2: `A class decorated by '@Observed' cannot inherit from a class decorated by '@ObservedV2'.`, + incompatibleHeritageObservedV2ToObserved: `A class decorated by '@ObservedV2' cannot inherit from a class decorated by '@Observed'.`, }, setup(context) { // Record the class name decorated with @Observed and @ObservedV2 diff --git a/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts b/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts index e02304b3c..808438ed0 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts @@ -29,9 +29,11 @@ const rule: UISyntaxRule = { return; } const hasObservedDecorator = node.definition?.annotations?.find(annotations => annotations.expr && - annotations.expr.dumpSrc() === PresetDecorators.OBSERVED_V1); + arkts.isIdentifier(annotations.expr) && + annotations.expr.name === PresetDecorators.OBSERVED_V1); const hasObservedV2Decorator = node.definition?.annotations?.find(annotations => annotations.expr && - annotations.expr.dumpSrc() === PresetDecorators.OBSERVED_V2); + arkts.isIdentifier(annotations.expr) && + annotations.expr.name === PresetDecorators.OBSERVED_V2); // If the current class is decorated by @Observed and @ObservedV2, an error is reported if (hasObservedDecorator && hasObservedV2Decorator) { context.report({ @@ -44,4 +46,4 @@ const rule: UISyntaxRule = { }, }; -export default rule; +export default rule; \ No newline at end of file -- Gitee From be0cfa20544b6d673778f15bfaa94288fef5c4e8 Mon Sep 17 00:00:00 2001 From: wuhailong Date: Tue, 3 Jun 2025 17:03:01 +0800 Subject: [PATCH 108/123] bugfix interop transform Issue: #ICCBDP Signed-off-by: wuhailong Change-Id: I605946a26c8b2d7ff515b389e95d13781bfd1619 --- compiler/src/process_arkts_evolution.ts | 52 +++++--- .../common/process_arkts_evolution.test.ts | 113 +++++++++--------- 2 files changed, 88 insertions(+), 77 deletions(-) diff --git a/compiler/src/process_arkts_evolution.ts b/compiler/src/process_arkts_evolution.ts index 63eb61e39..2b709cec7 100644 --- a/compiler/src/process_arkts_evolution.ts +++ b/compiler/src/process_arkts_evolution.ts @@ -275,10 +275,12 @@ function createObjectLiteralVisitor(context: ts.TransformationContext, typeCheck return ts.visitEachChild(node, visitor, context); } const isRecordType: boolean = contextualType.aliasSymbol?.escapedName === 'Record' && - (typeof ts.isStaticRecord === 'function' && ts.isStaticRecord(contextualType)); + (typeof typeChecker.isStaticRecord === 'function' && typeChecker.isStaticRecord(contextualType)); const finalType: ts.Type = unwrapType(node, contextualType); const decl : ts.Declaration = (finalType.symbol?.declarations || finalType.aliasSymbol?.declarations)?.[0]; + const scope: ts.Node = getScope(node); let className: string; + let tmpObjName: string; if (!isRecordType) { if (!decl || !isFromArkTSEvolutionModule(decl)) { return ts.visitEachChild(node, visitor, context); @@ -291,10 +293,10 @@ function createObjectLiteralVisitor(context: ts.TransformationContext, typeCheck if (ts.isClassDeclaration(decl) && !hasZeroArgConstructor(decl, className)) { return ts.visitEachChild(node, visitor, context); } + tmpObjName = getUniqueName(scope, 'tmpObj', scopeUsedNames); + declareGlobalTemp(tmpObjName); } - - const scope: ts.Node = getScope(node); - const tmpObjName: string = getUniqueName(scope, 'tmpObj', scopeUsedNames); + const fullName: string = buildFullClassName(decl, finalType, className, isRecordType); const getCtorExpr: ts.Expression = buildGetConstructorCall(fullName, isRecordType); let tmpClassName: string; @@ -305,15 +307,9 @@ function createObjectLiteralVisitor(context: ts.TransformationContext, typeCheck fullNameToTmpVar.set(fullName, tmpClassName); declareGlobalTemp(tmpClassName, getCtorExpr); } - declareGlobalTemp(tmpObjName); - - const assignments: ts.Expression[] = buildPropertyAssignments(node, tmpObjName, !isRecordType); - return ts.factory.createParenthesizedExpression(ts.factory.createCommaListExpression([ - ts.factory.createAssignment(ts.factory.createIdentifier(tmpObjName), - ts.factory.createNewExpression(ts.factory.createIdentifier(tmpClassName), undefined, [])), - ...assignments, - ts.factory.createIdentifier(tmpObjName) - ])); + + return ts.factory.createParenthesizedExpression( + ts.factory.createCommaListExpression(buildCommaExpressions(node, isRecordType, tmpObjName, tmpClassName))); }; } @@ -390,19 +386,18 @@ function hasZeroArgConstructor(decl: ts.ClassDeclaration, className: string): bo function buildFullClassName(decl: ts.Declaration, finalType: ts.Type, className: string, isRecordType: boolean): string { if (isRecordType) { - return 'Lescompat/Record'; + return 'Lescompat/Record;'; } const basePath: string = getArkTSEvoFileOHMUrl(finalType); return ts.isInterfaceDeclaration(decl) ? - `L${basePath}/${className}$ObjectLiteral` : - `L${basePath}/${className}`; + `L${basePath}/${basePath.split('/').join('$')}$${className}$ObjectLiteral;` : + `L${basePath}/${className};`; } function buildGetConstructorCall(fullName: string, isRecord: boolean): ts.Expression { return ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('globalThis'), 'gtest'), - isRecord ? 'etsVM.getInstance' : 'etsVM.getClass'), + ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('globalThis'), + isRecord ? 'Panda.getInstance' : 'Panda.getClass'), undefined, [ts.factory.createStringLiteral(fullName)] ); @@ -423,6 +418,25 @@ function buildPropertyAssignments(node: ts.ObjectLiteralExpression, tmpObjName: }).filter(Boolean) as ts.Expression[]; } +function buildCommaExpressions(node: ts.ObjectLiteralExpression, isRecordType: boolean, + tmpObjName: string, tmpClassName: string): ts.Expression[] { + const assignments: ts.Expression[] = + buildPropertyAssignments(node, isRecordType ? tmpClassName : tmpObjName, !isRecordType); + + if (isRecordType) { + return [...assignments, ts.factory.createIdentifier(tmpClassName)]; + } + + return [ + ts.factory.createAssignment( + ts.factory.createIdentifier(tmpObjName), + ts.factory.createNewExpression(ts.factory.createIdentifier(tmpClassName), undefined, []) + ), + ...assignments, + ts.factory.createIdentifier(tmpObjName) + ]; +} + function getArkTSEvoFileOHMUrl(contextualType: ts.Type): string { const decl: ts.Declaration = (contextualType.symbol?.declarations || contextualType.aliasSymbol?.declarations)?.[0]; if (!decl) { diff --git a/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts b/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts index 69cddf379..686228e5e 100644 --- a/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts +++ b/compiler/test/ark_compiler_ut/common/process_arkts_evolution.test.ts @@ -116,9 +116,8 @@ ArkTSRecordFunc({a: 1}); `; const IMPORT_ARKTS_EVO_RECORD_CODE_EXPECT: string = `import { ArkTSRecordFunc } from "arkTSEvo"; -let tmpRecord = globalThis.gtest.etsVM.getInstance("Lescompat/Record"); -let tmpObj; -ArkTSRecordFunc((tmpObj = new tmpRecord(), tmpObj["a"] = 1, tmpObj)); +let tmpRecord = globalThis.Panda.getInstance("Lescompat/Record;"); +ArkTSRecordFunc((tmpRecord["a"] = 1, tmpRecord)); `; const IMPORT_ARKTS_EVO_CLASS_CODE_1: string = `import { ArkTSClass } from "arkTSEvo"; @@ -126,8 +125,8 @@ let a: ArkTSClass = {a: 1}; `; const IMPORT_ARKTS_EVO_CLASS_CODE_1_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); let a: ArkTSClass = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); `; @@ -137,8 +136,8 @@ an = {a: 1}; `; const IMPORT_ARKTS_EVO_CLASS_CODE_2_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); let an = new ArkTSClass(); an = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); `; @@ -148,8 +147,8 @@ let aas = {a: 1} as ArkTSClass; `; const IMPORT_ARKTS_EVO_CLASS_CODE_3_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); let aas = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj) as ArkTSClass; `; @@ -160,8 +159,8 @@ class A { `; const IMPORT_ARKTS_EVO_CLASS_CODE_4_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); class A { a: ArkTSClass = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); } @@ -178,8 +177,8 @@ let aa = new AA({a: 1}) `; const IMPORT_ARKTS_EVO_CLASS_CODE_5_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); class AA { a: ArkTSClass; constructor(a: ArkTSClass) { @@ -197,8 +196,8 @@ let aaa: AAA = {a: {a: 1}} `; const IMPORT_ARKTS_EVO_CLASS_CODE_6_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); class AAA { a: ArkTSClass = new ArkTSClass(); } @@ -210,8 +209,8 @@ function foo(a: ArkTSClass = {a:1}) {} `; const IMPORT_ARKTS_EVO_CLASS_CODE_7_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); function foo(a: ArkTSClass = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)) { } `; @@ -221,8 +220,8 @@ bar({a: 1}) `; const IMPORT_ARKTS_EVO_CLASS_CODE_8_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); function bar(a: ArkTSClass) { } bar((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); `; @@ -232,8 +231,8 @@ let aaa: () => ArkTSClass = () => ({a: 1}) `; const IMPORT_ARKTS_EVO_CLASS_CODE_9_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); let aaa: () => ArkTSClass = () => ((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); `; @@ -244,8 +243,8 @@ function fooa(): ArkTSClass { `; const IMPORT_ARKTS_EVO_CLASS_CODE_10_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); function fooa(): ArkTSClass { return (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); } @@ -256,8 +255,8 @@ let a: ArkTSInterface = {a: 1}; `; const IMPORT_ARKTS_EVO_INTERFACE_CODE_1_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); let a: ArkTSInterface = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); `; @@ -266,8 +265,8 @@ let aas = {a: 1} as ArkTSInterface; `; const IMPORT_ARKTS_EVO_INTERFACE_CODE_2_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); let aas = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj) as ArkTSInterface; `; @@ -278,8 +277,8 @@ class A { `; const IMPORT_ARKTS_EVO_INTERFACE_CODE_3_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); class A { a: ArkTSInterface = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); } @@ -296,8 +295,8 @@ let aa = new AA({a: 1}) `; const IMPORT_ARKTS_EVO_INTERFACE_CODE_4_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); class AA { a: ArkTSInterface; constructor(a: ArkTSInterface) { @@ -312,8 +311,8 @@ function foo(a: ArkTSInterface = {a:1}) {} `; const IMPORT_ARKTS_EVO_INTERFACE_CODE_5_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); function foo(a: ArkTSInterface = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)) { } `; @@ -323,8 +322,8 @@ bar({a: 1}) `; const IMPORT_ARKTS_EVO_INTERFACE_CODE_6_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); function bar(a: ArkTSInterface) { } bar((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); `; @@ -334,8 +333,8 @@ let aaa: () => ArkTSInterface = () => ({a: 1}) `; const IMPORT_ARKTS_EVO_INTERFACE_CODE_7_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); let aaa: () => ArkTSInterface = () => ((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); `; @@ -346,8 +345,8 @@ function fooa(): ArkTSInterface { `; const IMPORT_ARKTS_EVO_INTERFACE_CODE_8_EXPECT: string = `import { ArkTSInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); function fooa(): ArkTSInterface { return (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); } @@ -362,10 +361,10 @@ ArkTSFuncInterface({a: 1}); `; const IMPORT_ARKTS_EVO_FUNCTION_CODE_EXPECT: string = `import { ArkTSFuncClass, ArkTSFuncInterface } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; -let tmpClass_1 = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSInterface$ObjectLiteral"); +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); let tmpObj_1; +let tmpClass_1 = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/arkTSEvo$src$main$ets$decl$ArkTSInterface$ObjectLiteral;"); ArkTSFuncClass((tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj)); ArkTSFuncInterface((tmpObj_1 = new tmpClass_1(), tmpObj_1.a = 1, tmpObj_1)); `; @@ -375,8 +374,8 @@ let a: ArkTSClass | undefined = {a: 1}; `; const UNION_NO_AMBIGUITY_CODE_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); let a: ArkTSClass | undefined = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); `; @@ -412,8 +411,8 @@ let a: (ArkTSClass) = {a: 1}; `; const PARENTHESIZED_CODE_EXPECT: string = `import { ArkTSClass } from "arkTSEvo"; -let tmpClass = globalThis.gtest.etsVM.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass"); let tmpObj; +let tmpClass = globalThis.Panda.getClass("LarkTSEvo/src/main/ets/decl/ArkTSClass;"); let a: (ArkTSClass) = (tmpObj = new tmpClass(), tmpObj.a = 1, tmpObj); `; @@ -581,7 +580,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-1: test mixCompile is false', function () { const sourceFile: ts.SourceFile = ts.createSourceFile('a.ts', 'let x = 1;', ts.ScriptTarget.ESNext); const program: ts.Program = ts.createProgram({ rootNames: ['a.ts'], options: {}, host: ts.createCompilerHost({}) }); - const result: ts.SourceFile = interopTransform(program, testFileName, false, false)()(sourceFile); + const result: ts.SourceFile = interopTransform(program, testFileName, false)()(sourceFile); expect(result === sourceFile).to.be.true; }); @@ -597,7 +596,7 @@ mocha.describe('process arkts evolution tests', function () { 'in the ArkTS Evolution class "ArkTSClassNoCtor" type in the object literal.' ] ); - ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]); + ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]); const hasError = interopTransformLog.errors.some(error => error.message.includes(errInfo.toString()) ); @@ -607,14 +606,12 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-3: test import ArkTS evoluion Record in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_RECORD_CODE); - const isStaticRecord = () => (true); - const mockedTs = { - ...require('typescript'), - isStaticRecord - }; - let interopTransform; - ({ interopTransform } = proxyquire('../../../lib/process_arkts_evolution', { 'typescript': mockedTs })); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const originalChecker = program.getTypeChecker(); + const mockedTypeChecker = Object.create(originalChecker); + mockedTypeChecker.isStaticRecord = () => true; + const mockedProgram = Object.create(program); + mockedProgram.getTypeChecker = () => mockedTypeChecker; + const result = ts.transform(testSourceFile, [interopTransform(mockedProgram, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_RECORD_CODE_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -622,7 +619,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-1: test import ArkTS evoluion class (variable init) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_1); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_1_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -630,7 +627,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-2: test import ArkTS evoluion class (object assignment) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_2); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_2_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -638,7 +635,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-3: test import ArkTS evoluion class (type assertions) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_3); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_3_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -646,7 +643,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-4: test import ArkTS evoluion class (property init) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_4); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_4_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -654,7 +651,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-5: test import ArkTS evoluion class (contr function call) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_5); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_5_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -662,7 +659,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-6: test import ArkTS evoluion class (multi-layer object assignment) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_6); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_6_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -670,7 +667,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-7: test import ArkTS evoluion class (parameter initp) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_7); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_7_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -678,7 +675,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-8: test import ArkTS evoluion class (function call) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_8); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_8_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -686,7 +683,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-9: test import ArkTS evoluion class (arrow function return value) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_9); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_9_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -694,7 +691,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-4-10: test import ArkTS evoluion class (function return value) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_CLASS_CODE_10); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_CLASS_CODE_10_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -702,7 +699,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-5-1: test import ArkTS evoluion interface (variable init) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_1); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_1_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -710,7 +707,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-5-2: test import ArkTS evoluion interface (type assertions) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_2); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_2_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -718,7 +715,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-5-3: test import ArkTS evoluion interface (property init) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_3); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_3_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -726,7 +723,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-5-4: test import ArkTS evoluion interface (contr function call) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_4); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_4_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -734,7 +731,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-5-5: test import ArkTS evoluion interface (parameter initp) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_5); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_5_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -742,7 +739,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-5-6: test import ArkTS evoluion interface (function call) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_6); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_6_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -750,7 +747,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-5-7: test import ArkTS evoluion interface (arrow function return value) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_7); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_7_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -758,7 +755,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-5-8: test import ArkTS evoluion interface (function return value) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_INTERFACE_CODE_8); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_INTERFACE_CODE_8_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -766,7 +763,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-6: test import ArkTS evoluion function in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(IMPORT_ARKTS_EVO_FUNCTION_CODE); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === IMPORT_ARKTS_EVO_FUNCTION_CODE_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -774,7 +771,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-7: test union type (no ambiguity) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(UNION_NO_AMBIGUITY_CODE); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === UNION_NO_AMBIGUITY_CODE_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -782,7 +779,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-8: test union type (ambiguity) in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(UNION_AMBIGUITY_CODE); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); const errInfo: LogData = LogDataFactory.newInstance( ErrorCode.ETS2BUNDLE_EXTERNAL_UNION_TYPE_AMBIGUITY, @@ -801,7 +798,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-1-9: test parenthesized type in object literal', function () { const { program, testSourceFile } = createDualSourceProgram(PARENTHESIZED_CODE); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, false)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === PARENTHESIZED_CODE_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); @@ -809,7 +806,7 @@ mocha.describe('process arkts evolution tests', function () { mocha.it('3-2-1: test class extends arkTS evolution class or implement arkTS evolution interface', function () { const { program, testSourceFile } = createDualSourceProgram(CLASS_IMPLEMENTS_ARKTS_EVO_CLASS_OR_INTERFACE_CODE); - const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true, true)]).transformed[0]; + const result = ts.transform(testSourceFile, [interopTransform(program, testFileName, true)]).transformed[0]; const resultCode = ts.createPrinter().printFile(result); expect(resultCode === CLASS_IMPLEMENTS_ARKTS_EVO_CLASS_OR_INTERFACE_CODE_EXPECT).to.be.true; cleanUpProcessArkTSEvolutionObj(); -- Gitee From 619d90477f2636051255325e19ebd4159fdce1c8 Mon Sep 17 00:00:00 2001 From: wangweiyuan Date: Thu, 29 May 2025 17:47:42 +0800 Subject: [PATCH 109/123] add ui-syntax-plugins 8/22 Signed-off-by: wangweiyuan --- .../rules/build-root-node.ts | 59 +-- .../component-componentV2-mix-use-check.ts | 68 +++- .../rules/componentV2-mix-check.ts | 3 + .../rules/computed-decorator-check.ts | 341 ++++++++++++++++++ .../consumer-provider-decorator-check.ts | 325 +++++++++++++---- .../rules/monitor-decorator-check.ts | 79 ++-- .../rules/no-duplicate-state-manager.ts | 25 +- 7 files changed, 750 insertions(+), 150 deletions(-) create mode 100644 arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts diff --git a/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts b/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts index c3678f1fe..39d8bb07a 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts @@ -21,12 +21,29 @@ const BUILD_NAME: string = 'build'; const BUILD_ROOT_NUM: number = 1; const STATEMENT_LENGTH: number = 1; -function isBuildOneRoot(statements: readonly arkts.Statement[], buildNode: arkts.Identifier, +function isBuildOneRoot( + entryDecoratorUsage: arkts.AnnotationUsage | undefined, + statements: readonly arkts.Statement[], + buildNode: arkts.Identifier | undefined, context: UISyntaxRuleContext): void { if (statements.length > STATEMENT_LENGTH && buildNode) { context.report({ node: buildNode, - message: rule.messages.invalidBuildRootCount, + message: entryDecoratorUsage ? rule.messages.invalidBuildRoot : rule.messages.invalidBuildRootNode + }); + } +} + +function reportvalidBuildRoot( + entryDecoratorUsage: arkts.AnnotationUsage | undefined, + isContainer: boolean, + buildNode: arkts.Identifier | undefined, + context: UISyntaxRuleContext +): void { + if (entryDecoratorUsage && !isContainer && buildNode) { + context.report({ + node: buildNode, + message: rule.messages.invalidBuildRoot, }); } } @@ -38,7 +55,6 @@ function checkBuildRootNode(node: arkts.AstNode, context: UISyntaxRuleContext): } const entryDecoratorUsage = getAnnotationUsage(node, PresetDecorators.ENTRY); node.definition.body.forEach(member => { - // Determine the number of root node if (!arkts.isMethodDefinition(member) || getIdentifierName(member.name) !== BUILD_NAME) { return; } @@ -48,14 +64,13 @@ function checkBuildRootNode(node: arkts.AstNode, context: UISyntaxRuleContext): } const buildNode = member.scriptFunction.id; const statements = blockStatement.statements; - // rule1: The 'build' method cannot have more than one root node. if (buildNode) { - isBuildOneRoot(statements, buildNode, context); + // rule1: The 'build' method cannot have more than one root node. + isBuildOneRoot(entryDecoratorUsage, statements, buildNode, context); } if (statements.length !== BUILD_ROOT_NUM) { return; } - // Determine whether it is a container component const expressionStatement = statements[0]; if (!arkts.isExpressionStatement(expressionStatement)) { return; @@ -64,29 +79,31 @@ function checkBuildRootNode(node: arkts.AstNode, context: UISyntaxRuleContext): if (!arkts.isCallExpression(callExpression)) { return; } - const componentName = callExpression.expression.dumpSrc(); + let componentName: string = ''; + if (arkts.isMemberExpression(callExpression.expression) && + arkts.isCallExpression(callExpression.expression.object) && + arkts.isIdentifier(callExpression.expression.object.expression)) { + componentName = getIdentifierName(callExpression.expression.object.expression); + } else if (arkts.isIdentifier(callExpression.expression)) { + componentName = getIdentifierName(callExpression.expression); + } let isContainer: boolean = false; - loadedContainerComponents?.forEach(container => { - if (componentName.includes(container)) { - isContainer = true; - } - }); - // rule2: If the component is decorated by '@Entry', - // its 'build' function can have only one root node, which must be a container component. - if (entryDecoratorUsage && !isContainer && buildNode) { - context.report({ - node: buildNode, - message: rule.messages.invalidBuildRoot, - }); + if (!loadedContainerComponents) { + return; } + isContainer = componentName + ? loadedContainerComponents.has(componentName) + : false; + // rule2: its 'build' function can have only one root node, which must be a container component. + reportvalidBuildRoot(entryDecoratorUsage, isContainer, buildNode, context); }); } const rule: UISyntaxRule = { name: 'build-root-node', messages: { - invalidBuildRootCount: `The 'build' method cannot have more than one root node.`, - invalidBuildRoot: `If the component is decorated by '@Entry', its 'build' function can have only one root node, which must be a container component.` + invalidBuildRoot: `In an '@Entry' decorated component, the 'build' function can have only one root node, which must be a container component.`, + invalidBuildRootNode: `The 'build' function can have only one root node.` }, setup(context) { return { diff --git a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts index ce7afdf8f..89275f075 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts @@ -14,22 +14,46 @@ */ import * as arkts from '@koalaui/libarkts'; -import { PresetDecorators } from '../utils'; +import { PresetDecorators, getIdentifierName } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +const v1ComponentDecorators: string[] = [ + PresetDecorators.STATE, + PresetDecorators.PROP, + PresetDecorators.LINK, + PresetDecorators.PROVIDE, + PresetDecorators.CONSUME, + PresetDecorators.STORAGE_LINK, + PresetDecorators.STORAGE_PROP, + PresetDecorators.LOCAL_STORAGE_LINK, + PresetDecorators.LOCAL_STORAGE_PROP, +]; +const v2ComponentDecorators: string[] = [ + PresetDecorators.LOCAL, + PresetDecorators.PARAM, + PresetDecorators.EVENT, + PresetDecorators.PROVIDER, + PresetDecorators.CONSUMER, +]; + // Report an Observed version violation error function reportObservedConflict( node: arkts.ClassProperty, context: UISyntaxRuleContext, + componentDecorators: string[], message: string ): void { node.annotations.forEach((anno) => { - if (anno.expr?.dumpSrc()) { + if (!anno.expr) { + return; + } + const annotationName = getIdentifierName(anno.expr); + if (annotationName && componentDecorators.includes(annotationName)) { context.report({ node: anno, message: message, data: { - annotation: anno.expr?.dumpSrc(), + annotation: annotationName, } }); } @@ -47,12 +71,12 @@ function processNode( while (queue.length > 0) { const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; if (arkts.isIdentifier(currentNode)) { - if (observedV1Name.has(currentNode.dumpSrc()) && annotationName === PresetDecorators.COMPONENT_V2) { - reportObservedConflict(node, context, rule.messages.observedv1_v2); + if (observedV1Name.has(getIdentifierName(currentNode)) && annotationName === PresetDecorators.COMPONENT_V2) { + reportObservedConflict(node, context, v2ComponentDecorators, rule.messages.observedv1_v2); break; } - if (observedV2Name.has(currentNode.dumpSrc()) && annotationName === PresetDecorators.COMPONENT_V1) { - reportObservedConflict(node, context, rule.messages.observedv2_v1); + if (observedV2Name.has(getIdentifierName(currentNode)) && annotationName === PresetDecorators.COMPONENT_V1) { + reportObservedConflict(node, context, v1ComponentDecorators, rule.messages.observedv2_v1); break; } } @@ -82,11 +106,15 @@ function traverseTree( function findAllObserved(node: arkts.AstNode, observedV1Name: Set, observedV2Name: Set): void { if (arkts.isClassDeclaration(node)) { node.definition?.annotations.forEach((anno) => { - if (anno.expr?.dumpSrc() === PresetDecorators.OBSERVED_V1) { + if (!anno.expr) { + return; + } + const annotationName = getIdentifierName(anno.expr); + if (annotationName === PresetDecorators.OBSERVED_V1) { const componentV1Name = node?.definition?.ident?.name; componentV1Name ? observedV1Name.add(componentV1Name) : null; } - if (anno.expr?.dumpSrc() === PresetDecorators.OBSERVED_V2) { + if (annotationName === PresetDecorators.OBSERVED_V2) { const componentV2Name = node?.definition?.ident?.name; componentV2Name ? observedV2Name.add(componentV2Name) : null; } @@ -106,7 +134,7 @@ function findAllTSTypeAliasDeclaration( if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION) { node.getChildren().forEach((child) => { if (arkts.isIdentifier(child)) { - const typeName = child.dumpSrc(); + const typeName = getIdentifierName(child); findAllObservedType(node, typeName, observedV1Name, observedV2Name); } }); @@ -123,10 +151,10 @@ function findAllObservedType( observedV1Name: Set, observedV2Name: Set ): void { - if (arkts.isIdentifier(node) && observedV1Name.has(node.dumpSrc())) { + if (arkts.isIdentifier(node) && observedV1Name.has(getIdentifierName(node))) { observedV1Name.add(typeName); } - if (arkts.isIdentifier(node) && observedV2Name.has(node.dumpSrc())) { + if (arkts.isIdentifier(node) && observedV2Name.has(getIdentifierName(node))) { observedV2Name.add(typeName); } const children = node.getChildren(); @@ -141,11 +169,15 @@ function processComponentAnnotations( observedV2Name: Set, context: UISyntaxRuleContext ): void { - node?.definition?.annotations.forEach((anno) => { - if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2) { + node.definition.annotations.forEach((anno) => { + if (!anno.expr) { + return; + } + const annotationName = getIdentifierName(anno.expr); + if (annotationName === PresetDecorators.COMPONENT_V2) { traverseTree(node, PresetDecorators.COMPONENT_V2, observedV1Name, observedV2Name, context); } - if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V1) { + if (annotationName === PresetDecorators.COMPONENT_V1) { traverseTree(node, PresetDecorators.COMPONENT_V1, observedV1Name, observedV2Name, context); } }); @@ -154,8 +186,8 @@ function processComponentAnnotations( const rule: UISyntaxRule = { name: 'component-componentV2-mix-use-check', messages: { - observedv1_v2: `The type of the @{{annotation}} Decorator property can not be a class decorated with @Observed.`, - observedv2_v1: `The type of the @{{annotation}} Decorator property can not be a class decorated with @ObservedV2.` + observedv1_v2: `The type of the @{{annotation}} property cannot be a class decorated with '@Observed'.`, + observedv2_v1: `The type of the @{{annotation}} property cannot be a class decorated with '@ObservedV2'.` }, setup(context) { let observedV1Name: Set = new Set(); @@ -174,4 +206,4 @@ const rule: UISyntaxRule = { }, }; -export default rule; \ No newline at end of file +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts index 082d768d1..b29ca95f2 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts @@ -28,6 +28,9 @@ const rule: UISyntaxRule = { if (!arkts.isStructDeclaration(node)) { return; } + if (!node.definition) { + return; + } const structName = node.definition.ident?.name ?? ''; const structNameNode = node.definition.ident; if (!structNameNode) { diff --git a/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts new file mode 100644 index 000000000..1d67fb928 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getIdentifierName, PresetDecorators, getAnnotationName, getAnnotationUsage } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +const BUILD_NAME: string = 'build'; + +function validateStructBody( + node: arkts.StructDeclaration, + computedGetters: Map, + computedSetters: Map, + context: UISyntaxRuleContext +): void { + let hasComputed: arkts.AnnotationUsage | undefined; + node.definition.body.forEach((member) => { + if (arkts.isClassProperty(member)) { + validateComputedOnClassProperty(member, context); + return; + } + if (arkts.isMethodDefinition(member)) { + const methodName = getIdentifierName(member.name); + hasComputed = member.scriptFunction.annotations?.find(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.COMPUTED + ); + validateComputedMethodKind(member, hasComputed, methodName, computedGetters, context); + const isSetter = member.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET; + if (isSetter) { + computedSetters.set(methodName, member); + } + if (methodName === BUILD_NAME) { + validateBuildMethod(member, computedGetters, context); + } + } + }); + validateGetterSetterConflict(computedGetters, computedSetters, context); +} + +function validateComputedOnClassProperty(member: arkts.ClassProperty, context: UISyntaxRuleContext): void { + const hasComputed = member.annotations?.find(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.COMPUTED + ); + if (hasComputed) { + context.report({ + node: hasComputed, + message: rule.messages.onlyOnGetter, + fix: (hasComputed) => { + const startPosition = hasComputed.startPosition; + const endPosition = hasComputed.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); + } +} + +function validateComputedMethodKind( + member: arkts.MethodDefinition, + hasComputed: arkts.AnnotationUsage | undefined, + methodName: string, + computedGetters: Map, + context: UISyntaxRuleContext +): void { + if (hasComputed) { + const isGetter = member.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET; + if (!isGetter) { + reportValidateComputedMethodKind(hasComputed, context); + } else { + computedGetters.set(methodName, member); + } + } +} + +function reportValidateComputedMethodKind( + hasComputed: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + if (!hasComputed) { + return; + } + context.report({ + node: hasComputed, + message: rule.messages.onlyOnGetter, + fix: (hasComputed) => { + const startPosition = hasComputed.startPosition; + const endPosition = hasComputed.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +function validateBuildMethod( + member: arkts.MethodDefinition, + computedGetters: Map, + context: UISyntaxRuleContext +): void { + member.scriptFunction.body?.getChildren().forEach((childNode) => { + if (!arkts.isExpressionStatement(childNode)) { + return; + } + const queue: Array = [childNode]; + while (queue.length > 0) { + const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; + // Check if it's a CallExpression (function call) + if (arkts.isCallExpression(currentNode)) { + // Check if it's a $$(...) call + validateCallExpression(currentNode, computedGetters, context); + } + // Continue traversing the child nodes + const children = currentNode.getChildren(); + for (const child of children) { + queue.push(child); + } + } + }); +} + +function validateCallExpression( + currentNode: arkts.CallExpression, + computedGetters: Map, + context: UISyntaxRuleContext +): void { + // Check if it's a $$(...) call + if (!arkts.isIdentifier(currentNode.expression)) { + return; + } + if (getIdentifierName(currentNode.expression) === '$$') { + currentNode.arguments.forEach(argument => { + if (arkts.isMemberExpression(argument)) { + const getterName = getIdentifierName(argument.property); + reportValidateCallExpression(currentNode, getterName, computedGetters, context); + } + }); + } +} + +function reportValidateCallExpression( + currentNode: arkts.CallExpression, + getterName: string, + computedGetters: Map, + context: UISyntaxRuleContext +): void { + if (computedGetters.has(getterName)) { + context.report({ + node: currentNode, + message: rule.messages.noTwoWayBinding, + fix: (currentNode) => { + const startPosition = currentNode.startPosition; + const endPosition = currentNode.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); + } +} + +// Check for the presence of a @Computed property that defines both a getter and a setter +function validateGetterSetterConflict( + computedGetters: Map, + computedSetters: Map, + context: UISyntaxRuleContext +): void { + for (const [name] of computedGetters) { + if (computedSetters.has(name)) { + reportValidateGetterSetterConflict(computedSetters, name, context); + } + } +} + +function reportValidateGetterSetterConflict( + computedSetters: Map, + name: string, + context: UISyntaxRuleContext +): void { + context.report({ + node: computedSetters.get(name)!, + message: rule.messages.computedMethodDefineSet, + fix: (node) => { + const startPosition = node.startPosition; + const endPosition = node.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + }, + }); +} + +function validateClassBody( + node: arkts.ClassDeclaration, + computedGetters: Map, + context: UISyntaxRuleContext +): void { + const hasObservedV2 = node.definition?.annotations.find(annotation => + getAnnotationName(annotation) === PresetDecorators.OBSERVED_V2 + ); + node.definition?.body.forEach((member) => { + if (arkts.isMethodDefinition(member)) { + validateComputedInClass(node, member, hasObservedV2, context); + if (!arkts.isIdentifier(member.name)) { + return; + } + const methodName = getIdentifierName(member.name); + const hasComputed = member.scriptFunction.annotations?.find(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.COMPUTED + ); + validateComputedMethodKind(member, hasComputed, methodName, computedGetters, context); + } + }); +} + +function validateComponentV2InStruct( + node: arkts.StructDeclaration, + context: UISyntaxRuleContext +): void { + const hasComponentV2 = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); + const hasComponent = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); + node.definition?.body.forEach((member) => { + if (arkts.isMethodDefinition(member)) { + reportComponentV2InStruct(node, member, hasComponentV2, hasComponent, context); + } + }); +} + +function reportComponentV2InStruct( + node: arkts.StructDeclaration | arkts.ClassDeclaration, + member: arkts.MethodDefinition, + hasComponentV2: arkts.AnnotationUsage | undefined, + hasComponent: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + const hasComputed = member.scriptFunction.annotations?.find(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.COMPUTED + ); + if (hasComputed && !hasComponentV2 && !hasComponent) { + context.report({ + node: hasComputed, + message: rule.messages.componentV2InStruct, + fix: () => { + const startPosition = node.startPosition; + const endPosition = node.startPosition; + return { + range: [startPosition, endPosition], + code: `@${PresetDecorators.COMPONENT_V2}\n`, + }; + }, + }); + } + if (hasComputed && !hasComponentV2 && hasComponent) { + context.report({ + node: hasComputed, + message: rule.messages.componentV2InStruct, + fix: () => { + const startPosition = hasComponent.startPosition; + const endPosition = hasComponent.endPosition; + return { + range: [startPosition, endPosition], + code: `@${PresetDecorators.COMPONENT_V2}`, + }; + }, + }); + } +} + +function validateComputedInClass( + node: arkts.AstNode, + member: arkts.MethodDefinition, + hasObservedV2: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + const hasComputed = member.scriptFunction.annotations?.find(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.COMPUTED + ); + if (hasComputed && !hasObservedV2 && + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET === member.kind) { + context.report({ + node: hasComputed, + message: rule.messages.onlyInObservedV2, + fix: () => { + const startPosition = node.startPosition; + return { + range: [startPosition, startPosition], + code: `@${PresetDecorators.OBSERVED_V2}\n`, + }; + }, + }); + } +} + +const rule: UISyntaxRule = { + name: 'computed-decorator-check', + messages: { + onlyOnGetter: `@Computed can only decorate 'GetAccessor'.`, + onlyInObservedV2: `The '@Computed' can decorate only member method within a 'class' decorated with ObservedV2.`, + componentV2InStruct: `The '@Computed' decorator can only be used in a 'struct' decorated with ComponentV2.`, + noTwoWayBinding: `A property decorated by '@Computed' cannot be used with two-way bind syntax.`, + computedMethodDefineSet: `A property decorated by '@Computed' cannot define a set method.` + }, + setup(context) { + const computedGetters = new Map(); + const computedSetters = new Map(); + return { + parsed: (node): void => { + if (arkts.isStructDeclaration(node)) { + validateComponentV2InStruct(node, context); + validateStructBody(node, computedGetters, computedSetters, context); + } + if (arkts.isClassDeclaration(node)) { + validateClassBody(node, computedGetters, context); + } + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts index cb4f7fcd8..d95a5104b 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts @@ -14,72 +14,138 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, MultiMap, PresetDecorators } from '../utils'; +import { getAnnotationUsage, getIdentifierName, MultiMap, PresetDecorators, getAnnotationName } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -// Traverse the member variables of the struct, recording the members of the @Consumer modifications + +// Traverse the member variables of the struct, recording the members of the @Consumer or @Provider modifications function processStructMembers( node: arkts.StructDeclaration, structName: string, - componentv2WithConsumer: MultiMap + componentv2WithConsumer: MultiMap, + componentv2WithProvider: MultiMap ): void { node.definition.body.forEach((member) => { // When a member variable is @consumer modified, it is stored to mark fields that cannot be initialized if (arkts.isClassProperty(member)) { - const memberName = member?.key?.dumpSrc(); - structName && memberName ? componentv2WithConsumer.add(structName, memberName) : null; + const hasComsumerDecorator = member?.annotations.some(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.CONSUMER + ); + const hasProviderDecorator = member?.annotations.some(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.PROVIDER + ); + if (!member?.key) { + return; + } + const memberName = getIdentifierName(member?.key); + if (hasComsumerDecorator && structName && memberName) { + componentv2WithConsumer.add(structName, memberName); + } + + if (hasProviderDecorator && structName && memberName) { + componentv2WithProvider.add(structName, memberName); + } } }); } -function rememberStructName(node: arkts.AstNode, componentv2WithConsumer: MultiMap): void { + +function rememberStructName( + node: arkts.AstNode, + componentv2WithConsumer: MultiMap, + componentv2WithProvider: MultiMap, +): void { // First it has to be of the struct type if (arkts.isStructDeclaration(node)) { node?.definition?.annotations.forEach((anno) => { + if (!anno.expr) { + return; + } + const annoName = getIdentifierName(anno.expr); // Second, it must be decorated with a @component v2 decorator - if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2) { + if (annoName === PresetDecorators.COMPONENT_V2) { const structName = node.definition.ident?.name ?? ''; - processStructMembers(node, structName, componentv2WithConsumer); + processStructMembers(node, structName, componentv2WithConsumer, componentv2WithProvider); } }); } } + function findDecorator(member: arkts.ClassProperty, decorator: string): arkts.AnnotationUsage | undefined { return member.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === decorator + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === decorator ); } -// Verify that the @Consumer decorator is used on the method -function validateConsumerOnMethod(member: arkts.MethodDefinition, context: UISyntaxRuleContext): void { - const annotationNode = member.scriptFunction.annotations?.find(annotation => - annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.CONSUMER + +function findOtherDecorator(member: arkts.ClassProperty, decorator: string): arkts.AnnotationUsage | undefined { + return member.annotations?.find(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name !== decorator ); - if (annotationNode) { - context.report({ - node: annotationNode, - message: rule.messages.consumerOnlyOnMember, - fix: (annotationNode) => { - const startPosition = arkts.getStartPosition(annotationNode); - const endPosition = arkts.getEndPosition(annotationNode); - return { - range: [startPosition, endPosition], - code: '', - }; - } - }); +} + +function findDecoratorInMethod(member: arkts.MethodDefinition, decorator: string): arkts.AnnotationUsage | undefined { + return member.scriptFunction.annotations?.find(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === decorator + ); +} + +// Verify that the @Consumer decorator is used on the method +function validateDecoratorOnMethod(member: arkts.MethodDefinition, context: UISyntaxRuleContext): void { + validateDecorator(member, PresetDecorators.CONSUMER, context); + validateDecorator(member, PresetDecorators.PROVIDER, context); +} + +function validateDecorator( + member: arkts.MethodDefinition, + decoratorName: string, + context: UISyntaxRuleContext, +): void { + const decorator = findDecoratorInMethod(member, decoratorName); + if (!decorator) { + return; } + + context.report({ + node: decorator, + message: rule.messages.consumerOnlyOnMember, + data: { + decorator: getAnnotationName(decorator), + }, + fix: (decorator) => { + const startPosition = decorator.startPosition; + const endPosition = decorator.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); } + // @Consumer Bugs that conflict with other decorators -function reportMultipleBuiltInDecorators( - hasConsumeDecorator: arkts.AnnotationUsage, - otherDecorators: arkts.AnnotationUsage, +function validateMultipleBuiltInDecorators( + member: arkts.ClassProperty, + decorateName: string, context: UISyntaxRuleContext, ): void { + + const hasDecorator = findDecorator(member, decorateName); + const otherDecorators = findOtherDecorator(member, decorateName); + if (!hasDecorator || !otherDecorators) { + return; + } context.report({ - node: hasConsumeDecorator, + node: hasDecorator, message: rule.messages.multipleBuiltInDecorators, - fix: (hasConsumeDecorator) => { - const startPosition = arkts.getStartPosition(otherDecorators); - const endPosition = arkts.getEndPosition(otherDecorators); + data: { + decorator: getAnnotationName(hasDecorator) + }, + fix: (decorator) => { + const startPosition = otherDecorators.startPosition; + const endPosition = otherDecorators.endPosition; return { range: [startPosition, endPosition], code: '', @@ -87,20 +153,24 @@ function reportMultipleBuiltInDecorators( } }); } + // Report a bug where @Provider is missing @ComponentV2 function reportProviderRequiresComponentV2( - hasProviderDecorator: arkts.AnnotationUsage, + decorator: arkts.AnnotationUsage, hasComponent: arkts.AnnotationUsage | undefined, node: arkts.AstNode, context: UISyntaxRuleContext, ): void { if (hasComponent) { context.report({ - node: hasProviderDecorator, + node: decorator, message: rule.messages.providerRequiresComponentV2, + data: { + decorator: getAnnotationName(decorator), + }, fix: (hasProviderDecorator) => { - const startPosition = arkts.getStartPosition(hasComponent); - const endPosition = arkts.getEndPosition(hasComponent); + const startPosition = hasComponent.startPosition; + const endPosition = hasComponent.endPosition; return { range: [startPosition, endPosition], code: `@${PresetDecorators.COMPONENT_V2}`, @@ -109,10 +179,13 @@ function reportProviderRequiresComponentV2( }); } else { context.report({ - node: hasProviderDecorator, + node: decorator, message: rule.messages.providerRequiresComponentV2, + data: { + decorator: getAnnotationName(decorator), + }, fix: (hasProviderDecorator) => { - const startPosition = arkts.getStartPosition(node); + const startPosition = node.startPosition; const endPosition = startPosition; return { range: [startPosition, endPosition], @@ -122,36 +195,91 @@ function reportProviderRequiresComponentV2( }); } } + +function validateDecoratorWithComponentV2Requirement( + member: arkts.ClassProperty, + hasComponentV2: arkts.AnnotationUsage | undefined, + hasComponent: arkts.AnnotationUsage | undefined, + node: arkts.AstNode, + context: UISyntaxRuleContext, + decoratorName: string +): void { + const decorator = findDecorator(member, decoratorName); + if (decorator && !hasComponentV2) { + reportProviderRequiresComponentV2(decorator, hasComponent, node, context); + } +} + // Verify decorator conflicts on member variables -function validateMemberDecorators(member: arkts.ClassProperty, +function validateMemberDecorators( + member: arkts.ClassProperty, hasComponentV2: arkts.AnnotationUsage | undefined, hasComponent: arkts.AnnotationUsage | undefined, node: arkts.AstNode, context: UISyntaxRuleContext ): void { - const hasConsumeDecorator = findDecorator(member, PresetDecorators.CONSUMER); - const hasProviderDecorator = findDecorator(member, PresetDecorators.PROVIDER); - const otherDecorators = member.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() !== PresetDecorators.CONSUMER + // Check that the @Consumer is not mixed with other decorators + validateMultipleBuiltInDecorators(member, PresetDecorators.CONSUMER, context); + + // Check that the @Provider is mixed with other decorators + validateMultipleBuiltInDecorators(member, PresetDecorators.PROVIDER, context); + + // Check if the @Consumer is in a @ComponentV2-modified structure + validateDecoratorWithComponentV2Requirement( + member, hasComponentV2, hasComponent, node, context, PresetDecorators.CONSUMER + ); + // Check if the @Provider is in a @ComponentV2-modified structure + validateDecoratorWithComponentV2Requirement( + member, hasComponentV2, hasComponent, node, context, PresetDecorators.PROVIDER ); - if (hasConsumeDecorator && otherDecorators) { - reportMultipleBuiltInDecorators(hasConsumeDecorator, otherDecorators, context); - } - if (hasProviderDecorator && !hasComponentV2) { - reportProviderRequiresComponentV2(hasProviderDecorator, hasComponent, node, context); - } } + // Verify that @Provider is being used in the class -function validateProviderInClass(member: arkts.ClassProperty, context: UISyntaxRuleContext): void { - const hasProviderDecorator = findDecorator(member, PresetDecorators.PROVIDER); - if (hasProviderDecorator) { +function validateDecoratorInClass( + member: arkts.ClassProperty, + decoratorName: string, + context: UISyntaxRuleContext +): void { + const decorator = findDecorator(member, decoratorName); + if (!decorator) { + return; + } + context.report({ + node: decorator, + message: rule.messages.providerOnlyInStruct, + data: { + decorator: getAnnotationName(decorator), + }, + fix: (hasProviderDecorator) => { + const startPosition = hasProviderDecorator.startPosition; + const endPosition = hasProviderDecorator.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); +} + +// Verify that the current identifier is an illegally initialized @Consumer member variable +function reportValidateConsumer( + currentNode: arkts.Identifier, + callExpName: string, + componentv2WithConsumer: MultiMap, + context: UISyntaxRuleContext +): void { + if (componentv2WithConsumer.get(callExpName).includes(getIdentifierName(currentNode))) { context.report({ - node: hasProviderDecorator, - message: rule.messages.providerOnlyInStruct, - fix: (hasProviderDecorator) => { - const startPosition = arkts.getStartPosition(hasProviderDecorator); - const endPosition = arkts.getEndPosition(hasProviderDecorator); + node: currentNode.parent, + message: rule.messages.forbiddenInitialization, + data: { + decorator: PresetDecorators.CONSUMER, + value: getIdentifierName(currentNode), + structName: callExpName + }, + fix: () => { + const startPosition = currentNode.parent.startPosition; + const endPosition = currentNode.parent.endPosition; return { range: [startPosition, endPosition], code: '', @@ -160,24 +288,25 @@ function validateProviderInClass(member: arkts.ClassProperty, context: UISyntaxR }); } } -// Verify that the current identifier is an illegally initialized @Consumer member variable -function reportValidateConsumer( + +function reportValidateProvider( currentNode: arkts.Identifier, callExpName: string, - componentv2WithConsumer: MultiMap, + componentv2WithProvider: MultiMap, context: UISyntaxRuleContext ): void { - if (componentv2WithConsumer.get(callExpName).includes(currentNode.dumpSrc())) { + if (componentv2WithProvider.get(callExpName).includes(getIdentifierName(currentNode))) { context.report({ node: currentNode.parent, message: rule.messages.forbiddenInitialization, data: { - value: currentNode.dumpSrc(), + decorator: PresetDecorators.PROVIDER, + value: getIdentifierName(currentNode), structName: callExpName }, fix: () => { - const startPosition = arkts.getStartPosition(currentNode.parent); - const endPosition = arkts.getEndPosition(currentNode.parent); + const startPosition = currentNode.parent.startPosition; + const endPosition = currentNode.parent.endPosition; return { range: [startPosition, endPosition], code: '', @@ -186,10 +315,14 @@ function reportValidateConsumer( }); } } + // Verify that the @Consumer-decorated property is initialized function validateConsumerInitialization(node: arkts.CallExpression, componentv2WithConsumer: MultiMap, context: UISyntaxRuleContext): void { - const callExpName: string = node.expression.dumpSrc(); + if (!arkts.isIdentifier(node.expression)) { + return; + } + const callExpName: string = node.expression.name; if (componentv2WithConsumer.has(callExpName)) { const queue: Array = [node]; while (queue.length > 0) { @@ -204,7 +337,33 @@ function validateConsumerInitialization(node: arkts.CallExpression, componentv2W } } } -function collectStructsWithConsumer(node: arkts.AstNode, componentv2WithConsumer: MultiMap): void { + +function validateProviderInitialization(node: arkts.CallExpression, componentv2WithProvider: MultiMap, + context: UISyntaxRuleContext): void { + if (!arkts.isIdentifier(node.expression)) { + return; + } + const callExpName: string = node.expression.name; + if (componentv2WithProvider.has(callExpName)) { + const queue: Array = [node]; + while (queue.length > 0) { + const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; + if (arkts.isIdentifier(currentNode)) { + reportValidateProvider(currentNode, callExpName, componentv2WithProvider, context); + } + const children = currentNode.getChildren(); + for (const child of children) { + queue.push(child); + } + } + } +} + +function collectStructsWithConsumerAndProvider( + node: arkts.AstNode, + componentv2WithConsumer: MultiMap, + componentv2WithProvider: MultiMap, +): void { // Used to document all V2 structs that use '@Consumer' if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { // Breadth traversal is done through while and queues @@ -212,7 +371,7 @@ function collectStructsWithConsumer(node: arkts.AstNode, componentv2WithConsumer while (queue.length > 0) { const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; // Filter and record the nodes of the tree - rememberStructName(currentNode, componentv2WithConsumer); + rememberStructName(currentNode, componentv2WithConsumer, componentv2WithProvider); const children = currentNode.getChildren(); for (const child of children) { queue.push(child); @@ -220,13 +379,14 @@ function collectStructsWithConsumer(node: arkts.AstNode, componentv2WithConsumer } } } + function validateStructDecoratorsAndMembers(node: arkts.AstNode, context: UISyntaxRuleContext): void { if (arkts.isStructDeclaration(node)) { const hasComponentV2 = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); const hasComponent = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); node.definition.body.forEach(member => { if (arkts.isMethodDefinition(member)) { - validateConsumerOnMethod(member, context); + validateDecoratorOnMethod(member, context); } if (arkts.isClassProperty(member)) { validateMemberDecorators(member, hasComponentV2, hasComponent, node, context); @@ -234,38 +394,43 @@ function validateStructDecoratorsAndMembers(node: arkts.AstNode, context: UISynt }); } } -function validateProviderInClasses(node: arkts.AstNode, context: UISyntaxRuleContext): void { + +function validateInClass(node: arkts.AstNode, context: UISyntaxRuleContext): void { if (arkts.isClassDeclaration(node)) { node.definition?.body.forEach(member => { if (arkts.isClassProperty(member)) { - validateProviderInClass(member, context); + validateDecoratorInClass(member, PresetDecorators.CONSUMER, context); + validateDecoratorInClass(member, PresetDecorators.PROVIDER, context); } }); } } + const rule: UISyntaxRule = { name: 'consumer-provider-decorator-check', messages: { - consumerOnlyOnMember: `'@Consumer' can only decorate member property.`, + consumerOnlyOnMember: `'@{{decorator}}' can only decorate member property.`, multipleBuiltInDecorators: `The struct member variable can not be decorated by multiple built-in decorators.`, - providerRequiresComponentV2: `The '@Provider' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, - providerOnlyInStruct: `The '@Provider' decorator can only be used with 'struct'.`, - forbiddenInitialization: `Property '{{value}}' in the custom component '{{structName}}' cannot be initialized here (forbidden to specify).`, + providerRequiresComponentV2: `The '@{{decorator}}' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, + providerOnlyInStruct: `The '@{{decorator}}' decorator can only be used with 'struct'.`, + forbiddenInitialization: `The '@{{decorator}}' property '{{value}}' in the custom component '{{structName}}' cannot be initialized here (forbidden to specify).`, }, setup(context) { // Used to record the names of the corresponding structs and member variables that are @consumer modified let componentv2WithConsumer: MultiMap = new MultiMap(); + let componentv2WithProvider: MultiMap = new MultiMap(); return { parsed: (node): void => { - collectStructsWithConsumer(node, componentv2WithConsumer); + collectStructsWithConsumerAndProvider(node, componentv2WithConsumer, componentv2WithProvider); validateStructDecoratorsAndMembers(node, context); - validateProviderInClasses(node, context); + validateInClass(node, context); if (arkts.isCallExpression(node)) { validateConsumerInitialization(node, componentv2WithConsumer, context); + validateProviderInitialization(node, componentv2WithProvider, context); } }, }; }, }; -export default rule; +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts index e0696de48..1b08c9b6a 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts @@ -14,23 +14,33 @@ */ import * as arkts from '@koalaui/libarkts'; -import { PresetDecorators } from '../utils'; +import { getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +const MONITOR_COUNT_LIMIT = 1; + // Function declarations moved to the top with explicit return types function getLocalMonitorUsed(body: arkts.MethodDefinition): arkts.AnnotationUsage | undefined { const localMonitorUsed = body.scriptFunction.annotations?.find( - annotation => annotation.expr && - annotation.expr.dumpSrc() === PresetDecorators.MONITOR + annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.MONITOR ); return localMonitorUsed; } +function getMonitor(body: arkts.MethodDefinition): arkts.AnnotationUsage[] { + const monitor = body.scriptFunction.annotations?.filter( + annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.MONITOR + ); + return monitor; +} + function checkConflictingDecorators(context: UISyntaxRuleContext, body: arkts.MethodDefinition, localMonitorUsed: arkts.AnnotationUsage): boolean { const conflictingDecorators = body.scriptFunction.annotations?.filter( - annotation => annotation.expr && - annotation.expr.dumpSrc() !== PresetDecorators.MONITOR + annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name !== PresetDecorators.MONITOR ); if (conflictingDecorators?.length > 0) { reportConflictingDecorators(context, localMonitorUsed, conflictingDecorators); @@ -43,11 +53,11 @@ function reportConflictingDecorators(context: UISyntaxRuleContext, localMonitorU conflictingDecorators: arkts.AnnotationUsage[]): void { context.report({ node: localMonitorUsed, - message: rule.messages.invalidUsage1, + message: rule.messages.monitorUsedAlone, fix: () => { const startPositions = conflictingDecorators.map(annotation => - arkts.getStartPosition(annotation)); - const endPositions = conflictingDecorators.map(annotation => arkts.getEndPosition(annotation)); + annotation.startPosition); + const endPositions = conflictingDecorators.map(annotation => annotation.endPosition); const startPosition = startPositions[0]; const endPosition = endPositions[endPositions.length - 1]; return { @@ -60,19 +70,21 @@ function reportConflictingDecorators(context: UISyntaxRuleContext, localMonitorU function checkIfClassIsObservedV2(node: arkts.ClassDeclaration): boolean { return node.definition?.annotations?.some( - observedV2 => observedV2.expr?.dumpSrc() === PresetDecorators.OBSERVED_V2 + observedV2 => observedV2.expr && arkts.isIdentifier(observedV2.expr) && + observedV2.expr?.name === PresetDecorators.OBSERVED_V2 ) ?? false; } function checkIfStructIsComponentV2(node: arkts.StructDeclaration): boolean { - return node.definition?.annotations?.some( - componentV2 => componentV2.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2 + return node.definition.annotations?.some( + componentV2 => componentV2.expr && arkts.isIdentifier(componentV2.expr) && + componentV2.expr?.name === PresetDecorators.COMPONENT_V2 ) ?? false; } function reportInvalidUsage(context: UISyntaxRuleContext, node: arkts.AstNode, message: string, fixCode: string) : void { - const startPosition = arkts.getStartPosition(node); + const startPosition = node.startPosition; context.report({ node, message, @@ -91,7 +103,11 @@ function checkMultipleDecorators( let monitorUsed: boolean = false; node.definition?.body.forEach(body => { if (arkts.isMethodDefinition(body)) { + const duplicatedMonitor = getMonitor(body); const localMonitorUsed = getLocalMonitorUsed(body); + if (duplicatedMonitor.length > MONITOR_COUNT_LIMIT && localMonitorUsed) { + reportDuplicatedMonitor(context, localMonitorUsed); + } if (localMonitorUsed) { monitorUsed = true; checkConflictingDecorators(context, body, localMonitorUsed); @@ -102,6 +118,21 @@ function checkMultipleDecorators( return monitorUsed; } +function reportDuplicatedMonitor(context: UISyntaxRuleContext, localMonitorUsed: arkts.AstNode,): void { + context.report({ + node: localMonitorUsed, + message: rule.messages.duplicatedMonitor, + fix: () => { + const startPosition = localMonitorUsed.startPosition; + const endPosition = localMonitorUsed.endPosition; + return { + range: [startPosition, endPosition], + code: '' + }; + } + }); +} + function checkDecorateMethod( node: arkts.ClassDeclaration | arkts.StructDeclaration, context: UISyntaxRuleContext @@ -112,16 +143,17 @@ function checkDecorateMethod( return; } const monitorDecorator = body.annotations?.find( - annotation => annotation.expr?.dumpSrc() === PresetDecorators.MONITOR); + annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name === PresetDecorators.MONITOR); if (monitorDecorator === undefined) { return; } context.report({ node: monitorDecorator, - message: rule.messages.invalidUsage4, + message: rule.messages.monitorDecorateMethod, fix: () => { - const startPosition = arkts.getStartPosition(monitorDecorator); - const endPosition = arkts.getEndPosition(monitorDecorator); + const startPosition = monitorDecorator.startPosition; + const endPosition = monitorDecorator.endPosition; return { range: [startPosition, endPosition], code: '', @@ -135,14 +167,15 @@ function checkDecorateMethod( const rule: UISyntaxRule = { name: 'monitor-decorator-check', messages: { - invalidUsage1: + monitorUsedAlone: `The member property or method can not be decorated by multiple built-in decorators.`, - invalidUsage2: + monitorUsedInObservedV2Class: `The '@Monitor' can decorate only member method within a 'class' decorated with @ObservedV2.`, - invalidUsage3: + monitorUsedInComponentV2Struct: `The '@Monitor' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, - invalidUsage4: - `@Monitor can only decorate method`, + monitorDecorateMethod: + `@Monitor can only decorate method.`, + duplicatedMonitor: `Duplicate decorators for method are not allowed.`, }, setup(context) { return { @@ -159,10 +192,10 @@ const rule: UISyntaxRule = { // Check for errors related to @Monitor usage if (monitorUsed && !isObservedV2 && arkts.isClassDeclaration(node)) { - reportInvalidUsage(context, node, rule.messages.invalidUsage2, `@${PresetDecorators.OBSERVED_V2}\n`); + reportInvalidUsage(context, node, rule.messages.monitorUsedInObservedV2Class, `@${PresetDecorators.OBSERVED_V2}`); } if (monitorUsed && !isComponentV2 && arkts.isStructDeclaration(node)) { - reportInvalidUsage(context, node, rule.messages.invalidUsage3, `@${PresetDecorators.COMPONENT_V2}\n`); + reportInvalidUsage(context, node, rule.messages.monitorUsedInComponentV2Struct, `@${PresetDecorators.COMPONENT_V2}\n`); } checkDecorateMethod(node, context); diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts index df1468fd5..725bcbba5 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts @@ -14,15 +14,15 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getClassPropertyAnnotationNames } from '../utils'; +import { getClassPropertyAnnotationNames, getIdentifierName, PresetDecorators, getAnnotationUsage } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; export const stateManagementDecorator = { - STATE: 'State', - PROP: 'Prop', - LINK: 'Link', - PROVIDE: 'Provide', - CONSUME: 'Consume' + STATE: PresetDecorators.STATE, + PROP: PresetDecorators.PROP, + LINK: PresetDecorators.LINK, + PROVIDE: PresetDecorators.PROVIDER, + CONSUME: PresetDecorators.CONSUME }; const CLASS_PROPERTY_ANNOTATION_ONE: number = 1; @@ -38,8 +38,13 @@ function duplicateState( const stateDecorators = propertyDecorators.filter(decorator => Object.values(stateManagementDecorator).includes(decorator) ); + + // Check if Require is included const propertyNameNode = body.key; - const attributeName = body.key?.dumpSrc(); + let attributeName: string = ''; + if (propertyNameNode && arkts.isIdentifier(propertyNameNode)) { + attributeName = getIdentifierName(propertyNameNode); + } if (!propertyNameNode || !attributeName) { return; } @@ -57,7 +62,7 @@ function duplicateState( const rule: UISyntaxRule = { name: 'no-duplicate-state-manager', messages: { - duplicateState: `This attribute '{{attributeName}}' cannot have mutilate state management decorators. `, + duplicateState: `This property '{{attributeName}}' cannot have mutilate state management decorators.`, }, setup(context) { return { @@ -65,6 +70,10 @@ const rule: UISyntaxRule = { if (!arkts.isStructDeclaration(node)) { return; } + const hasComponentV2 = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); + if (hasComponentV2) { + return; + } duplicateState(node, context); }, }; -- Gitee From 85c78cd926dd1fd00147f626799b154fdc132549 Mon Sep 17 00:00:00 2001 From: lihao Date: Wed, 21 May 2025 22:06:27 +0800 Subject: [PATCH 110/123] File-based hybrid compilation Issue: https://gitee.com/openharmony/developtools_ace_ets2bundle/issues/ICC7RT Signed-off-by: lihao Change-Id: I7be036f720af6970f3b4c9d796dab82cff8d29d7 --- compiler/main.js | 7 +- compiler/src/ets_checker.ts | 8 +- .../interop/run_declgen_standalone.ts | 408 ++++++++++++++++++ .../fast_build/ark_compiler/interop/type.ts | 31 +- .../ark_compiler/module/module_mode.ts | 14 +- .../ark_compiler/module/module_source_file.ts | 10 +- .../common/process_project_config.ts | 6 +- compiler/src/pre_define.ts | 3 +- compiler/src/process_arkts_evolution.ts | 86 +++- 9 files changed, 530 insertions(+), 43 deletions(-) create mode 100644 compiler/src/fast_build/ark_compiler/interop/run_declgen_standalone.ts diff --git a/compiler/main.js b/compiler/main.js index c9d6a4e88..22dbce8fa 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -419,7 +419,7 @@ function setAbilityPages(projectConfig) { if (projectConfig.aceModuleJsonPath && fs.existsSync(projectConfig.aceModuleJsonPath)) { const moduleJson = JSON.parse(fs.readFileSync(projectConfig.aceModuleJsonPath).toString()); abilityPages = readAbilityEntrance(moduleJson); - setAbilityFile(projectConfig, abilityPages); + setAbilityFile(projectConfig, abilityPages, moduleJson.module?.codeLanguage); setBundleModuleInfo(projectConfig, moduleJson); } } @@ -486,13 +486,16 @@ function setBundleModuleInfo(projectConfig, moduleJson) { } } -function setAbilityFile(projectConfig, abilityPages) { +function setAbilityFile(projectConfig, abilityPages, codeLanguage) { abilityPages.forEach(abilityPath => { const projectAbilityPath = path.resolve(projectConfig.projectPath, '../', abilityPath); if (path.isAbsolute(abilityPath)) { abilityPath = '.' + abilityPath.slice(projectConfig.projectPath.length); } const entryPageKey = abilityPath.replace(/^\.\/ets\//, './').replace(/\.ts$/, '').replace(/\.ets$/, ''); + if (codeLanguage === '1.2') { + return; + } if (fs.existsSync(projectAbilityPath)) { abilityConfig.projectAbilityPath.push(projectAbilityPath); projectConfig.entryObj[entryPageKey] = projectAbilityPath + '?entry'; diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index 1ec5ea72b..3e3ed92b2 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -110,6 +110,7 @@ import { } from '../node_modules/declgen/build/src/generateInteropDecls'; import { arkTSEvolutionModuleMap, + arkTSHybridModuleMap, getArkTSEvoDeclFilePath } from './process_arkts_evolution'; import { processInteropUI } from './process_interop_ui'; @@ -572,9 +573,6 @@ export function serviceChecker(rootFileNames: string[], newLogger: Object = null processBuildHap(cacheFile, rootFileNames, compilationTime, rollupShareObject); MemoryMonitor.stopRecordStage(processBuildHaprrecordInfo); } - if (rollupShareObject?.projectConfig.mixCompile) { - generateDeclarationFileForSTS(rootFileNames); - } if (globalProgram.program && (process.env.watchMode !== 'true' && !projectConfig.isPreview && !projectConfig.hotReload && !projectConfig.coldReload)) { @@ -1093,7 +1091,7 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string resolvedModules.push(result.resolvedModule); } } else if (result.resolvedModule.resolvedFileName && /\.ets$/.test(result.resolvedModule.resolvedFileName) && - !/\.d\.ets$/.test(result.resolvedModule.resolvedFileName) && arkTSEvolutionModuleMap.size !== 0) { + !/\.d\.ets$/.test(result.resolvedModule.resolvedFileName) && (arkTSEvolutionModuleMap.size !== 0 || arkTSHybridModuleMap.size !== 0)) { // When result has a value and the path parsed is the source code file path of module 1.2, // the parsing result needs to be modified to the glue code path of module 1.2 let arktsEvoDeclFilePathExist: boolean = false; @@ -1315,7 +1313,7 @@ export function instanceInsteadThis(content: string, fileName: string, extendFun return content; } -function getResolveModule(modulePath: string, type): ts.ResolvedModuleFull { +export function getResolveModule(modulePath: string, type): ts.ResolvedModuleFull { return { resolvedFileName: modulePath, isExternalLibraryImport: false, diff --git a/compiler/src/fast_build/ark_compiler/interop/run_declgen_standalone.ts b/compiler/src/fast_build/ark_compiler/interop/run_declgen_standalone.ts new file mode 100644 index 000000000..cf724c889 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/interop/run_declgen_standalone.ts @@ -0,0 +1,408 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { FileManager } from './interop_manager'; +import { ResolveModuleInfo, getResolveModule, readDeaclareFiles } from '../../../ets_checker'; +import { processInteropUI } from '../../../process_interop_ui'; +import { + mkdirsSync, + readFile, + toUnixPath +} from '../../../utils'; +import { + ArkTSEvolutionModule, + BuildType, + DeclFilesConfig, + Params, + ProjectConfig, + RunnerParms +} from './type'; +import fs from 'fs'; +import path from 'path'; +import * as ts from 'typescript'; +import { EXTNAME_D_ETS, EXTNAME_JS } from '../common/ark_define'; +import { getRealModulePath } from '../../system_api/api_check_utils'; +import { generateInteropDecls } from '../../../../node_modules/declgen/build/src/generateInteropDecls'; + +export function run(param: Params): boolean { + FileManager.init(param.dependentModuleMap); + DeclfileProductor.init(param); + param.tasks.forEach(task => { + const moduleInfo = FileManager.arkTSModuleMap.get(task.packageName); + if (task.buildTask === BuildType.DECLGEN) { + DeclfileProductor.getInstance().runDeclgen(moduleInfo); + } else if (task.buildTask === BuildType.INTEROP_CONTEXT) { + DeclfileProductor.getInstance().writeDeclFileInfo(moduleInfo, task.mainModuleName); + } else if (task.buildTask === BuildType.BYTE_CODE_HAR) { + //todo + } + }); + return true; +} + +class DeclfileProductor { + private static declFileProductor: DeclfileProductor; + + static compilerOptions: ts.CompilerOptions; + static sdkConfigPrefix = 'ohos|system|kit|arkts'; + static sdkConfigs = []; + static systemModules = []; + static defaultSdkConfigs = []; + static projectPath; + private projectConfig; + private pkgDeclFilesConfig: { [pkgName: string]: DeclFilesConfig } = {}; + + static init(param: Params): void { + DeclfileProductor.declFileProductor = new DeclfileProductor(param); + DeclfileProductor.compilerOptions = ts.readConfigFile( + path.join(__dirname, '../../../../tsconfig.json'), ts.sys.readFile).config.compilerOptions; + DeclfileProductor.initSdkConfig(); + Object.assign(DeclfileProductor.compilerOptions, { + emitNodeModulesFiles: true, + importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Preserve, + module: ts.ModuleKind.CommonJS, + moduleResolution: ts.ModuleResolutionKind.NodeJs, + noEmit: true, + packageManagerType: 'ohpm', + allowJs: true, + allowSyntheticDefaultImports: true, + esModuleInterop: true, + noImplicitAny: false, + noUnusedLocals: false, + noUnusedParameters: false, + experimentalDecorators: true, + resolveJsonModule: true, + skipLibCheck: false, + sourceMap: true, + target: 8, + types: [], + typeRoots: [], + lib: ['lib.es2021.d.ts'], + alwaysStrict: true, + checkJs: false, + maxFlowDepth: 2000, + etsAnnotationsEnable: false, + etsLoaderPath: path.join(__dirname, '../../../'), + needDoArkTsLinter: true, + isCompatibleVersion: false, + skipTscOhModuleCheck: false, + skipArkTSStaticBlocksCheck: false, + incremental: true, + tsImportSendableEnable: false, + skipPathsInKeyForCompilationSettings: true, + }); + DeclfileProductor.projectPath = param.projectConfig.projectRootPath; + } + static getInstance(param?: Params): DeclfileProductor { + if (!this.declFileProductor) { + this.declFileProductor = new DeclfileProductor(param); + } + return this.declFileProductor; + } + + private constructor(param: Params) { + this.projectConfig = param.projectConfig as ProjectConfig; + } + + runDeclgen(moduleInfo: ArkTSEvolutionModule): void { + let inputList = []; + moduleInfo.dynamicFiles.forEach(path => { + inputList.push(toUnixPath(path)); + }); + readDeaclareFiles().forEach(path => { + inputList.push(toUnixPath(path)); + }); + + inputList = inputList.filter(filePath => !filePath.endsWith('.js')); + const config: RunnerParms = { + inputDirs: [], + inputFiles: inputList, + outDir: moduleInfo.declgenV2OutPath, + // use package name as folder name + rootDir: moduleInfo.modulePath, + customResolveModuleNames: resolveModuleNames, + customCompilerOptions: DeclfileProductor.compilerOptions, + includePaths: [moduleInfo.modulePath] + }; + if (fs.existsSync(config.outDir)) { + fs.rmSync(config.outDir, { recursive: true, force: true }); + } + fs.mkdirSync(config.outDir, { recursive: true }); + generateInteropDecls(config); + processInteropUI(FileManager.arkTSModuleMap.get(moduleInfo.packageName)?.declgenV2OutPath); + } + + writeDeclFileInfo(moduleInfo: ArkTSEvolutionModule, mainModuleName: string): void { + moduleInfo.dynamicFiles.forEach(file => { + this.addDeclFilesConfig(file, mainModuleName, this.projectConfig.bundleName, moduleInfo); + }); + + const declFilesConfigFile: string = toUnixPath(moduleInfo.declFilesPath); + mkdirsSync(path.dirname(declFilesConfigFile)); + fs.writeFileSync(declFilesConfigFile, JSON.stringify(this.pkgDeclFilesConfig[moduleInfo.packageName], null, 2), 'utf-8'); + } + + addDeclFilesConfig(filePath: string, mainModuleName: string, bundleName: string, moduleInfo: ArkTSEvolutionModule): void { + const projectFilePath = getRelativePath(filePath, moduleInfo.modulePath); + + const declgenV2OutPath: string = this.getDeclgenV2OutPath(moduleInfo.packageName); + if (!declgenV2OutPath) { + return; + } + if (!this.pkgDeclFilesConfig[moduleInfo.packageName]) { + this.pkgDeclFilesConfig[moduleInfo.packageName] = { packageName: moduleInfo.packageName, files: {} }; + } + if (this.pkgDeclFilesConfig[moduleInfo.packageName].files[projectFilePath]) { + return; + } + // The module name of the entry module of the project during the current compilation process. + const normalizedFilePath: string = `${moduleInfo.packageName}/${projectFilePath}`; + const declPath: string = path.join(toUnixPath(declgenV2OutPath), projectFilePath) + EXTNAME_D_ETS; + const ohmUrl: string = `N&${mainModuleName}&${bundleName}&${normalizedFilePath}&${moduleInfo.packageVersion}`; + this.pkgDeclFilesConfig[moduleInfo.packageName].files[projectFilePath] = { declPath, ohmUrl: `@normalized:${ohmUrl}` }; + } + + getDeclgenV2OutPath(pkgName: string): string { + if (FileManager.arkTSModuleMap.size && FileManager.arkTSModuleMap.get(pkgName)) { + const arkTsModuleInfo: ArkTSEvolutionModule = FileManager.arkTSModuleMap.get(pkgName); + return arkTsModuleInfo.declgenV2OutPath; + } + return ''; + } + + static initSdkConfig(): void { + const apiDirPath = path.resolve(__dirname, '../../../../../api'); + const arktsDirPath = path.resolve(__dirname, '../../../../../arkts'); + const kitsDirPath = path.resolve(__dirname, '../../../../../kits'); + const systemModulePathArray = [apiDirPath]; + if (!process.env.isFaMode) { + systemModulePathArray.push(arktsDirPath, kitsDirPath); + } + systemModulePathArray.forEach(systemModulesPath => { + if (fs.existsSync(systemModulesPath)) { + const modulePaths = []; + readFile(systemModulesPath, modulePaths); + DeclfileProductor.systemModules.push(...fs.readdirSync(systemModulesPath)); + const moduleSubdir = modulePaths.filter(filePath => { + const dirName = path.dirname(filePath); + return !(dirName === apiDirPath || dirName === arktsDirPath || dirName === kitsDirPath); + }).map(filePath => { + return filePath + .replace(apiDirPath, '') + .replace(arktsDirPath, '') + .replace(kitsDirPath, '') + .replace(/(^\\)|(.d.e?ts$)/g, '') + .replace(/\\/g, '/'); + }); + } + }); + DeclfileProductor.defaultSdkConfigs = [ + { + 'apiPath': systemModulePathArray, + 'prefix': '@ohos' + }, { + 'apiPath': systemModulePathArray, + 'prefix': '@system' + }, { + 'apiPath': systemModulePathArray, + 'prefix': '@arkts' + } + ]; + DeclfileProductor.sdkConfigs = [...DeclfileProductor.defaultSdkConfigs]; + } +} + +function resolveModuleNames(moduleNames: string[], containingFile: string): ts.ResolvedModuleFull[] { + const resolvedModules: ts.ResolvedModuleFull[] = []; + + for (const moduleName of moduleNames) { + let resolvedModule: ts.ResolvedModuleFull | null = null; + + resolvedModule = resolveWithDefault(moduleName, containingFile); + if (resolvedModule) { + resolvedModules.push(resolvedModule); + continue; + } + + resolvedModule = resolveSdkModule(moduleName); + if (resolvedModule) { + resolvedModules.push(resolvedModule); + continue; + } + + resolvedModule = resolveEtsModule(moduleName, containingFile); + if (resolvedModule) { + resolvedModules.push(resolvedModule); + continue; + } + + resolvedModule = resolveTsModule(moduleName, containingFile); + if (resolvedModule) { + resolvedModules.push(resolvedModule); + continue; + } + + resolvedModule = resolveOtherModule(moduleName, containingFile); + resolvedModules.push(resolvedModule ?? null); + } + + return resolvedModules; +} + +function resolveWithDefault( + moduleName: string, + containingFile: string +): ts.ResolvedModuleFull | null { + const result = ts.resolveModuleName(moduleName, containingFile, DeclfileProductor.compilerOptions, moduleResolutionHost); + if (!result.resolvedModule) { + return null; + } + + const resolvedFileName = result.resolvedModule.resolvedFileName; + if (resolvedFileName && path.extname(resolvedFileName) === EXTNAME_JS) { + const resultDETSPath = resolvedFileName.replace(EXTNAME_JS, EXTNAME_D_ETS); + if (ts.sys.fileExists(resultDETSPath)) { + return getResolveModule(resultDETSPath, EXTNAME_D_ETS); + } + } + + return result.resolvedModule; +} + +function resolveEtsModule(moduleName: string, containingFile: string): ts.ResolvedModuleFull | null { + if (!/\.ets$/.test(moduleName) || /\.d\.ets$/.test(moduleName)) { + return null; + } + + const modulePath = path.resolve(path.dirname(containingFile), moduleName); + return ts.sys.fileExists(modulePath) ? getResolveModule(modulePath, '.ets') : null; +} + +function resolveSdkModule(moduleName: string): ts.ResolvedModuleFull | null { + const prefixRegex = new RegExp(`^@(${DeclfileProductor.sdkConfigPrefix})\\.`, 'i'); + if (!prefixRegex.test(moduleName.trim())) { + return null; + } + + for (const sdkConfig of DeclfileProductor.sdkConfigs) { + const resolveModuleInfo: ResolveModuleInfo = getRealModulePath(sdkConfig.apiPath, moduleName, ['.d.ts', '.d.ets']); + const modulePath: string = resolveModuleInfo.modulePath; + const isDETS: boolean = resolveModuleInfo.isEts; + + const moduleKey = moduleName + (isDETS ? '.d.ets' : '.d.ts'); + if (DeclfileProductor.systemModules.includes(moduleKey) && ts.sys.fileExists(modulePath)) { + return getResolveModule(modulePath, isDETS ? '.d.ets' : '.d.ts'); + } + } + + return null; +} + +function resolveTsModule(moduleName: string, containingFile: string): ts.ResolvedModuleFull | null { + if (!/\.ts$/.test(moduleName)) { + return null; + } + + + const modulePath = path.resolve(path.dirname(containingFile), moduleName); + return ts.sys.fileExists(modulePath) ? getResolveModule(modulePath, '.ts') : null; +} + +function resolveOtherModule(moduleName: string, containingFile: string): ts.ResolvedModuleFull | null { + const apiModulePath = path.resolve(__dirname, '../../../api', moduleName + '.d.ts'); + const systemDETSModulePath = path.resolve(__dirname, '../../../api', moduleName + '.d.ets'); + const kitModulePath = path.resolve(__dirname, '../../../kits', moduleName + '.d.ts'); + const kitSystemDETSModulePath = path.resolve(__dirname, '../../../kits', moduleName + '.d.ets'); + const jsModulePath = path.resolve(__dirname, '../node_modules', moduleName + (moduleName.endsWith('.js') ? '' : '.js')); + const fileModulePath = path.resolve(__dirname, '../node_modules', moduleName + '/index.js'); + const DETSModulePath = path.resolve(path.dirname(containingFile), + moduleName.endsWith('.d.ets') ? moduleName : moduleName + EXTNAME_D_ETS); + + if (ts.sys.fileExists(apiModulePath)) { + return getResolveModule(apiModulePath, '.d.ts'); + } else if (ts.sys.fileExists(systemDETSModulePath)) { + return getResolveModule(systemDETSModulePath, '.d.ets'); + } else if (ts.sys.fileExists(kitModulePath)) { + return getResolveModule(kitModulePath, '.d.ts'); + } else if (ts.sys.fileExists(kitSystemDETSModulePath)) { + return getResolveModule(kitSystemDETSModulePath, '.d.ets'); + } else if (ts.sys.fileExists(jsModulePath)) { + return getResolveModule(jsModulePath, '.js'); + } else if (ts.sys.fileExists(fileModulePath)) { + return getResolveModule(fileModulePath, '.js'); + } else if (ts.sys.fileExists(DETSModulePath)) { + return getResolveModule(DETSModulePath, '.d.ets'); + } else { + const srcIndex = DeclfileProductor.projectPath.indexOf('src' + path.sep + 'main'); + if (srcIndex > 0) { + const DETSModulePathFromModule = path.resolve( + DeclfileProductor.projectPath.substring(0, srcIndex), + moduleName + path.sep + 'index' + EXTNAME_D_ETS + ); + if (ts.sys.fileExists(DETSModulePathFromModule)) { + return getResolveModule(DETSModulePathFromModule, '.d.ets'); + } + } + return null; + } +} + +function getRelativePath(filePath: string, pkgPath: string): string { + // rollup uses commonjs plugin to handle commonjs files, + // the commonjs files are prefixed with '\x00' and need to be removed. + if (filePath.startsWith('\x00')) { + filePath = filePath.replace('\x00', ''); + } + let unixFilePath: string = toUnixPath(filePath); + + // Handle .d.ets and .d.ts extensions + const dEtsIndex = unixFilePath.lastIndexOf('.d.ets'); + const dTsIndex = unixFilePath.lastIndexOf('.d.ts'); + + if (dEtsIndex !== -1) { + unixFilePath = unixFilePath.substring(0, dEtsIndex); + } else if (dTsIndex !== -1) { + unixFilePath = unixFilePath.substring(0, dTsIndex); + } else { + // Fallback to regular extension removal if not a .d file + const lastDotIndex = unixFilePath.lastIndexOf('.'); + if (lastDotIndex !== -1) { + unixFilePath = unixFilePath.substring(0, lastDotIndex); + } + } + + const projectFilePath: string = unixFilePath.replace(toUnixPath(pkgPath) + '/', ''); + return projectFilePath; +} + +const moduleResolutionHost: ts.ModuleResolutionHost = { + fileExists: (fileName: string): boolean => { + let exists = ts.sys.fileExists(fileName); + if (exists === undefined) { + exists = ts.sys.fileExists(fileName); + } + return exists; + }, + + readFile(fileName: string): string | undefined { + return ts.sys.readFile(fileName); + }, + realpath(path: string): string { + return ts.sys.realpath(path); + }, + trace(s: string): void { + console.info(s); + } +}; \ No newline at end of file diff --git a/compiler/src/fast_build/ark_compiler/interop/type.ts b/compiler/src/fast_build/ark_compiler/interop/type.ts index 66deaf308..132f76602 100644 --- a/compiler/src/fast_build/ark_compiler/interop/type.ts +++ b/compiler/src/fast_build/ark_compiler/interop/type.ts @@ -13,6 +13,8 @@ * limitations under the License. */ +import * as ts from 'typescript'; + export interface ArkTSEvolutionModule { language: string; packageName: string; @@ -26,6 +28,7 @@ export interface ArkTSEvolutionModule { staticFiles: string[]; cachePath: string; byteCodeHarInfo?: Object; + packageVersion: string; } export const ARKTS_1_2: string = '1.2'; @@ -39,14 +42,14 @@ export interface Params { tasks: taskInfo[]; } -interface ProjectConfig { +export interface ProjectConfig { cachePath: string; bundleName: string; mainModuleName: string; projectRootPath: string; }; -enum BuildType { +export enum BuildType { DECLGEN = 'declgen', BYTE_CODE_HAR = 'byteCodeHar', INTEROP_CONTEXT = 'interopContext' @@ -55,6 +58,7 @@ enum BuildType { interface taskInfo { packageName: string; buildTask: BuildType; + mainModuleName?: string; } export interface AliasConfig { @@ -66,4 +70,27 @@ export interface FileInfo { recordName: string; baseUrl: string; absolutePath: string; + abstractPath: string; +} + +export interface RunnerParms { + inputDirs: string[]; + inputFiles: string[]; + outDir: string; + rootDir: string; + customResolveModuleNames?: (moduleName: string[], containingFile: string) => ts.ResolvedModuleFull[]; + customCompilerOptions?: ts.CompilerOptions; + includePaths?: string[]; +} + +export interface DeclFilesConfig { + packageName: string; + files: { + [filePath: string]: DeclFileConfig; + } +} + +interface DeclFileConfig { + declPath: string; + ohmUrl: string; } \ No newline at end of file diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts index e058778ec..562661f77 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_mode.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -100,6 +100,7 @@ import { } from '../../../gen_aot'; import { ARKTS_1_2, + ARKTS_HYBRID, NATIVE_MODULE } from '../../../pre_define'; import { @@ -122,7 +123,8 @@ import { ArkTSEvolutionModule, getDeclgenBridgeCodePath, pkgDeclFilesConfig, - arkTSModuleMap + arkTSModuleMap, + isArkTSEvolutionFile } from '../../../process_arkts_evolution'; export class ModuleInfo { @@ -250,9 +252,9 @@ export class ModuleMode extends CommonMode { ); this.logger.printErrorAndExit(errInfo); } - const isArkTSEvolution: boolean = metaInfo.language === ARKTS_1_2; + const isArkTSEvolution: boolean = isArkTSEvolutionFile(moduleId, metaInfo); const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(metaInfo.pkgName), metaInfo.moduleName) : metaInfo.pkgPath; + path.join(getDeclgenBridgeCodePath(metaInfo.pkgName), metaInfo.pkgName) : metaInfo.pkgPath; const pkgParams = { pkgName: metaInfo.pkgName, pkgPath, @@ -519,15 +521,15 @@ export class ModuleMode extends CommonMode { let moduleName: string = metaInfo.moduleName; let recordName: string = ''; - let cacheFilePath: string = metaInfo.language === ARKTS_1_2 ? originalFilePath : + let cacheFilePath: string = isArkTSEvolutionFile(filePath, metaInfo) ? originalFilePath : this.genFileCachePath(filePath, this.projectConfig.projectRootPath, this.projectConfig.cachePath, metaInfo); let packageName: string = ''; if (this.useNormalizedOHMUrl) { packageName = metaInfo.pkgName; - const isArkTSEvolution: boolean = metaInfo.language === ARKTS_1_2; + const isArkTSEvolution: boolean = isArkTSEvolutionFile(filePath, metaInfo); const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(packageName), metaInfo.moduleName) : metaInfo.pkgPath; + path.join(getDeclgenBridgeCodePath(packageName), metaInfo.pkgName) : metaInfo.pkgPath; const pkgParams = { pkgName: packageName, pkgPath, diff --git a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts index fd3cd73f3..8d9771f04 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts @@ -53,6 +53,7 @@ import { import { ORIGIN_EXTENTION } from '../process_mock'; import { ARKTS_1_2, + ARKTS_HYBRID, ESMODULE, TRANSFORMED_MOCK_CONFIG, USER_DEFINE_MOCK_CONFIG @@ -81,7 +82,8 @@ import { import { checkIfJsImportingArkts } from '../check_import_module'; import { getDeclgenBridgeCodePath, - writeBridgeCodeFileSyncByNode + writeBridgeCodeFileSyncByNode, + isArkTSEvolutionFile } from '../../../process_arkts_evolution'; const ROLLUP_IMPORT_NODE: string = 'ImportDeclaration'; @@ -117,7 +119,7 @@ export class ModuleSourceFile { if (typeof this.source !== 'string') { this.isSourceNode = true; } - if (metaInfo?.language === ARKTS_1_2) { + if (metaInfo?.language === ARKTS_1_2 || (metaInfo && isArkTSEvolutionFile(moduleId, metaInfo))) { this.isArkTSEvolution = true; } } @@ -508,9 +510,9 @@ export class ModuleSourceFile { } private static spliceNormalizedOhmurl(moduleInfo: Object, filePath: string, importerFile?: string): string { - const isArkTSEvolution: boolean = moduleInfo.meta.language === ARKTS_1_2; + const isArkTSEvolution: boolean = isArkTSEvolutionFile(filePath, moduleInfo.meta); const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(moduleInfo.meta.pkgName), moduleInfo.meta.moduleName) : moduleInfo.meta.pkgPath; + path.join(getDeclgenBridgeCodePath(moduleInfo.meta.pkgName), moduleInfo.meta.pkgName) : moduleInfo.meta.pkgPath; const pkgParams = { pkgName: moduleInfo.meta.pkgName, pkgPath, diff --git a/compiler/src/fast_build/common/process_project_config.ts b/compiler/src/fast_build/common/process_project_config.ts index ac205bf34..82da9bbf0 100644 --- a/compiler/src/fast_build/common/process_project_config.ts +++ b/compiler/src/fast_build/common/process_project_config.ts @@ -38,7 +38,11 @@ export function getEntryObj() { } projectConfig.entryObj = Object.keys(projectConfig.entryObj).reduce((newEntry, key) => { const newKey: string = key.replace(/^\.\//, ''); - newEntry[newKey] = projectConfig.entryObj[key].replace('?entry', ''); + const filePath = projectConfig.entryObj[key].replace('?entry', ''); + const firstLine = fs.readFileSync(filePath, 'utf-8').split('\n')[0]; + if (!firstLine.includes('use static')) { + newEntry[newKey] = filePath; + } return newEntry; }, {}); } diff --git a/compiler/src/pre_define.ts b/compiler/src/pre_define.ts index 5da8a4c27..354c315bc 100644 --- a/compiler/src/pre_define.ts +++ b/compiler/src/pre_define.ts @@ -648,4 +648,5 @@ export const INTEGRATED_HSP: string = 'integratedHsp'; export const ARKTS_1_2: string = '1.2'; export const ARKTS_1_1: string = '1.1'; -export const ARKTS_1_0: string = '1.0'; \ No newline at end of file +export const ARKTS_1_0: string = '1.0'; +export const ARKTS_HYBRID: string = 'hybrid'; \ No newline at end of file diff --git a/compiler/src/process_arkts_evolution.ts b/compiler/src/process_arkts_evolution.ts index 63eb61e39..f4c1b5baf 100644 --- a/compiler/src/process_arkts_evolution.ts +++ b/compiler/src/process_arkts_evolution.ts @@ -23,6 +23,7 @@ import { ARKTS_1_0, ARKTS_1_1, ARKTS_1_2, + ARKTS_HYBRID, SUPER_ARGS } from './pre_define'; import { @@ -118,7 +119,8 @@ export function addDeclFilesConfig(filePath: string, projectConfig: Object, logg export function getArkTSEvoDeclFilePath(resolvedFileInfo: ResolvedFileInfo): string { const { moduleRequest, resolvedFileName } = resolvedFileInfo; let arktsEvoDeclFilePath: string = moduleRequest; - for (const [pkgName, arkTSEvolutionModuleInfo] of arkTSEvolutionModuleMap) { + const combinedMap = new Map([...arkTSEvolutionModuleMap, ...arkTSHybridModuleMap]); + for (const [pkgName, arkTSEvolutionModuleInfo] of combinedMap) { const declgenV1OutPath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenV1OutPath); const modulePath: string = toUnixPath(arkTSEvolutionModuleInfo.modulePath); const declgenBridgeCodePath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenBridgeCodePath); @@ -153,23 +155,36 @@ export function collectArkTSEvolutionModuleInfo(share: Object): void { // dependentModuleMap Contents eg. // 1.2 hap -> 1.1 har: It contains the information of 1.1 har // 1.1 hap -> 1.2 har -> 1.1 har : There is information about 3 modules. + + const throwCollectionError = (pkgName: string): void => { + share.throwArkTsCompilerError(red, 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + + `Error Message: Failed to collect arkTs evolution module "${pkgName}" info from rollup.`, reset); + }; + for (const [pkgName, dependentModuleInfo] of share.projectConfig.dependentModuleMap) { - if (dependentModuleInfo.language === ARKTS_1_2) { - if (dependentModuleInfo.declgenV1OutPath && dependentModuleInfo.declgenBridgeCodePath) { - arkTSEvolutionModuleMap.set(pkgName, dependentModuleInfo); - } else { - share.throwArkTsCompilerError(red, 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + - `Error Message: Failed to collect arkTs evolution module "${pkgName}" info from rollup.`, reset); - } - } else if (dependentModuleInfo.language === ARKTS_1_1 || dependentModuleInfo.language === ARKTS_1_0) { - if (dependentModuleInfo.declgenV2OutPath && dependentModuleInfo.declFilesPath) { - arkTSModuleMap.set(pkgName, dependentModuleInfo); - } else { - share.throwArkTsCompilerError(red, 'ArkTS:INTERNAL ERROR: Failed to collect arkTs evolution module info.\n' + - `Error Message: Failed to collect arkTs evolution module "${pkgName}" info from rollup.`, reset); - } - } else { - arkTSHybridModuleMap.set(pkgName, dependentModuleInfo); + switch (dependentModuleInfo.language) { + case ARKTS_1_2: + if (dependentModuleInfo.declgenV1OutPath && dependentModuleInfo.declgenBridgeCodePath) { + arkTSEvolutionModuleMap.set(pkgName, dependentModuleInfo); + } else { + throwCollectionError(pkgName); + } + break; + case ARKTS_HYBRID: + if (dependentModuleInfo.declgenV2OutPath && dependentModuleInfo.declFilesPath && dependentModuleInfo.declgenBridgeCodePath) { + arkTSHybridModuleMap.set(pkgName, dependentModuleInfo); + } else { + throwCollectionError(pkgName); + } + break; + case ARKTS_1_1: + case ARKTS_1_0: + if (dependentModuleInfo.declgenV2OutPath && dependentModuleInfo.declFilesPath) { + arkTSModuleMap.set(pkgName, dependentModuleInfo); + } else { + throwCollectionError(pkgName); + } + break; } } } @@ -197,21 +212,47 @@ export async function writeBridgeCodeFileSyncByNode(node: ts.SourceFile, moduleI } export function getDeclgenBridgeCodePath(pkgName: string): string { - if (arkTSEvolutionModuleMap.size && arkTSEvolutionModuleMap.get(pkgName)) { - const arkTSEvolutionModuleInfo: ArkTSEvolutionModule = arkTSEvolutionModuleMap.get(pkgName); + const combinedMap = new Map([...arkTSEvolutionModuleMap, ...arkTSHybridModuleMap]); + if (combinedMap.size && combinedMap.get(pkgName)) { + const arkTSEvolutionModuleInfo: ArkTSEvolutionModule = combinedMap.get(pkgName); return arkTSEvolutionModuleInfo.declgenBridgeCodePath; } return ''; } function getDeclgenV2OutPath(pkgName: string): string { - if (arkTSModuleMap.size && arkTSModuleMap.get(pkgName)) { - const arkTsModuleInfo: ArkTSEvolutionModule = arkTSModuleMap.get(pkgName); + const combinedMap = new Map([...arkTSModuleMap, ...arkTSHybridModuleMap]); + if (combinedMap.size && combinedMap.get(pkgName)) { + const arkTsModuleInfo: ArkTSEvolutionModule = combinedMap.get(pkgName); return arkTsModuleInfo.declgenV2OutPath; } return ''; } +export function isArkTSEvolutionFile(filePath: string, metaInfo: Object): boolean { + if (metaInfo.language === ARKTS_1_0 || metaInfo.language === ARKTS_1_1) { + return false; + } + + if (metaInfo.language === ARKTS_1_2) { + return true; + } + + if (metaInfo.language === ARKTS_HYBRID || arkTSHybridModuleMap.has(metaInfo.pkgName)) { + const hybridModule = arkTSHybridModuleMap.get(metaInfo.pkgName); + if (!hybridModule) { + return false; + } + + const normalizedFilePath = toUnixPath(filePath); + const staticFileList = hybridModule.staticFiles || []; + + return new Set(staticFileList.map(toUnixPath)).has(normalizedFilePath); + } + + return false; +} + export function interopTransform(program: ts.Program, id: string, mixCompile: boolean): ts.TransformerFactory { if (!mixCompile || /\.ts$/.test(id)) { return () => sourceFile => sourceFile; @@ -250,7 +291,8 @@ export function interopTransform(program: ts.Program, id: string, mixCompile: bo function isFromArkTSEvolutionModule(node: ts.Node): boolean { const sourceFile: ts.SourceFile = node.getSourceFile(); const filePath: string = toUnixPath(sourceFile.fileName); - for (const arkTSEvolutionModuleInfo of arkTSEvolutionModuleMap.values()) { + const combinedMap = new Map([...arkTSEvolutionModuleMap, ...arkTSHybridModuleMap]); + for (const arkTSEvolutionModuleInfo of combinedMap.values()) { const declgenV1OutPath: string = toUnixPath(arkTSEvolutionModuleInfo.declgenV1OutPath); if (filePath.startsWith(declgenV1OutPath + '/')) { const relative: string = filePath.replace(declgenV1OutPath + '/', '').replace(/\.d\.ets$/, ''); -- Gitee From 0ea99aede72717c1ce87bc20dba0d66f3c37da69 Mon Sep 17 00:00:00 2001 From: wangweiyuan Date: Thu, 29 May 2025 15:07:19 +0800 Subject: [PATCH 111/123] add ui-syntax-plugins 6/22 Signed-off-by: wangweiyuan --- .../rules/check-decorated-property-type.ts | 63 +++--- .../rules/nested-relationship.ts | 196 +++++++++-------- .../rules/nested-reuse-component-check.ts | 200 ++++++++++++++++++ .../rules/no-duplicate-entry.ts | 59 ++++-- .../rules/no-duplicate-preview.ts | 74 ++++--- .../ui-syntax-plugins/utils/index.ts | 47 ++++ 6 files changed, 459 insertions(+), 180 deletions(-) create mode 100644 arkui-plugins/ui-syntax-plugins/rules/nested-reuse-component-check.ts diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts b/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts index 8448fa435..d8f8f0dd9 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts @@ -16,58 +16,73 @@ import * as arkts from '@koalaui/libarkts'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; import { + forbiddenUseStateType, getAnnotationUsage, getClassPropertyAnnotationNames, getClassPropertyName, getClassPropertyType, PresetDecorators } from '../utils'; +const forbiddenUseStateTypeForDecorators: string[] = [ + PresetDecorators.STATE, + PresetDecorators.PROP, + PresetDecorators.LINK, + PresetDecorators.PROVIDE, + PresetDecorators.CONSUME, + PresetDecorators.OBJECT_LINK, + PresetDecorators.BUILDER_PARAM, + PresetDecorators.STORAGE_PROP, + PresetDecorators.STORAGE_LINK, + PresetDecorators.LOCAL_STORAGE_PROP, + PresetDecorators.LOCAL_STORAGE_LINK, +]; + function checkDecoratedPropertyType( member: arkts.AstNode, context: UISyntaxRuleContext, - relationship: Record + annoList: string[], + typeList: string[] ): void { if (!arkts.isClassProperty(member)) { return; } - const propertyName = getClassPropertyName(member); - const propertyType = getClassPropertyType(member); - const propertyAnnotationNames = getClassPropertyAnnotationNames(member); - Object.entries(relationship).forEach(([decoratorName, invalidPropertyTypes]) => { - if (propertyAnnotationNames.some(annotationName => annotationName === decoratorName) && - invalidPropertyTypes - .some(invalidPropertyType => invalidPropertyType === propertyType)) { - if (!arkts.isClassProperty || member.key === undefined) { - return; - } - const errorNode = member.key; - context.report({ - node: errorNode, - message: rule.messages.invalidDecoratedPropertyType, - data: { decoratorName, propertyName, propertyType }, - }); - } - }); + const propertyName: string = getClassPropertyName(member); + const propertyType: string = getClassPropertyType(member); + const propertyAnnotationNames: string[] = getClassPropertyAnnotationNames(member); + const decoratorName: string | undefined = + propertyAnnotationNames.find((annotation) => annoList.includes(annotation)); + const isType: boolean = typeList.includes(propertyType); + if (!member.key) { + return; + } + const errorNode = member.key; + if (decoratorName && isType) { + context.report({ + node: errorNode, + message: rule.messages.invalidDecoratedPropertyType, + data: { decoratorName, propertyName, propertyType }, + }); + } } const rule: UISyntaxRule = { name: 'check-decorated-property-type', messages: { - invalidDecoratedPropertyType: `The {{decoratorName}} property '{{propertyName}}' cannot be a '{{propertyType}}' object.`, + invalidDecoratedPropertyType: `The '@{{decoratorName}}' property '{{propertyName}}' cannot be a '{{propertyType}}' object.`, }, setup(context) { - const relationship: Record = { - [PresetDecorators.STATE]: ['CustomDialogController'], - }; return { parsed: (node): void => { if (!arkts.isStructDeclaration(node)) { return; } + if (!node.definition) { + return; + } const componentDecorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); if (!componentDecorator) { return; } node.definition.body.forEach(member => { - checkDecoratedPropertyType(member, context, relationship); + checkDecoratedPropertyType(member, context, forbiddenUseStateTypeForDecorators, forbiddenUseStateType); }); }, }; diff --git a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts index fd18100e9..18f8273e0 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts @@ -14,53 +14,106 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getIdentifierName } from '../utils'; +import { + getIdentifierName, + isAtomicComponent, + isBuildInComponent, + isSingleChildComponent, + listToString, + SINGLE_CHILD_COMPONENT +} from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -function checkInvalidChildInText(node: arkts.AstNode, context: UISyntaxRuleContext, textChild: string[]): void { - // Check if the current node is an identifier, and name is 'Text' +function checkValidParentComponent(node: arkts.AstNode, context: UISyntaxRuleContext,): void { + // Check if the node is an identifier and if there are any restrictions on the parent component if (!arkts.isIdentifier(node)) { return; } - if (getIdentifierName(node) !== 'Text') { + const componentName: string = getIdentifierName(node); + if (!context.componentsInfo.validParentComponent.has(componentName) || !node.parent || !node.parent.parent) { return; } - if (!node.parent) { + let curNode = node.parent.parent; + while (!arkts.isCallExpression(curNode) || !arkts.isIdentifier(curNode.expression) || + !isBuildInComponent(context, curNode.expression.name)) { + if (!curNode.parent) { + return; + } + curNode = curNode.parent; + } + // If the parent component of the current component is not within the valid range, an error is reported + const parentComponentName = curNode.expression.name; + if (!context.componentsInfo.validParentComponent.get(componentName)!.includes(parentComponentName)) { + context.report({ + node: node, + message: rule.messages.delegateChildrenComponentChildren, + data: { + childComponentName: componentName, + parentComponentName: parentComponentName, + }, + }); + const parentComponentListArray: string[] = context.componentsInfo.validParentComponent.get(componentName)!; + const parentComponentList: string = listToString(parentComponentListArray); + context.report({ + node: node, + message: rule.messages.delegateParentComponent, + data: { + componentName: componentName, + parentComponentList: parentComponentList, + }, + }); + } +} + +function checkValidChildComponent(node: arkts.AstNode, context: UISyntaxRuleContext): void { + // Check whether the node is an identifier and whether there are restrictions on subcomponents + if (!arkts.isIdentifier(node)) { return; } - const parentNode = node.parent; - if (!arkts.isCallExpression(parentNode)) { + const parentComponentName: string = getIdentifierName(node); + if (!context.componentsInfo.validChildComponent.has(parentComponentName) || !node.parent) { return; } - // If the BlockStatement contains a child component that should not exist under the text, an error will be reported + let parentNode = node.parent; + if (!arkts.isCallExpression(parentNode) || !arkts.isIdentifier(parentNode.expression)) { + return; + } + // If the BlockStatement contains a child component that should not exist under the component, an error will be reported parentNode.getChildren().forEach(member => { if (!arkts.isBlockStatement(member)) { return; } - member.getChildren().forEach(sibling => { - if (!arkts.isExpressionStatement(sibling) || !arkts.isCallExpression(sibling.expression)) { + member.statements.forEach(statement => { + if (!arkts.isExpressionStatement(statement) || !statement.expression) { return; } - const childComponentName = sibling.expression.expression.dumpSrc(); - if (!textChild.includes(childComponentName)) { + if (!arkts.isCallExpression(statement.expression) || !statement.expression.expression || + !arkts.isIdentifier(statement.expression.expression)) { + return; + } + const componentName = getIdentifierName(statement.expression.expression); + const childComponentListArray: string[] = context.componentsInfo.validChildComponent.get(parentComponentName)!; + if (!childComponentListArray.includes(componentName) && isBuildInComponent(context, componentName)) { + const childComponentList: string = listToString(childComponentListArray); context.report({ - node: node, - message: rule.messages.invalidChildInText + node: parentNode, + message: rule.messages.delegateChildrenComponentParent, + data: { + parentComponentName: parentComponentName, + childComponentList: childComponentList, + }, }); - return; } }); }); } -function checkOneChildInButton(node: arkts.AstNode, context: UISyntaxRuleContext): void { - // Check if the current node is an identifier, and name is 'Button' +function checkSingleChildComponent(node: arkts.AstNode, context: UISyntaxRuleContext): void { + // Check whether the current node is an identifier and a single subcomponent container if (!arkts.isIdentifier(node)) { return; } - if (getIdentifierName(node) !== 'Button') { - return; - } - if (!node.parent) { + const componentName: string = getIdentifierName(node); + if (!isSingleChildComponent(context, componentName) || !node.parent) { return; } const parentNode = node.parent; @@ -72,117 +125,60 @@ function checkOneChildInButton(node: arkts.AstNode, context: UISyntaxRuleContext if (!arkts.isBlockStatement(member)) { return; } - if (member.statements.length > 1) { + if (member.statements.length > SINGLE_CHILD_COMPONENT) { context.report({ node: node, - message: rule.messages.oneChildInButton + message: rule.messages.singleChildComponent, + data: { componentName: componentName } }); } }); } -function checkListItem(node: arkts.AstNode, context: UISyntaxRuleContext): void { - // Check if the current node is an identifier, and name is 'ListItem' +function checkNoChildComponent(node: arkts.AstNode, context: UISyntaxRuleContext): void { + // Check whether the current node is an identifier and an atomic component if (!arkts.isIdentifier(node)) { return; } - if (getIdentifierName(node) !== 'ListItem') { - return; - } - if (!node.parent || !node.parent.parent) { - return; - } - let curNode: arkts.AstNode = node.parent.parent; - do { - while (!arkts.isCallExpression(curNode)) { - if (!curNode.parent) { - return; - } - curNode = curNode.parent; - } - const parentName: string = curNode.expression.dumpSrc(); - if (parentName === 'List') { // If the parent component's name is 'List', exit directly - break; - } else if (parentName !== 'ForEach') { // If the parent component's name is not 'List' or 'ForEach', throw an error - context.report({ - node: node, - message: rule.messages.listItemCannotInOther, - data: { parentName: parentName } - }); - context.report({ - node: node, - message: rule.messages.listItemMustInList - }); - break; - } - // In the remaining case, the parent component is 'ForEach', continue traversing upwards for further checks - if (!curNode.parent) { - return; - } - curNode = curNode.parent; - } while (true); -} - -function checkSpan(node: arkts.AstNode, context: UISyntaxRuleContext): void { - // Check if the current node is an identifier, and name is 'Span' - if (!arkts.isIdentifier(node)) { - return; - } - if (getIdentifierName(node) !== 'Span') { + const componentName: string = getIdentifierName(node); + if (!isAtomicComponent(context, componentName) || !node.parent) { return; } let parentNode = node.parent; if (!arkts.isCallExpression(parentNode)) { return; } - // If there are subcomponents in the BlockStatement, an error is reported - parentNode.getChildren().forEach(sibling => { - if (!arkts.isBlockStatement(sibling)) { + // If there are child components in arguments, an error will be reported + parentNode.getChildren().forEach(member => { + if (!arkts.isBlockStatement(member)) { return; } - if (sibling.statements.length > 0) { + if (member.statements.length > 0) { context.report({ node: node, - message: rule.messages.noChildInSpan + message: rule.messages.noChildComponent, + data: { componentName: componentName } }); } }); - if (!node.parent || !node.parent.parent) { - return; - } - parentNode = parentNode.parent; - while (!arkts.isCallExpression(parentNode)) { - parentNode = parentNode.parent; - } - const parentName: string = parentNode.expression.dumpSrc(); - // If the name of the parent component is not 'Text', an error is reported - if (parentName !== 'Text' && parentName !== 'RichEditor' && parentName !== 'ContainerSpan') { - context.report({ - node: node, - message: rule.messages.spanMustInText - }); - } } -// The 'Text' component can have only the Span, ImageSpan, ContainerSpan and SymbolSpan child component. const rule: UISyntaxRule = { name: 'nested-relationship', messages: { - invalidChildInText: `The 'Text' component can have only the Span, ImageSpan, ContainerSpan and SymbolSpan child component.`, - oneChildInButton: `The 'Button' component can have only one child component.`, - listItemMustInList: `The 'ListItem' component can only be nested in the List and ListItemGroup parent component.`, - listItemCannotInOther: `The 'ListItem' component cannot be a child component of the '{{parentName}}' component.`, - noChildInSpan: `No child component is allowed in the 'Span' component. `, - spanMustInText: `The 'Span' component can only be nested in the Text, RichEditor and ContainerSpan parent component. `, + noChildComponent: `No child component is allowed in the '{{componentName}}' component.`, + singleChildComponent: `The '{{componentName}}' component can have only one child component.`, + delegateChildrenComponentChildren: `The '{{childComponentName}}' component cannot be a child component of the '{{parentComponentName}}' component.`, + delegateChildrenComponentParent: `The component '{{parentComponentName}}' can only have the child component {{childComponentList}}.`, + delegateParentComponent: `The '{{componentName}}' component can only be nested in the {{parentComponentList}} parent component.`, }, setup(context) { - const textChild: string[] = ['Span', 'ImageSpan', 'ContainerSpan', 'SymbolSpan']; return { parsed: (node): void => { - checkInvalidChildInText(node, context, textChild); - checkOneChildInButton(node, context); - checkListItem(node, context); - checkSpan(node, context); + checkValidParentComponent(node, context); + checkValidChildComponent(node, context); + checkSingleChildComponent(node, context); + checkNoChildComponent(node, context); }, }; }, diff --git a/arkui-plugins/ui-syntax-plugins/rules/nested-reuse-component-check.ts b/arkui-plugins/ui-syntax-plugins/rules/nested-reuse-component-check.ts new file mode 100644 index 000000000..90d19982b --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/nested-reuse-component-check.ts @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { COMPONENT_REPEAT, getIdentifierName, PresetDecorators, TEMPLATE } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function initStructName(node: arkts.AstNode, reusableV2StructName: string[], reusableStructName: string[]): void { + if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + return; + } + //Go through all the children of Program + for (const childNode of node.getChildren()) { + // Check whether the type is struct + if (!arkts.isStructDeclaration(childNode)) { + return; + } + // Get a list of annotations + const annotationsList = childNode.definition.annotations; + // Check that the current component has @Reusable and @ReusableV2 decorators + if (annotationsList?.some((annotation: any) => annotation.expr.name === PresetDecorators.REUSABLE_V2)) { + const struceName = childNode.definition?.ident?.name || ''; + reusableV2StructName.push(struceName); + } else if (annotationsList?.some((annotation: any) => annotation.expr.name === PresetDecorators.REUSABLE_V1)) { + const struceName = childNode.definition?.ident?.name || ''; + reusableStructName.push(struceName); + } + } +} + +function reportNoReusableV2InRepeatTemplate(errorNode: arkts.AstNode, context: UISyntaxRuleContext): void { + context.report({ + node: errorNode, + message: rule.messages.noReusableV2InRepeatTemplate, + fix: (errorNode) => { + return { + range: [errorNode.startPosition, errorNode.endPosition], + code: '', + }; + } + }); +} + +function checkHasRepeatOrTemplate(node: arkts.CallExpression): { hasRepeat: boolean, hasTemplate: boolean } { + let hasRepeat: boolean = false; + let hasTemplate: boolean = false; + while (arkts.isCallExpression(node) && + node.expression && arkts.isMemberExpression(node.expression) && + node.expression.object && arkts.isCallExpression(node.expression.object)) { + if (arkts.isIdentifier(node.expression.property) && getIdentifierName(node.expression.property) === TEMPLATE) { + hasTemplate = true; + } + node = node.expression.object; + } + if (arkts.isCallExpression(node) && arkts.isIdentifier(node.expression)) { + hasRepeat = getIdentifierName(node.expression) === COMPONENT_REPEAT; + } + return { hasRepeat, hasTemplate }; +} + +function checkNoReusableV2InRepeatTemplate( + node: arkts.AstNode, + errorNode: arkts.AstNode, + context: UISyntaxRuleContext +): boolean { + if (!arkts.isCallExpression(node)) { + return false; + } + const flag = checkHasRepeatOrTemplate(node); + if (!flag.hasRepeat || !flag.hasTemplate) { + return false; + } + reportNoReusableV2InRepeatTemplate(errorNode, context); + return true; +} + +function reportNoReusableV1InReusableV2(node: arkts.AstNode, context: UISyntaxRuleContext): void { + context.report({ + node: node, + message: rule.messages.noReusableV1InReusableV2, + fix: (node) => { + return { + range: [node.startPosition, node.endPosition], + code: '', + }; + } + }); +} + +function checkNoReusableV1InReusableV2( + node: arkts.AstNode, + context: UISyntaxRuleContext, + reusableStructName: string[] +): void { + if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.expression)) { + return; + } + if (reusableStructName.includes(node.expression.name)) { + // Traverse upwards to find the custom component. + let struceNode: arkts.AstNode = node; + while (!arkts.isStructDeclaration(struceNode)) { + struceNode = struceNode.parent; + } + const annotationsList = struceNode.definition.annotations; + // Check that the current component is decorated by the @ComponentV2 decorator + if (annotationsList.some((annotation: any) => annotation.expr.name === PresetDecorators.REUSABLE_V2)) { + reportNoReusableV1InReusableV2(node, context); + } + } +} + +function reportNoReusableV2InReusableV1(node: arkts.AstNode, context: UISyntaxRuleContext): void { + context.report({ + node: node, + message: rule.messages.noReusableV2InReusableV1, + fix: (node) => { + return { + range: [node.startPosition, node.endPosition], + code: '', + }; + } + }); +} + +function reportNoReusableV2InComponentV1(node: arkts.AstNode, context: UISyntaxRuleContext): void { + context.report({ + node: node, + message: rule.messages.noReusableV2InComponentV1, + fix: (node) => { + return { + range: [node.startPosition, node.endPosition], + code: '', + }; + } + }); +} + +function checkNestedReuseComponent( + node: arkts.AstNode, + context: UISyntaxRuleContext, + reusableV2StructName: string[], +): void { + if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.expression)) { + return; + } + if (reusableV2StructName.includes(node.expression.name)) { + // Traverse upwards to find the custom component. + let struceNode: arkts.AstNode = node; + let hasReportedError = false; + while (!arkts.isStructDeclaration(struceNode)) { + struceNode = struceNode.parent; + if (!hasReportedError) { + hasReportedError = checkNoReusableV2InRepeatTemplate(struceNode, node, context); + } + } + // Gets a list of decorators for the current Struct + const annotationsList = struceNode.definition.annotations; + if (annotationsList?.some((annotation: any) => annotation.expr.name === PresetDecorators.REUSABLE_V1)) { + reportNoReusableV2InReusableV1(node, context); + } else if (annotationsList?.some((annotation: any) => annotation.expr.name === PresetDecorators.COMPONENT_V1)) { + reportNoReusableV2InComponentV1(node, context); + } + } +} + +const rule: UISyntaxRule = { + name: 'nested-reuse-component-check', + messages: { + noReusableV2InComponentV1: `A custom component decorated with @Component cannot contain child components decorated with @ReusableV2.`, + noReusableV2InReusableV1: `A custom component decorated with @Reusable cannot contain child components decorated with @ReusableV2.`, + noReusableV1InReusableV2: `A custom component decorated with @ReusableV2 cannot contain child components decorated with @Reusable.`, + noReusableV2InRepeatTemplate: `The template attribute of the Repeat component cannot contain any custom component decorated with @ReusableV2.`, + }, + setup(context) { + // Create arrays to store the components decorated with @ReusableV2 and @Reusable + let reusableV2StructName: string[] = []; + let reusableStructName: string[] = []; + return { + parsed: (node): void => { + initStructName(node, reusableV2StructName, reusableStructName); + checkNestedReuseComponent(node, context, reusableV2StructName); + checkNoReusableV1InReusableV2(node, context, reusableStructName); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts index 60c810180..5dc533729 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts @@ -14,56 +14,69 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, PresetDecorators } from '../utils'; +import { getAnnotationUsage, MAX_ENTRY_DECORATOR_COUNT, PresetDecorators } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -const MAX_ENTRY_DECORATOR_COUNT = 1; -function checkDuplicateEntry(node: arkts.AstNode, context: UISyntaxRuleContext): void { - if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { +function checkDuplicateEntry( + node: arkts.AstNode, + context: UISyntaxRuleContext, + entryDecoratorUsages: arkts.AnnotationUsage[], + entryData: { count: number } +): void { + if (!arkts.isStructDeclaration(node)) { return; } - let entryDecoratorUsages: arkts.AnnotationUsage[] = []; - node.getChildren().forEach((child) => { - if (!arkts.isStructDeclaration(child)) { - return; - } - const entryDecoratorUsage = getAnnotationUsage( - child, - PresetDecorators.ENTRY, - ); - if (entryDecoratorUsage) { - entryDecoratorUsages.push(entryDecoratorUsage); - } - }); + const entryDecoratorUsage = getAnnotationUsage( + node, + PresetDecorators.ENTRY, + ); + if (entryDecoratorUsage) { + entryDecoratorUsages.push(entryDecoratorUsage); + } // If more than one entry decorator is recorded, an error is reported if (entryDecoratorUsages.length <= MAX_ENTRY_DECORATOR_COUNT) { return; } - entryDecoratorUsages.forEach((entryDocoratorUsage) => { + if (entryData.count === MAX_ENTRY_DECORATOR_COUNT) { context.report({ - node: entryDocoratorUsage, + node: entryDecoratorUsages.at(0)!, message: rule.messages.duplicateEntry, fix: (entryDocoratorUsage) => { - const startPosition = arkts.getStartPosition(entryDocoratorUsage); - const endPosition = arkts.getEndPosition(entryDocoratorUsage); + const startPosition = entryDocoratorUsage.startPosition; + const endPosition = entryDocoratorUsage.endPosition; return { range: [startPosition, endPosition], code: '', }; } }); + } + context.report({ + node: entryDecoratorUsages.at(entryData.count)!, + message: rule.messages.duplicateEntry, + fix: (entryDocoratorUsage) => { + const startPosition = entryDocoratorUsage.startPosition; + const endPosition = entryDocoratorUsage.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + } }); + entryData.count++; } const rule: UISyntaxRule = { name: 'no-duplicate-entry', messages: { - duplicateEntry: `An ArkTS file can contain only one '@Entry' decorator.`, + duplicateEntry: `A page can't contain more then one '@Entry' decorator.`, }, setup(context) { + let entryDecoratorUsages: arkts.AnnotationUsage[] = []; + let entryData = { count: 1 }; return { parsed: (node): void => { - checkDuplicateEntry(node, context); + checkDuplicateEntry(node, context, entryDecoratorUsages, entryData); }, }; }, diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts index fe57d8f11..544c8155a 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts @@ -14,57 +14,65 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, PresetDecorators } from '../utils'; +import { getAnnotationUsage, MAX_PREVIEW_DECORATOR_COUNT, PresetDecorators } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -const MAX_PREVIEW_DECORATOR_COUNT = 10; +function reportError(context: UISyntaxRuleContext, errorNode: arkts.AnnotationUsage): void { + context.report({ + node: errorNode, + message: rule.messages.duplicateEntry, + fix: (previewDecoratorUsage) => { + const startPosition = previewDecoratorUsage.startPosition; + const endPosition = previewDecoratorUsage.endPosition; + return { + range: [startPosition, endPosition], + code: '', + }; + } + }); +} -function checkDuplicatePreview(node: arkts.AstNode, context: UISyntaxRuleContext): void { - if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { +function checkDuplicatePreview( + node: arkts.AstNode, + context: UISyntaxRuleContext, + previewDecoratorUsages: arkts.AnnotationUsage[], + previewData: { count: number }, +): void { + if (!arkts.isStructDeclaration(node)) { return; } - let previewDecoratorUsages: arkts.AnnotationUsage[] = []; - node.getChildren().forEach((child) => { - if (!arkts.isStructDeclaration(child)) { - return; - } - const previewDecoratorUsage = getAnnotationUsage( - child, - PresetDecorators.PREVIEW, - ); - if (previewDecoratorUsage) { - previewDecoratorUsages.push(previewDecoratorUsage); - } - }); - // If the number of preview decorators is greater than 10, an error is reported + const previewDecoratorUsage = getAnnotationUsage( + node, + PresetDecorators.PREVIEW, + ); + if (previewDecoratorUsage) { + previewDecoratorUsages.push(previewDecoratorUsage); + } + // If the number of preview decorators is less than 10, no error is reported if (previewDecoratorUsages.length <= MAX_PREVIEW_DECORATOR_COUNT) { return; } - previewDecoratorUsages.forEach((previewDecoratorUsage) => { - context.report({ - node: previewDecoratorUsage, - message: rule.messages.duplicateEntry, - fix: (previewDecoratorUsage) => { - const startPosition = arkts.getStartPosition(previewDecoratorUsage); - const endPosition = arkts.getEndPosition(previewDecoratorUsage); - return { - range: [startPosition, endPosition], - code: '', - }; - } + if (previewData.count === MAX_PREVIEW_DECORATOR_COUNT) { + previewDecoratorUsages.forEach((previewDecoratorUsage) => { + reportError(context, previewDecoratorUsage); }); - }); + } else { + reportError(context, previewDecoratorUsages.at(previewData.count)!); + } + previewData.count++; } const rule: UISyntaxRule = { name: 'no-duplicate-preview', messages: { - duplicateEntry: `An ArkTS file con contain at most 10 '@Preview' decorators.`, + duplicateEntry: `A page can contain at most 10 '@Preview' decorators.`, }, setup(context) { + let previewDecoratorUsages: arkts.AnnotationUsage[] = []; + let previewData = { count: 10 }; return { parsed: (node): void => { - checkDuplicatePreview(node, context); + checkDuplicatePreview(node, context, previewDecoratorUsages, previewData); }, }; }, diff --git a/arkui-plugins/ui-syntax-plugins/utils/index.ts b/arkui-plugins/ui-syntax-plugins/utils/index.ts index 87ba336a7..0cc5c13d3 100644 --- a/arkui-plugins/ui-syntax-plugins/utils/index.ts +++ b/arkui-plugins/ui-syntax-plugins/utils/index.ts @@ -17,6 +17,46 @@ import * as arkts from '@koalaui/libarkts'; import * as fs from 'fs'; import * as path from 'path'; +export const SINGLE_CHILD_COMPONENT: number = 1; +export const MAX_ENTRY_DECORATOR_COUNT: number = 1; +export const MAX_PREVIEW_DECORATOR_COUNT: number = 10; + +export const COMPONENT_REPEAT: string = 'Repeat'; +export const TEMPLATE: string = 'template'; + +export const PresetType = { + STRING: 'string', + NUMBER: 'number', + BOOLEAN: 'boolean', + BIGINT: 'bigint' +}; + +export const forbiddenUseStateType: string[] = [ + 'Scroller', + 'SwiperScroller', + 'VideoController', + 'WebController', + 'CustomDialogController', + 'SwiperController', + 'TabsController', + 'CalendarController', + 'AbilityController', + 'XComponentController', + 'CanvasRenderingContext2D', + 'CanvasGradient', + 'ImageBitmap', + 'ImageData', + 'Path2D', + 'RenderingContextSettings', + 'OffscreenCanvasRenderingContext2D', + 'PatternLockController', + 'TextAreaController', + 'TextInputController', + 'TextTimerController', + 'SearchController', + 'RichEditorController', +]; + export const PresetDecorators = { BUILDER_PARAM: 'BuilderParam', COMPONENT_V1: 'Component', @@ -53,6 +93,9 @@ export const PresetDecorators = { ONCE: 'Once', MONITOR: 'Monitor', LOCAL_BUILDER: 'LocalBuilder', + REGULAR: 'regular', + VARIABLE: 'variable', + PARAMETER: 'parameter', }; const PUBLIC_PROPERTY_MODIFIERS: Number = 4; @@ -134,6 +177,10 @@ export function isProtectedlassProperty(property: arkts.ClassProperty): boolean return property.modifiers === PROTECTED_PROPERTY_MODIFIERS; } +export function listToString(strList: string[]): string { + return strList.length > 1 ? `${strList.slice(0, -1).join(', ')} and ${strList.slice(-1)}` : strList.join(''); +} + export class MultiMap { private readonly map: Map; constructor() { -- Gitee From dc51b2713582346bb908dfe3536eac64a626c07b Mon Sep 17 00:00:00 2001 From: wangweiyuan Date: Wed, 4 Jun 2025 17:57:17 +0800 Subject: [PATCH 112/123] =?UTF-8?q?add=20ui-syntax-plugins=200604=208?= =?UTF-8?q?=E6=9D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangweiyuan --- .../rules/component-componentV2-init-check.ts | 88 ++++++++++++++ .../rules/no-prop-link-objectlink-in-entry.ts | 33 +++-- .../rules/one-decorator-on-function-method.ts | 46 +++++-- .../rules/reusableV2-decorator-check.ts | 84 +++++++++++++ .../rules/specific-component-children.ts | 113 ++++++++++++++++++ .../rules/struct-missing-decorator.ts | 28 ++--- .../rules/struct-no-extends.ts | 52 ++++++++ .../rules/validate-build-in-struct.ts | 15 ++- .../ui-syntax-plugins/utils/index.ts | 6 + 9 files changed, 416 insertions(+), 49 deletions(-) create mode 100644 arkui-plugins/ui-syntax-plugins/rules/component-componentV2-init-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/reusableV2-decorator-check.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/specific-component-children.ts create mode 100644 arkui-plugins/ui-syntax-plugins/rules/struct-no-extends.ts diff --git a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-init-check.ts b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-init-check.ts new file mode 100644 index 000000000..df746ab4c --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-init-check.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { getAnnotationUsage, getIdentifierName, hasAnnotation, PresetDecorators } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function initComponentV1WithLinkList(node: arkts.AstNode, componentV1WithLinkList: string[]): void { + if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { + return; + } + node.getChildren().forEach((member) => { + if (!arkts.isStructDeclaration(member) || !member.definition.ident || + !hasAnnotation(member?.definition.annotations, PresetDecorators.COMPONENT_V1)) { + return; + } + let structName: string = member.definition.ident?.name ?? ''; + member.definition?.body?.forEach((item) => { + if (!arkts.isClassProperty(item) || !item.key) { + return; + } + if (item.annotations.some(annotation => annotation.expr && + getIdentifierName(annotation.expr) === PresetDecorators.LINK)) { + componentV1WithLinkList.push(structName); + } + }); + }); +} + +function checkComponentInitLink( + node: arkts.AstNode, + context: UISyntaxRuleContext, + componentV1WithLinkList: string[] +): void { + if (!arkts.isIdentifier(node) || !componentV1WithLinkList.includes(getIdentifierName(node))) { + return; + } + let parentNode = node.parent; + while (!arkts.isStructDeclaration(parentNode)) { + if (!parentNode.parent) { + return; + } + parentNode = parentNode.parent; + } + if (getAnnotationUsage(parentNode, PresetDecorators.COMPONENT_V2) !== undefined) { + context.report({ + node: node.parent, + message: rule.messages.componentInitLinkCheck, + fix: (node) => { + return { + range: [node.startPosition, node.endPosition], + code: '', + }; + } + }); + } +} + +const rule: UISyntaxRule = { + name: 'component-componentV2-init-check', + messages: { + componentInitLinkCheck: `A V2 component cannot be used with any member property decorated by '@Link' in a V1 component.`, + }, + setup(context) { + // Decorated by component v1 and uses the link attribute + let componentV1WithLinkList: string[] = []; + return { + parsed: (node): void => { + initComponentV1WithLinkList(node, componentV1WithLinkList); + checkComponentInitLink(node, context, componentV1WithLinkList); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts index 8815feff4..01e12efda 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts @@ -17,9 +17,15 @@ import * as arkts from '@koalaui/libarkts'; import { getAnnotationUsage, PresetDecorators } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; +const invalidDecorators = [PresetDecorators.PROP, PresetDecorators.LINK, PresetDecorators.OBJECT_LINK]; + function checkNoPropLinkOrObjectLinkInEntry(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { // Check if the struct has the @Entry decorator const isEntryComponent = !!getAnnotationUsage(node, PresetDecorators.ENTRY); + if (!node.definition.ident || !arkts.isIdentifier(node.definition.ident)) { + return; + } + const componentName = node.definition.ident.name; if (!isEntryComponent) { return; } @@ -27,25 +33,32 @@ function checkNoPropLinkOrObjectLinkInEntry(context: UISyntaxRuleContext, node: if (!arkts.isClassProperty(body)) { return; } - const invalidDecorators = [PresetDecorators.PROP, PresetDecorators.LINK, PresetDecorators.OBJECT_LINK]; + if (!body.key || !arkts.isIdentifier(body.key)) { + return; + } + const propertyName = body.key.name; // Check if any invalid decorators are applied to the class property body.annotations?.forEach(annotation => { - reportInvalidDecorator(context, annotation, invalidDecorators); + reportInvalidDecorator(context, annotation, invalidDecorators, componentName, propertyName); }); }); } function reportInvalidDecorator(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage, - invalidDecorators: string[],): void { - if (annotation.expr && invalidDecorators.includes(annotation.expr.dumpSrc())) { - const decorator = annotation.expr.dumpSrc(); + invalidDecorators: string[], componentName: string, propertyName: string): void { + if (annotation.expr && arkts.isIdentifier(annotation.expr) && invalidDecorators.includes(annotation.expr.name)) { + const decoratorName = annotation.expr.name; context.report({ node: annotation, - message: rule.messages.invalidUsage, - data: { decorator }, + message: rule.messages.disallowDecoratorInEntry, + data: { + componentName, + decoratorName, + propertyName, + }, fix: (annotation) => { - const startPosition = arkts.getStartPosition(annotation); - const endPosition = arkts.getEndPosition(annotation); + const startPosition = annotation.startPosition; + const endPosition = annotation.endPosition; return { range: [startPosition, endPosition], code: '', @@ -58,7 +71,7 @@ function reportInvalidDecorator(context: UISyntaxRuleContext, annotation: arkts. const rule: UISyntaxRule = { name: 'no-prop-link-objectlink-in-entry', messages: { - invalidUsage: `@{{decorator}} decorator cannot be used for '@Entry' decorated components.`, + disallowDecoratorInEntry: `The '@Entry' component '{{componentName}}' cannot have the '@{{decoratorName}}' property '{{propertyName}}'.`, }, setup(context) { return { diff --git a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts index 66dd9cdbd..2e9f11fbf 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts @@ -14,10 +14,11 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getAnnotationName } from '../utils'; +import { getAnnotationName, PresetDecorators } from '../utils'; import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -const allowedDecorators = new Set(['Extend', 'Builder', 'Styles']); +const allowedDecorators = PresetDecorators.BUILDER; +const DECORATOR_LIMIT = 1; function validateFunctionDecorator(node: arkts.EtsScript, context: UISyntaxRuleContext): void { node.statements.forEach((statement) => { @@ -30,27 +31,48 @@ function validateFunctionDecorator(node: arkts.EtsScript, context: UISyntaxRuleC if (!annotations) { return; } + const otherDecorator = annotations?.find(annotation => + annotation.expr && arkts.isIdentifier(annotation.expr) && + annotation.expr.name !== PresetDecorators.BUILDER + ); // Check that each annotation is in the list of allowed decorators annotations.forEach((annotation) => { const decoratorName = getAnnotationName(annotation); - // rule1: misuse of decorator, only '@Extend', '@Builder' , '@Styles' decorators allowed on global functions - if (!allowedDecorators.has(decoratorName)) { - context.report({ - node: annotation, - message: rule.messages.invalidDecorator, - data: { - decoratorName, - }, - }); + // rule1: misuse of decorator, only '@Builder' , '@Styles' decorators allowed on global functions + if (allowedDecorators !== decoratorName || + (allowedDecorators === decoratorName && decoratorName.length > DECORATOR_LIMIT)) { + reportInvalidDecorator(annotation, otherDecorator, context); } }); }); } +function reportInvalidDecorator( + annotation: arkts.AnnotationUsage, + otherDecorator: arkts.AnnotationUsage | undefined, + context: UISyntaxRuleContext +): void { + if (!otherDecorator) { + return; + } + context.report({ + node: annotation, + message: rule.messages.invalidDecorator, + fix: () => { + const startPosition = otherDecorator.startPosition; + const endPosition = otherDecorator.endPosition; + return { + range: [startPosition, endPosition], + code: `` + }; + } + }); +} + const rule: UISyntaxRule = { name: 'one-decorator-on-function-method', messages: { - invalidDecorator: `misuse of '@{{decoratorName}}' decorator, only '@Extend', '@Builder' and '@Styles' decorators allowed on global functions.`, + invalidDecorator: `A function can only be decorated by the 'Builder'.`, }, setup(context) { return { diff --git a/arkui-plugins/ui-syntax-plugins/rules/reusableV2-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/reusableV2-decorator-check.ts new file mode 100644 index 000000000..41bee3a60 --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/reusableV2-decorator-check.ts @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { PresetDecorators, getAnnotationUsage } from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function reportInvalidDecoratorUsage( + reusableDocoratorUsage: arkts.AnnotationUsage | undefined, + structNode: arkts.Identifier | undefined, + context: UISyntaxRuleContext +): void { + if (!structNode || !reusableDocoratorUsage) { + return; + } + context.report({ + node: structNode, + message: rule.messages.conflictingDecorators, + }); +} + +function reportConflictingDecorators( + node: arkts.StructDeclaration, + structNode: arkts.Identifier | undefined, + context: UISyntaxRuleContext +): void { + if (!structNode || !node) { + return; + } + context.report({ + node: structNode, + message: rule.messages.invalidDecoratorUsage, + }); +} + +const rule: UISyntaxRule = { + name: 'reusableV2-decorator-check', + messages: { + conflictingDecorators: `The '@Reusable' and '@ReusableV2' decorators cannot be applied simultaneously.`, + invalidDecoratorUsage: `@ReusableV2 is only applicable to custom components decorated by @ComponentV2.`, + }, + setup(context) { + return { + parsed: (node): void => { + if (!arkts.isStructDeclaration(node)) { + return; + } + if (!node.definition) { + return; + } + if (!arkts.isClassDefinition(node.definition)) { + return; + } + const structNode = node.definition.ident; + // Check whether the decoration exists, and mark true if it does + const reusableDocoratorUsage = getAnnotationUsage(node, PresetDecorators.REUSABLE_V1); + const reusableV2DocoratorUsage = getAnnotationUsage(node, PresetDecorators.REUSABLE_V2); + const componnetV2DocoratorUsage = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); + // Check whether @Reusable and @ReusableV2 exist at the same time + if (reusableV2DocoratorUsage && reusableDocoratorUsage && structNode) { + reportInvalidDecoratorUsage(reusableDocoratorUsage, structNode, context); + } + // Check if @ReusableV2 is applied to a class decorated by @ComponentV2 + if (reusableV2DocoratorUsage && !componnetV2DocoratorUsage && structNode) { + reportConflictingDecorators(node, structNode, context); + } + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/specific-component-children.ts b/arkui-plugins/ui-syntax-plugins/rules/specific-component-children.ts new file mode 100644 index 000000000..279ea271e --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/specific-component-children.ts @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { + getIdentifierName, + PresetDecorators, + SINGLE_CHILD_COMPONENT, + TOGGLE_TYPE, + ToggleType, + TYPE +} from '../utils'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function getToggleType(node: arkts.CallExpression): string { + let toggleType = ''; + node.arguments.forEach((member) => { + if (!arkts.isObjectExpression(member) || !member.properties) { + return; + } + member.properties.forEach((property) => { + if (!arkts.isProperty(property) || !property.value) { + return; + } + // If the property name is not 'toggle type' + if (!arkts.isMemberExpression(property.value) || !property.value.object || + !arkts.isIdentifier(property.value.object) || property.value.object.name !== TOGGLE_TYPE) { + return; + } + if (!property.value.property || !arkts.isIdentifier(property.value.property)) { + return; + } + toggleType = property.value.property.name; + }); + }); + return toggleType; +} + +function checkSingleChildComponent(node: arkts.AstNode, context: UISyntaxRuleContext): void { + // Check whether the current node is an identifier and toggle component + if (!arkts.isIdentifier(node)) { + return; + } + const componentName: string = getIdentifierName(node); + if (componentName !== PresetDecorators.TOGGLE || !node.parent) { + return; + } + const parentNode = node.parent; + if (!arkts.isCallExpression(parentNode)) { + return; + } + const toggleTypeValue = getToggleType(parentNode); + // If there is more than one subcomponent in the BlockStatement, an error is reported + parentNode.getChildren().forEach(member => { + if (!arkts.isBlockStatement(member)) { + return; + } + // If the toggle component type is checkbox and has child components, an error is reported + if (toggleTypeValue === ToggleType.CHECKBOX && member.statements.length > 0) { + context.report({ + node: node, + message: rule.messages.toggleTypeCheckboxWithNoChild, + data: { + componentName: componentName, + toggleTypeKey: TYPE, + toggleTypeValue: toggleTypeValue + } + }); + } + // If the toggle component type is button and there is more than one child component, an error is reported + if (toggleTypeValue === ToggleType.BUTTON && member.statements.length > SINGLE_CHILD_COMPONENT) { + context.report({ + node: node, + message: rule.messages.toggleTypeButtonWithsingleChild, + data: { + componentName: componentName, + toggleTypeKey: TYPE, + toggleTypeValue: toggleTypeValue + } + }); + } + }); +} + + +const rule: UISyntaxRule = { + name: 'specific-component-children', + messages: { + toggleTypeCheckboxWithNoChild: `When the component '{{componentName}}' set '{{toggleTypeKey}}' as '{{toggleTypeValue}}', it can't have any child.`, + toggleTypeButtonWithsingleChild: `When the component '{{componentName}}' set '{{toggleTypeKey}}' as '{{toggleTypeValue}}', it can only have a single child component.`, + }, + setup(context) { + return { + parsed: (node): void => { + checkSingleChildComponent(node, context); + }, + }; + }, +}; + +export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts index 7ca8e7b3a..6f3019c5a 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts @@ -20,9 +20,7 @@ import { UISyntaxRule } from './ui-syntax-rule'; const rule: UISyntaxRule = { name: 'struct-missing-decorator', messages: { - missingComponentDecorator: `struct '{{structName}}' is missing '@Component' or '@CustomDialog' decorators`, - misusedPreview: `struct '{{structName}}' misused '@Preview' decorator. it should be decorated by '@Component' or '@CustomDialog'`, - misusedObserved: `struct '{{structName}}' misused '@Observed' decorator. it should be decorated by '@Component' or '@CustomDialog'`, + missingComponentDecorator: `Decorator '@Component', '@ComponentV2', or '@CustomDialog' is missing for struct '{{structName}}'.` }, setup(context) { function hasDecorator(node: arkts.StructDeclaration, decorator: string): boolean { @@ -34,14 +32,18 @@ const rule: UISyntaxRule = { if (!arkts.isStructDeclaration(node)) { return; } + if (!node.definition) { + return; + } + if (!arkts.isClassDefinition(node.definition)) { + return; + } // Check for the presence of specific decorators on the struct const structName = node.definition.ident?.name ?? ''; const structNode = node.definition.ident; const hasComponent = hasDecorator(node, PresetDecorators.COMPONENT_V1); const hasComponentV2 = hasDecorator(node, PresetDecorators.COMPONENT_V2); const hasCustomDialog = hasDecorator(node, PresetDecorators.CUSTOM_DIALOG); - const hasPreview = getAnnotationUsage(node, PresetDecorators.PREVIEW); - const hasObserved = getAnnotationUsage(node, PresetDecorators.OBSERVED_V1); // If no valid component decorators (@Component or @CustomDialog) are found if (!hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { context.report({ @@ -50,22 +52,6 @@ const rule: UISyntaxRule = { data: { structName }, }); } - // If the @Preview decorator is used but the struct is not decorated with @Component or @CustomDialog - if (hasPreview && !hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { - context.report({ - node: structNode, - message: rule.messages.misusedPreview, - data: { structName }, - }); - } - // If the @Observed decorator is used but the struct is not decorated with @Component or @CustomDialog - if (hasObserved && !hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { - context.report({ - node: structNode, - message: rule.messages.misusedObserved, - data: { structName }, - }); - } }, }; }, diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-no-extends.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-no-extends.ts new file mode 100644 index 000000000..99018623d --- /dev/null +++ b/arkui-plugins/ui-syntax-plugins/rules/struct-no-extends.ts @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; +import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; + +function checkExtendOrImplement( + node: arkts.AstNode, + context: UISyntaxRuleContext +): void { + if (!arkts.isStructDeclaration(node) || !node.definition.ident) { + return; + } + const hasSuperClass: boolean = node.definition.super !== undefined; + const hasImplements: boolean = node.definition.implements.length > 0; + // If there is an inheritance class or implementation interface, an error is reported + if (hasSuperClass || hasImplements) { + const errorNode = node.definition.ident; + context.report({ + node: errorNode, + message: rule.messages.structNoExtends, + }); + } +} + +const rule: UISyntaxRule = { + name: 'struct-no-extends', + messages: { + structNoExtends: `Structs are not allowed to inherit from classes or implement interfaces.`, + }, + setup(context) { + return { + parsed: (node): void => { + checkExtendOrImplement(node, context); + }, + }; + }, +}; + +export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts index 938c3a210..f5d308652 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts @@ -44,8 +44,8 @@ function reportBuildParamNotAllowed( node: param, message: rule.messages.invalidComponet, fix: (param) => { - const startPosition = arkts.getStartPosition(param); - const endPosition = arkts.getEndPosition(param); + const startPosition = param.startPosition; + const endPosition = param.endPosition; return { range: [startPosition, endPosition], code: '' @@ -83,8 +83,11 @@ function reportMissingBuildInStruct( context.report({ node: structName, message: rule.messages.invalidBuild, + data: { + structName: getIdentifierName(structName), + }, fix: (structName) => { - const startPosition = arkts.getStartPosition(blockStatement); + const startPosition = blockStatement.startPosition; const endPosition = startPosition; return { range: [startPosition, endPosition], @@ -101,7 +104,7 @@ function validateBuild( ): void { node.definition.body.forEach((member) => { // Check if the member is defined for the method and the method name is 'build' - if (arkts.isMethodDefinition(member) && getIdentifierName(member.name) === BUILD_NAME) { + if (arkts.isMethodDefinition(member) && arkts.isIdentifier(member.name) && getIdentifierName(member.name) === BUILD_NAME) { buildFunctionCount++; validateBuildFunctionParameters(member, context); } @@ -116,8 +119,8 @@ function validateBuild( const rule: UISyntaxRule = { name: 'validate-build-in-struct', messages: { - invalidComponet: `A custom component can have only one 'build' function, which does not require parameters.`, - invalidBuild: `This rule validates the use of the 'build' function`, + invalidComponet: `The 'build' method can not have arguments.`, + invalidBuild: `The struct '{{structName}}' must have at least and at most one 'build' method.`, }, setup(context) { return { diff --git a/arkui-plugins/ui-syntax-plugins/utils/index.ts b/arkui-plugins/ui-syntax-plugins/utils/index.ts index 87ba336a7..16b42fc35 100644 --- a/arkui-plugins/ui-syntax-plugins/utils/index.ts +++ b/arkui-plugins/ui-syntax-plugins/utils/index.ts @@ -170,6 +170,12 @@ export class MultiMap { } } +export function hasAnnotation(annoArray: readonly arkts.AnnotationUsage[], annotationName: string): boolean { + return (annoArray || []).some(anno => + anno.expr && getIdentifierName(anno.expr) === annotationName + ); +} + interface ComponentJson { name: string; atomic?: boolean; -- Gitee From 0ebf116b4c91d823514b079c8203c401cea6b054 Mon Sep 17 00:00:00 2001 From: l00913061 Date: Thu, 29 May 2025 19:28:41 +0800 Subject: [PATCH 113/123] refactor interop Signed-off-by: l00913061 Change-Id: I15892a722cdd7e402f76cf7db5208d30e4083a8b --- arkui-plugins/common/program-visitor.ts | 2 +- .../demo/interop/1.2Provide-1.1Consume.ets | 106 ++++++ .../demo/interop/1.2State-1.1Link-example.ets | 2 +- .../ui-plugins/checked-transformer.ts | 4 +- .../ui-plugins/component-transformer.ts | 47 ++- .../ui-plugins/{ => interop}/initstatevar.ts | 311 +++++++++++------- .../ui-plugins/{ => interop}/interop.ts | 281 +++++++--------- .../{ => interop}/legacy-transformer.ts | 59 +++- arkui-plugins/ui-plugins/interop/provide.ts | 189 +++++++++++ arkui-plugins/ui-plugins/interop/utils.ts | 184 +++++++++++ 10 files changed, 870 insertions(+), 315 deletions(-) create mode 100644 arkui-plugins/test/demo/interop/1.2Provide-1.1Consume.ets rename arkui-plugins/ui-plugins/{ => interop}/initstatevar.ts (42%) rename arkui-plugins/ui-plugins/{ => interop}/interop.ts (79%) rename arkui-plugins/ui-plugins/{ => interop}/legacy-transformer.ts (83%) create mode 100644 arkui-plugins/ui-plugins/interop/provide.ts create mode 100644 arkui-plugins/ui-plugins/interop/utils.ts diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index c73e00073..daf5cda20 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -19,7 +19,7 @@ import { matchPrefix } from './arkts-utils'; import { debugDump, getDumpFileName } from './debug'; import { InteroperAbilityNames } from './predefines'; import { PluginContext } from './plugin-context'; -import { LegacyTransformer } from '../ui-plugins/legacy-transformer'; +import { LegacyTransformer } from '../ui-plugins/interop/legacy-transformer'; import { ComponentTransformer } from '../ui-plugins/component-transformer'; export interface ProgramVisitorOptions extends VisitorOptions { diff --git a/arkui-plugins/test/demo/interop/1.2Provide-1.1Consume.ets b/arkui-plugins/test/demo/interop/1.2Provide-1.1Consume.ets new file mode 100644 index 000000000..48076c791 --- /dev/null +++ b/arkui-plugins/test/demo/interop/1.2Provide-1.1Consume.ets @@ -0,0 +1,106 @@ +/* + * 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. + */ + + +// ArkTS1.2 +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { ArkUICompatible, InteropComponent, Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickEvent, UserView, } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins +import { State, StateDecoratedVariable, MutableState, stateOf, observableProxy, Observed, Track, Provide, Consume } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { MyText } from 'har2/src/main/ets/components/MainPage' +import { Child1 } from 'har1' + + +@Component +struct MyStateSample { + @Provide stateVar: MyText = new MyText(); + build() { + Column() { + Button(this.stateVar.text) + .onClick((e: ClickEvent) => { + this.stateVar.text += '~'; + }) + Child1() + } + } +} + +class MyText { + text: string = 'MyText'; +} + + +//ArkT1.1 +import { MyText } from 'har2/src/main/ets/components/MainPage' + +@Component +export struct Child1{ + @Consume stateVar: MyText; + build() { + Column() { + Button(this.stateVar.text) + .onClick(() => { + this.stateVar.text += '~'; + }) + } + } +} + + + +//transform 1.1struct 'Child1' to ArkUICompatible + +ArkUICompatible(__memo_context, ((__memo_id) + (252133223)), (() => { + let global = ESValue.getGlobal(); + let param = ESValue.instantiateEmptyObject(); + let createState = global.getProperty("createStateVariable"); + let setFindProvideInterop = global.getProperty("setFindProvideInterop"); + let findProvideInterop = ((providedPropName: string): Object => { + let provide = (this).findProvide(providedPropName); + if (((provide!?.getProxy()) === (undefined))) { + let setSource = ((value: Object) => { + provide!.set(value); + }); + let proxyState = createState.invoke(ESValue.wrap(provide!.get()), ESValue.wrap(setSource)); + let setProxy = ((value: Object) => { + proxyState.invokeMethod("set", ESValue.wrap(value)); + }); + let notifyCallback = ((propertyName: string) => { + proxyState.invokeMethod("notifyPropertyHasChangedPU"); + }); + configureState(provide!, proxyState, setProxy, notifyCallback); + } + let proxy = provide!.getProxy(); + return (proxy as ESValue).unwrap()!; + }); + setFindProvideInterop.invoke(findProvideInterop); + let extraInfo = ESValue.instantiateEmptyObject(); + extraInfo.setProperty("page", "har1/src/main/ets/components/MainPage"); + let esundefined = ESValue.wrap(undefined); + let blank = (() => {}); + let esblank = ESValue.wrap((blank as object)); + let viewStackProcessor = global.getProperty("ViewStackProcessor"); + let createId = viewStackProcessor.getProperty("AllocateNewElmetIdForNextComponent"); + let elmtId = createId.invoke(); + let har1 = ESValue.load("@normalized:N&entry&com.example.Interop2use1&har1/src/main/ets/components/MainPage&1.0.0"); + let structObject = har1.getProperty("Child1"); + let component = structObject.instantiate(esundefined, param, esundefined, elmtId, esblank, extraInfo); + let create = structObject.getProperty("create"); + create.invoke(component); + structObject.invokeMethod("resetFindInterop") + return { + component: component, + name: "Child1", + }; + }), ((instance: ESValue) => {})); \ No newline at end of file diff --git a/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets b/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets index f11af005f..cfdff0613 100644 --- a/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets +++ b/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets @@ -24,7 +24,7 @@ import { Child1 } from 'har1' @Component struct MyStateSample { - @State stateVar: new MyText(); + @State stateVar: MyText = new MyText(); build() { Column() { Button(this.stateVar.text) diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index cde68e6c9..f3ccf8d29 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -36,7 +36,7 @@ import { isEntryWrapperClass } from './entry-translators/utils'; import { ImportCollector } from '../common/import-collector'; import { DeclarationCollector } from '../common/declaration-collector'; import { PropertyCache } from './property-translators/utils'; -import { isArkUICompatible, updateArkUICompatible } from './interop'; +import { isArkUICompatible, generateArkUICompatible } from './interop/interop'; export class CheckedTransformer extends AbstractVisitor { private scope: ScopeInfoCollection; @@ -109,7 +109,7 @@ export class CheckedTransformer extends AbstractVisitor { } else if (arkts.isCallExpression(node) && isResourceNode(node)) { return structFactory.transformResource(node, this.projectConfig); } else if (isArkUICompatible(node)) { - return updateArkUICompatible(node as arkts.CallExpression); + return generateArkUICompatible(node as arkts.CallExpression); } else if (arkts.isTSInterfaceDeclaration(node)) { return structFactory.tranformInterfaceMembers(node, this.externalSourceName); } else if (findCanAddMemoFromArrowFunction(node)) { diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 4485bc9bd..40336dec4 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -47,7 +47,7 @@ import { DECORATOR_TYPE_MAP, ENTRY_POINT_IMPORT_SOURCE_NAME, } from '../common/predefines'; -import { generateTempCallFunction } from './interop'; +import { generateInstantiateInterop } from './interop/interop'; export interface ComponentTransformerOptions extends VisitorOptions { arkui?: string; @@ -375,7 +375,7 @@ export class ComponentTransformer extends AbstractVisitor { this.hasLegacy = true; } - processImport(node: arkts.ETSImportDeclaration): void { + processInteropImport(node: arkts.ETSImportDeclaration): void { const source = node.source?.str!; const specifiers = node.specifiers as arkts.ImportSpecifier[]; if (this.legacyStructMap.has(source)) { @@ -384,14 +384,35 @@ export class ComponentTransformer extends AbstractVisitor { return; } for (const specifier of specifiers) { - const name = specifier.local?.name; - if (!!name && structMap[name]) { + const name = (specifier as arkts.ImportSpecifier)!.local!.name; + if (structMap[name]) { this.legacyCallMap.set(name, structMap[name]); } } } } + processInteropCall(node: arkts.CallExpression): arkts.CallExpression { + const ident = node.expression; + if (!(ident instanceof arkts.Identifier)) { + return node; + } + const className = ident.name; + if (this.legacyCallMap.has(className)) { + const path = this.legacyCallMap.get(className)!; + const args = node.arguments; + const context: InteropContext = { + className: className, + path: path, + arguments: args && args.length === 1 && args[0] instanceof arkts.ObjectExpression + ? args[0] + : undefined + }; + return generateInstantiateInterop(context); + } + return node; + } + visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); const newNode = this.visitEachChild(node); @@ -407,25 +428,15 @@ export class ComponentTransformer extends AbstractVisitor { this.exit(newNode); return updateNode; } + // process interop code if (!this.hasLegacy) { return newNode; } if (arkts.isETSImportDeclaration(newNode)) { - this.processImport(newNode); + this.processInteropImport(newNode); } - if (arkts.isCallExpression(newNode) && arkts.isIdentifier(newNode.expression)) { - const className = newNode.expression.name; - if (this.legacyCallMap.has(className)) { - const path = this.legacyCallMap.get(className)!; - const args = newNode.arguments; - const context: InteropContext = { - className: className, - path: path, - arguments: - args && args.length === 1 && args[0] instanceof arkts.ObjectExpression ? args[0] : undefined, - }; - return generateTempCallFunction(context); - } + if (arkts.isCallExpression(newNode)) { + return this.processInteropCall(newNode); } return newNode; } diff --git a/arkui-plugins/ui-plugins/initstatevar.ts b/arkui-plugins/ui-plugins/interop/initstatevar.ts similarity index 42% rename from arkui-plugins/ui-plugins/initstatevar.ts rename to arkui-plugins/ui-plugins/interop/initstatevar.ts index 3264db1a2..a914ab4e3 100644 --- a/arkui-plugins/ui-plugins/initstatevar.ts +++ b/arkui-plugins/ui-plugins/interop/initstatevar.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * 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 @@ -16,22 +16,11 @@ import * as arkts from '@koalaui/libarkts'; -import { InteroperAbilityNames } from '../common/predefines'; -import { annotation, backingField, isAnnotation } from '../common/arkts-utils'; -import { getPropertyESValue, getWrapValue, setPropertyESValue } from './interop'; +import { InteroperAbilityNames } from '../../common/predefines'; +import { annotation, backingField, isAnnotation } from '../../common/arkts-utils'; +import { stateProxy, getPropertyESValue, getWrapValue, ifStateHasProxy, setPropertyESValue, hasLink, hasState, hasProvide, hasProp } from './utils'; -export function processNormal(keyName: string, value: arkts.AstNode): arkts.Statement[] { - const result: arkts.Statement[] = []; - const setProperty = setPropertyESValue( - InteroperAbilityNames.PARAM, - keyName, - getWrapValue(value) - ); - result.push(setProperty); - return result; -} - export function createVariableLet(varName: string, expression: arkts.AstNode): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, @@ -43,7 +32,7 @@ export function createVariableLet(varName: string, expression: arkts.AstNode): a )] ); } -export function setValueCallback(name: string, type: arkts.TypeNode, block: arkts.BlockStatement): arkts.AstNode { +function setValueCallback(name: string, block: arkts.BlockStatement, type?: arkts.TypeNode): arkts.AstNode { return createVariableLet(name, arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( @@ -52,9 +41,16 @@ export function setValueCallback(name: string, type: arkts.TypeNode, block: arkt undefined, [ arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('value', type), - undefined, - ), + arkts.factory.createIdentifier( + 'value', + type ?? arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('Object') + ) + ) + ), + undefined + ) ], undefined, false @@ -66,29 +62,31 @@ export function setValueCallback(name: string, type: arkts.TypeNode, block: arkt ); } -function createProxyBlock(varName: string): arkts.BlockStatement { +function createProxyBlock(stateVar: () => arkts.Expression): arkts.BlockStatement { return arkts.factory.createBlock( [ arkts.factory.createExpressionStatement( - arkts.factory.createAssignmentExpression( + arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(varName), + stateVar(), + arkts.factory.createIdentifier('set'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier('value') + undefined, + [ + arkts.factory.createIdentifier('value') + ] ) ) ] ); } -export function setCallbackForProxy(varName: string, type: arkts.TypeNode): arkts.Statement[] { - const createCallback = setValueCallback(addStatePrefix(varName, 'SetSource'), type, createProxyBlock(varName)); - const createProxyState = createVariableLet(addStatePrefix(varName, 'ProxyState'), +function setCallbackForProxy(stateVar: () => arkts.Expression, type?: arkts.TypeNode): arkts.Statement[] { + const createCallback = setValueCallback('setSource', createProxyBlock(stateVar), type); + const createProxyState = createVariableLet('proxyState', arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier('createState'), @@ -100,49 +98,32 @@ export function setCallbackForProxy(varName: string, type: arkts.TypeNode): arkt undefined, [ getWrapValue( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(varName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + stateVar(), + arkts.factory.createIdentifier('get'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [] ) ), - getWrapValue(arkts.factory.createIdentifier(addStatePrefix(varName, 'SetSource'))) + getWrapValue(arkts.factory.createIdentifier('setSource')) ] ) ); - const setProxy = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(backingField(varName)), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ), - arkts.factory.createIdentifier('setProxy'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState'))], - ) - ); - return [createCallback, createProxyState, setProxy]; + return [createCallback, createProxyState]; } -function createSourceBlock(varName: string): arkts.BlockStatement { +function createSourceBlock(): arkts.BlockStatement { return arkts.factory.createBlock( [ arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')), + arkts.factory.createIdentifier('proxyState'), arkts.factory.createIdentifier('invokeMethod'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, @@ -161,13 +142,13 @@ function createSourceBlock(varName: string): arkts.BlockStatement { ); } -function createNotifyBlock(varName: string): arkts.BlockStatement { +function createNotifyBlock(): arkts.BlockStatement { return arkts.factory.createBlock( [ arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')), + arkts.factory.createIdentifier('proxyState'), arkts.factory.createIdentifier('invokeMethod'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, @@ -183,9 +164,10 @@ function createNotifyBlock(varName: string): arkts.BlockStatement { ); } -function setNotifyForSource(varName: string): arkts.Statement[] { - const block = createNotifyBlock(varName); - const createCallback = createVariableLet(addStatePrefix(varName, 'NotifyCallback'), +function setCallbackForSource(type?: arkts.TypeNode): arkts.Statement[] { + const createValueCallback = setValueCallback('setProxy', createSourceBlock(), type); + const block = createNotifyBlock(); + const createNotifyCallback = createVariableLet('notifyCallback', arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( block, @@ -211,80 +193,163 @@ function setNotifyForSource(varName: string): arkts.Statement[] { ) ) ); - const setCallback = arkts.factory.createExpressionStatement( + return [createValueCallback, createNotifyCallback]; +} + +function configureState(stateVar: () => arkts.Expression): arkts.Statement { + return arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(backingField(varName)), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ), - arkts.factory.createIdentifier('setNotifyCallback'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), + arkts.factory.createIdentifier('configureState'), undefined, - [arkts.factory.createIdentifier(addStatePrefix(varName, 'NotifyCallback'))], + [ + stateVar(), + arkts.factory.createIdentifier('proxyState'), + arkts.factory.createIdentifier('setProxy'), + arkts.factory.createIdentifier('notifyCallback'), + ], ) ); - return [createCallback, setCallback]; } -export function setCallbackForSource(varName: string, type: arkts.TypeNode): arkts.Statement[] { - const createCallback = setValueCallback(addStatePrefix(varName, 'SetProxy'), type, createSourceBlock(varName)); - const setFunc = arkts.factory.createExpressionStatement( - arkts.factory.createAssignmentExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(backingField(varName)), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ), - arkts.factory.createIdentifier('setProxyValue'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier(addStatePrefix(varName, 'SetProxy')) +function createProxyForState(stateVar: () => arkts.Expression, type?: arkts.TypeNode): arkts.Statement[] { + const setProxy = setCallbackForProxy(stateVar, type); + const setSource = setCallbackForSource(type); + const cfgState = configureState(stateVar); + return [...setProxy, ...setSource, cfgState]; +} + + +export function setStateProxy(stateVar: () => arkts.Expression, type?: arkts.TypeNode): arkts.Statement[] { + const statements = createProxyForState(stateVar, type); + const ifProxy = ifStateHasProxy(stateVar, arkts.factory.createBlock(statements)); + return [ifProxy]; +} + +function createBackingFieldExpression(varName: string): arkts.TSNonNullExpression { + return arkts.factory.createTSNonNullExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(backingField(varName)), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false ) ); - const setNotify = setNotifyForSource(varName); - return [createCallback, setFunc, ...setNotify]; } -export function processLink(keyName: string, value: arkts.AstNode, type: arkts.TypeNode, proxySet: Set): arkts.Statement[] { - const varName = ((value as arkts.MemberExpression).property as arkts.Identifier).name; +function setAndGetProxy(varName: string, type: arkts.TypeNode, stateVar: () => arkts.Expression, + proxySet: Set): arkts.Statement[] { const result: arkts.Statement[] = []; - if (!proxySet.has(varName)) { - proxySet.add(varName); - const setProxy = setCallbackForProxy(varName, type); - result.push(...setProxy); - const setSource = setCallbackForSource(varName, type); - result.push(...setSource); + if (!proxySet.has(stateProxy(varName))) { + proxySet.add(stateProxy(varName)); + const setProxy = setStateProxy(stateVar, type); + const getProxy = createVariableLet( + stateProxy(varName), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + stateVar(), + arkts.factory.createIdentifier('getProxy'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined + ) + ); + result.push(...setProxy, getProxy); } - const setParam = setPropertyESValue( - 'param', - keyName, - arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')) - ); - result.push(setParam); return result; } -export function hasLink(decorators: string[]): boolean { - return decorators.some(decorator => decorator === 'Link'); +function linkGetSource(varName: string, proxySet: Set): arkts.Statement[] { + const result: arkts.Statement[] = []; + const backingLink = createBackingFieldExpression(varName); + const stateName = `${varName}_State`; + if (!proxySet.has(stateName)) { + proxySet.add(stateName); + const getState = createVariableLet( + stateName, + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + backingLink, + arkts.factory.createIdentifier('getSource'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined + ) + ); + result.push(getState); + } + return result; } -function addStatePrefix(stateVarName: string, name: string): string { - return `${stateVarName}_${name}`; +/** + * + * @param keyName + * @param value + * @param type + * @param proxySet + * @returns 处理Link装饰器所生成的互操作代码 + */ +export function processLink(keyName: string, value: arkts.Expression, type: arkts.TypeNode, proxySet: Set): arkts.Statement[] { + const valueDecl = arkts.getDecl(value); + const result: arkts.Statement[] = []; + if (valueDecl instanceof arkts.ClassProperty) { + const annotations = valueDecl.annotations; + const decorators: string[] = annotations.map(annotation => { + return (annotation.expr as arkts.Identifier).name; + }); + + let varName: string; + let stateVar: () => arkts.Expression; + + if (hasState(decorators) || hasProvide(decorators) || hasProp(decorators)) { + varName = ((value as arkts.MemberExpression).property as arkts.Identifier).name; + stateVar = (): arkts.TSNonNullExpression => createBackingFieldExpression(varName); + } else if (hasLink(decorators)) { + varName = ((value as arkts.MemberExpression).property as arkts.Identifier).name; + const stateName = `${varName}_State`; + const getSource = linkGetSource(varName, proxySet); + result.push(...getSource); + stateVar = (): arkts.TSNonNullExpression => arkts.factory.createTSNonNullExpression( + arkts.factory.createIdentifier(stateName) + ); + } else { + throw Error('unsupported decorator for Link'); + } + + const proxyGet = setAndGetProxy(varName, type, stateVar, proxySet); + result.push(...proxyGet); + + const setParam = setPropertyESValue( + 'param', + keyName, + arkts.factory.createIdentifier(stateProxy(varName)) + ); + result.push(setParam); + } else { + throw Error('unsupported value for Link'); + } + return result; +} + +/** + * + * @param keyName + * @param value + * @returns 处理一般情况下的属性赋值 + */ +export function processNormal(keyName: string, value: arkts.AstNode): arkts.Statement[] { + const result: arkts.Statement[] = []; + const setProperty = setPropertyESValue( + InteroperAbilityNames.PARAM, + keyName, + getWrapValue(value) + ); + result.push(setProperty); + return result; } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/interop.ts b/arkui-plugins/ui-plugins/interop/interop.ts similarity index 79% rename from arkui-plugins/ui-plugins/interop.ts rename to arkui-plugins/ui-plugins/interop/interop.ts index d6c43d1c7..20305dc9a 100644 --- a/arkui-plugins/ui-plugins/interop.ts +++ b/arkui-plugins/ui-plugins/interop/interop.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * 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 @@ -16,104 +16,21 @@ import * as arkts from '@koalaui/libarkts'; -import { InteroperAbilityNames } from '../common/predefines'; -import { getCustomComponentOptionsName } from './utils'; -import { InteropContext } from './component-transformer'; -import { annotation, backingField, isAnnotation } from '../common/arkts-utils'; -import { hasLink, processLink, processNormal } from './initstatevar'; +import { InteroperAbilityNames } from '../../common/predefines'; +import { getCustomComponentOptionsName } from '../utils'; +import { InteropContext } from '../component-transformer'; +import { annotation, backingField, isAnnotation } from '../../common/arkts-utils'; +import { processLink, processNormal } from './initstatevar'; +import { createProvideInterop, resetFindProvide } from './provide'; +import { getPropertyESValue, getWrapValue, setPropertyESValue, hasLink, createEmptyESValue, hasProp } from './utils'; interface propertyInfo { decorators: string[], type: arkts.TypeNode, } -export function createEmptyESValue(name: string): arkts.VariableDeclaration { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(name), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(InteroperAbilityNames.INITEMPTYOBJECT), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - undefined - ) - ) - ] - ); -} - -export function getWrapValue(value: arkts.AstNode): arkts.AstNode { - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(InteroperAbilityNames.WRAP), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [value] - ); -} - -export function setPropertyESValue(name: string, key: string, wrapValue: arkts.AstNode): arkts.ExpressionStatement { - return arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(name), - arkts.factory.createIdentifier(InteroperAbilityNames.SETPROPERTY), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [ - arkts.factory.createStringLiteral(key), - wrapValue - ] - ) - ); -} - -export function getPropertyESValue(result: string, object: string, key: string): arkts.VariableDeclaration { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(result), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(object), - arkts.factory.createIdentifier(InteroperAbilityNames.GETPROPERTY), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [arkts.factory.create1StringLiteral(key)] - ) - ) - ] - ); -} - -function initialArgs(args: arkts.ObjectExpression, varMap: Map): arkts.Statement[] { - const result: arkts.Statement[] = [ - createEmptyESValue(InteroperAbilityNames.PARAM), - getPropertyESValue('createState', 'global', 'createStateVariable') - ]; - +function initialArgs(args: arkts.ObjectExpression, varMap: Map, updateProp: arkts.Property[]): arkts.Statement[] { + const result: arkts.Statement[] = []; const proxySet = new Set(); for (const property of args.properties) { @@ -125,14 +42,22 @@ function initialArgs(args: arkts.ObjectExpression, varMap: Map): arkts.BlockStatement { +function createWrapperBlock(context: InteropContext, varMap: Map, + updateProp: arkts.Property[]): arkts.BlockStatement { const className = context.className; const path = context.path; const args = context.arguments; @@ -438,10 +350,16 @@ function createWrapperBlock(context: InteropContext, varMap: Map): arkts.ArrowFunctionExpression { - const block = createWrapperBlock(context, varMap); +function createInitializer(context: InteropContext, varMap: Map, + updateProp: arkts.Property[]): arkts.ArrowFunctionExpression { + const block = createWrapperBlock(context, varMap, updateProp); return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( block, @@ -477,12 +397,36 @@ function createInitializer(context: InteropContext, varMap: Map): arkts.ArrowFunctionExpression { +function updateStateVars(updateProp: arkts.Property[]): arkts.Statement { + const obj = arkts.factory.createObjectExpression( + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + updateProp, + false + ); + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('component'), + arkts.factory.createIdentifier('invokeMethod'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createStringLiteral('updateStateVars'), + getWrapValue(obj) + ] + ); +} + +function createUpdater(esvalue: arkts.ETSTypeReference, varMap: Map, + updateProp: arkts.Property[]): arkts.ArrowFunctionExpression { + const updateState = updateStateVars(updateProp); return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( arkts.factory.createBlock( [ - + updateState ] ), arkts.factory.createFunctionSignature( @@ -524,42 +468,6 @@ function generateVarMap(node: arkts.Identifier): Map { return result; } -export function updateArkUICompatible(node: arkts.CallExpression): arkts.CallExpression { - const classInterop = (node.expression as arkts.MemberExpression).object as arkts.Identifier; - const className = classInterop.name; - const args = node.arguments; - const path = (args[0] as arkts.StringLiteral).str; - const line = args[1] instanceof arkts.UndefinedLiteral ? undefined : (args[1] as arkts.NumberLiteral).value; - const col = args[2] instanceof arkts.UndefinedLiteral ? undefined : (args[2] as arkts.NumberLiteral).value; - const options = args[3] instanceof arkts.UndefinedLiteral ? undefined : args[3] as arkts.ObjectExpression; - const context: InteropContext = { - className: className, - path: path, - line: line, - col: col, - arguments: options - }; - - const varMap: Map = generateVarMap(classInterop); - const esvalue = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) - ) - ); - const initializer = createInitializer(context, varMap); - const updater = createUpdater(esvalue, varMap); - return arkts.factory.updateCallExpression( - node, - arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), - undefined, - [ - initializer, - updater, - ] - ); -} - - function generateStructInfo(context: InteropContext): arkts.AstNode[] { const result: arkts.AstNode[] = [ arkts.factory.createStringLiteral(context.path), @@ -571,7 +479,17 @@ function generateStructInfo(context: InteropContext): arkts.AstNode[] { } -export function generateTempCallFunction(context: InteropContext): arkts.CallExpression { +/** + * After Parsed阶段 + * @param {Object} context - 组件上下文信息 + * @param {string} context.className - 组件类名 + * @param {string} context.path - 组件文件路径 + * @param {number} [context.line] - 组件在文件中的行号(可选) + * @param {number} [context.col] - 组件在文件中的列号(可选) + * @param {Object} [context.arguments] - 传递给组件的额外参数(可选) + * @returns {Object} 返回带有互操作标识的1.1组件静态方法,用于承载相关信息 + */ +export function generateInstantiateInterop(context: InteropContext): arkts.CallExpression { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier(context.className), @@ -585,6 +503,11 @@ export function generateTempCallFunction(context: InteropContext): arkts.CallExp ); } +/** + * After Checked阶段 + * @param node + * @returns {boolean} 判断节点是否为带有互操作标识的CallExpression + */ export function isArkUICompatible(node: arkts.AstNode): boolean { if (node instanceof arkts.CallExpression && node.expression instanceof arkts.MemberExpression && node.expression.property instanceof arkts.Identifier && @@ -592,4 +515,46 @@ export function isArkUICompatible(node: arkts.AstNode): boolean { return true; } return false; +} + + +/** + * + * @param node + * @returns After Checked阶段,将带有互操作标识的1.1组件静态方法转换为ArkUICompatible函数 + */ +export function generateArkUICompatible(node: arkts.CallExpression): arkts.CallExpression { + const classInterop = (node.expression as arkts.MemberExpression).object as arkts.Identifier; + const className = classInterop.name; + const args = node.arguments; + const path = (args[0] as arkts.StringLiteral).str; + const line = args[1] instanceof arkts.UndefinedLiteral ? undefined : (args[1] as arkts.NumberLiteral).value; + const col = args[2] instanceof arkts.UndefinedLiteral ? undefined : (args[2] as arkts.NumberLiteral).value; + const options = args[3] instanceof arkts.UndefinedLiteral ? undefined : args[3] as arkts.ObjectExpression; + const context: InteropContext = { + className: className, + path: path, + line: line, + col: col, + arguments: options + }; + + const varMap: Map = generateVarMap(classInterop); + const esvalue = arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) + ) + ); + const updateProp:arkts.Property[] = []; + const initializer = createInitializer(context, varMap, updateProp); + const updater = createUpdater(esvalue, varMap, updateProp); + return arkts.factory.updateCallExpression( + node, + arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), + undefined, + [ + initializer, + updater, + ] + ); } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/legacy-transformer.ts b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts similarity index 83% rename from arkui-plugins/ui-plugins/legacy-transformer.ts rename to arkui-plugins/ui-plugins/interop/legacy-transformer.ts index 2791e0192..f5bfb7810 100644 --- a/arkui-plugins/ui-plugins/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * 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 @@ -13,21 +13,32 @@ * limitations under the License. */ + + import * as arkts from '@koalaui/libarkts'; -import { getInteropPath } from '../path'; +import { getInteropPath } from '../../path'; const interop = require(getInteropPath()); const nullptr = interop.nullptr; -import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; -import { InteroperAbilityNames } from '../common/predefines'; -import { getCustomComponentOptionsName } from './utils'; +import { AbstractVisitor, VisitorOptions } from '../../common/abstract-visitor'; +import { InteroperAbilityNames } from '../../common/predefines'; +import { getCustomComponentOptionsName } from '../utils'; +import { annotation } from 'common/arkts-utils'; interface LegacyTransformerOptions extends VisitorOptions { structList?: string[] } +type ScopeInfo = { + name: string; + isEntry?: boolean; + isComponent?: boolean; + isReusable?: boolean; +}; + export class LegacyTransformer extends AbstractVisitor { private structList: string[] = []; private componentInterfaceCollection: arkts.TSInterfaceDeclaration[] = []; + private scopeInfos: ScopeInfo[] = []; constructor(options?: LegacyTransformerOptions) { const _options: LegacyTransformerOptions = options ?? {}; @@ -35,9 +46,12 @@ export class LegacyTransformer extends AbstractVisitor { this.structList = _options.structList ?? []; } + // TODO: check reset reset(): void { super.reset(); + this.structList = []; this.componentInterfaceCollection = []; + this.scopeInfos = []; } getList(): string[] { @@ -145,10 +159,6 @@ export class LegacyTransformer extends AbstractVisitor { arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE ); - console.log('print legacyclass definition' + newDefinition.dumpSrc()); - - - //TODO: need check if (arkts.isStructDeclaration(node)) { const _node = arkts.factory.createClassDeclaration(newDefinition); _node.modifiers = node.modifiers; @@ -230,19 +240,44 @@ export class LegacyTransformer extends AbstractVisitor { return node; } + enter(node: arkts.AstNode): void { + if (arkts.isStructDeclaration(node) && !!node.definition.ident) { + const scopeInfo: ScopeInfo = { name: node.definition.ident.name }; + this.scopeInfos.push(scopeInfo); + } + } + + exit(node: arkts.AstNode): void { + if (arkts.isStructDeclaration(node) || arkts.isClassDeclaration(node)) { + if (!node.definition || !node.definition.ident || this.scopeInfos.length === 0) { + return; + } + if (this.scopeInfos[this.scopeInfos.length - 1]?.name === node.definition.ident.name) { + this.scopeInfos.pop(); + } + } + } + visitor(node: arkts.AstNode): arkts.AstNode { + this.enter(node); const newNode = this.visitEachChild(node); if (arkts.isEtsScript(newNode)) { return this.processEtsScript(newNode); } if (arkts.isStructDeclaration(newNode)) { - const className = node.definition?.ident?.name; - const memberMap = this.collectComponentMembers(node as arkts.StructDeclaration, className); + const definition = newNode.definition!; + const annotations = definition.annotations; + if (annotations.some(annotation => annotation instanceof arkts.Identifier && annotation.name === 'Component')) { + return newNode; + } + const className = newNode.definition?.ident?.name!; + const memberMap = this.collectComponentMembers(newNode as arkts.StructDeclaration, className); this.componentInterfaceCollection.push(this.generateComponentInterface(className, node.modifiers, memberMap)); const updateNode = this.processComponent(newNode); + this.exit(newNode); return updateNode; } - if (arkts.isMethodDefinition(newNode)) { + if (this.scopeInfos.length > 0 && arkts.isMethodDefinition(newNode)) { const kind = newNode.kind; if (kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR) { const updateNode = this.processConstructor(newNode); diff --git a/arkui-plugins/ui-plugins/interop/provide.ts b/arkui-plugins/ui-plugins/interop/provide.ts new file mode 100644 index 000000000..0f37705f7 --- /dev/null +++ b/arkui-plugins/ui-plugins/interop/provide.ts @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +import * as arkts from '@koalaui/libarkts'; +import { getPropertyESValue } from './utils'; +import { createVariableLet, setStateProxy } from './initstatevar'; + + +function findProvide(): arkts.Statement { + return createVariableLet( + 'provide', + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('findProvide'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + [ + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('Object') + ) + ) + ], + [ + arkts.factory.createIdentifier('providedPropName') + ] + ) + ); +} + +function setProvideProxy(): arkts.Statement[] { + return setStateProxy( + () => arkts.factory.createTSNonNullExpression( + arkts.factory.createIdentifier('provide') + ) + ); +} + +function getProvideProxy(): arkts.Statement { + return createVariableLet( + 'proxy', + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression( + arkts.factory.createIdentifier('provide') + ), + arkts.factory.createIdentifier('getProxy'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined + ) + ); +} + +function returnProvide(): arkts.Statement { + return arkts.factory.createReturnStatement( + arkts.factory.createTSNonNullExpression( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSAsExpression( + arkts.factory.createIdentifier('proxy'), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('ESValue') + ) + ), + false + ), + arkts.factory.createIdentifier('unwrap'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined + ) + ) + ); +} + +function createProvideBlock(): arkts.BlockStatement { + const provide = findProvide(); + const setProxy = setProvideProxy(); + const getProxy = getProvideProxy(); + const returnStatement = returnProvide(); + return arkts.factory.createBlock([provide, ...setProxy, getProxy, returnStatement]); +} + +function findProvideCallback(): arkts.Statement { + const block = createProvideBlock(); + const callback = createVariableLet( + 'findProvideInterop', + arkts.factory.createArrowFunction( + arkts.factory.createScriptFunction( + block, + arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier('providedPropName', + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('string') + ) + ) + ), + undefined, + ), + ], + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier('Object') + ) + ), + false + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + ) + ) + ); + return callback; +} + +export function createProvideInterop(): arkts.Statement[] { + const func = getPropertyESValue( + 'setFindProvideInterop', + 'global', + 'setFindProvideInterop' + ); + const callback = findProvideCallback(); + const invokeFunc = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('setFindProvideInterop'), + arkts.factory.createIdentifier('invoke'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createIdentifier('findProvideInterop') + ] + ) + ); + return [func, callback, invokeFunc]; +} + + +/** + * + * @returns ViewPU.resetFindInterop() + */ +export function resetFindProvide(): arkts.Statement { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('structObject'), + arkts.factory.createIdentifier('invokeMethod'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createStringLiteral('resetFindProvide') + ] + ); +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/interop/utils.ts b/arkui-plugins/ui-plugins/interop/utils.ts new file mode 100644 index 000000000..70e997af6 --- /dev/null +++ b/arkui-plugins/ui-plugins/interop/utils.ts @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +import * as arkts from '@koalaui/libarkts'; +import { InteroperAbilityNames } from '../../common/predefines'; + + +/** + * + * @param result + * @returns let result = ESValue.instantiateEmptyObject() + */ +export function createEmptyESValue(result: string): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier(result), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), + arkts.factory.createIdentifier(InteroperAbilityNames.INITEMPTYOBJECT), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined + ) + ) + ] + ); +} + +/** + * + * @param value + * @returns ESValue.wrap(value) + */ +export function getWrapValue(value: arkts.AstNode): arkts.AstNode { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), + arkts.factory.createIdentifier(InteroperAbilityNames.WRAP), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [value] + ); +} + +/** + * + * @param object + * @param key + * @param value + * @returns object.setProperty(key, value) + */ +export function setPropertyESValue(object: string, key: string, value: arkts.AstNode): arkts.ExpressionStatement { + return arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(object), + arkts.factory.createIdentifier(InteroperAbilityNames.SETPROPERTY), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createStringLiteral(key), + value + ] + ) + ); +} + +/** + * + * @param result + * @param object + * @param key + * @returns let result = object.getProperty(key) + */ +export function getPropertyESValue(result: string, object: string, key: string): arkts.VariableDeclaration { + return arkts.factory.createVariableDeclaration( + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, + arkts.factory.createIdentifier(result), + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(object), + arkts.factory.createIdentifier(InteroperAbilityNames.GETPROPERTY), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [arkts.factory.create1StringLiteral(key)] + ) + ) + ] + ); +} + +/** + * + * @param stateName + * @param block + * @returns if (stateName.getProxy() === undefined) { block } + */ +export function ifStateHasProxy(stateVar: () => arkts.Expression, block: arkts.BlockStatement): arkts.Statement { + return arkts.factory.createIfStatement( + arkts.factory.createBinaryExpression( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + stateVar(), + arkts.factory.createIdentifier('getProxy'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + true + ), + undefined, + undefined, + ), + arkts.factory.createUndefinedLiteral(), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_STRICT_EQUAL + ), + block + ); +} + +/** + * + * @param decorators + * @returns 判断是否包含Link装饰器 + */ +export function hasLink(decorators: string[]): boolean { + return decorators.some(decorator => decorator === 'Link'); +} + +export function hasState(decorators: string[]): boolean { + return decorators.some(decorator => decorator === 'State'); +} + +export function hasProp(decorators: string[]): boolean { + return decorators.some(decorator => decorator === 'Prop'); +} + +export function hasProvide(decorators: string[]): boolean { + return decorators.some(decorator => decorator === 'Provide'); +} + +/** + * + * @param stateVarName + * @param name + * @returns 带有状态变量标识的变量命名 + */ +export function stateProxy(stateVarName: string): string { + return `${stateVarName}_State_Proxy`; +} + -- Gitee From c56612bbe49057996544b23b656499f9b91adb7f Mon Sep 17 00:00:00 2001 From: xieziang Date: Mon, 19 May 2025 21:31:56 +0800 Subject: [PATCH 114/123] add position information to class Change-Id: I3c189337b46c6454b237698fc33fc151cd010d46 Signed-off-by: xieziang --- .../ui-plugins/component-transformer.ts | 3 +++ koala-wrapper/native/src/bridges.cc | 22 ++++++++++++++++++- koala-wrapper/src/Es2pandaNativeModule.ts | 8 +++++++ koala-wrapper/src/arkts-api/peers/AstNode.ts | 17 ++++++++++++++ 4 files changed, 49 insertions(+), 1 deletion(-) diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 4485bc9bd..862c6d4af 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -242,8 +242,11 @@ export class ComponentTransformer extends AbstractVisitor { ); if (arkts.isStructDeclaration(node)) { + arkts.classDefinitionSetFromStructModifier(newDefinition); const _node = arkts.factory.createClassDeclaration(newDefinition); _node.modifiers = node.modifiers; + _node.startPosition = node.startPosition; + _node.endPosition = node.endPosition; return _node; } else { return arkts.factory.updateClassDeclaration(node, newDefinition); diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index e765f48ae..5333ea8b5 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -530,6 +530,16 @@ KNativePointer impl_AstNodeStartConst(KNativePointer context, KNativePointer rec } KOALA_INTEROP_2(AstNodeStartConst, KNativePointer, KNativePointer, KNativePointer); +void impl_AstNodeSetStart(KNativePointer context, KNativePointer receiver, KNativePointer start) +{ + auto _context = reinterpret_cast(context); + auto _receiver = reinterpret_cast(receiver); + auto _start = reinterpret_cast(start); + GetImpl()->AstNodeSetStart(_context, _receiver, _start); + return; +} +KOALA_INTEROP_V3(AstNodeSetStart, KNativePointer, KNativePointer, KNativePointer) + KNativePointer impl_AstNodeEndConst(KNativePointer context, KNativePointer receiver) { const auto _context = reinterpret_cast(context); @@ -538,6 +548,16 @@ KNativePointer impl_AstNodeEndConst(KNativePointer context, KNativePointer recei } KOALA_INTEROP_2(AstNodeEndConst, KNativePointer, KNativePointer, KNativePointer); +void impl_AstNodeSetEnd(KNativePointer context, KNativePointer receiver, KNativePointer end) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + const auto _end = reinterpret_cast(end); + GetImpl()->AstNodeSetEnd(_context, _receiver, _end); + return; +} +KOALA_INTEROP_V3(AstNodeSetEnd, KNativePointer, KNativePointer, KNativePointer); + KBoolean impl_IsArrayExpression(KNativePointer nodePtr) { auto node = reinterpret_cast(nodePtr); @@ -635,4 +655,4 @@ void impl_LogDiagnosticWithSuggestion(KNativePointer context, KNativePointer dia const auto _range = reinterpret_cast(range); GetImpl()->LogDiagnosticWithSuggestion(_context, _diagnosticInfo, _suggestionInfo, _range); } -KOALA_INTEROP_V4(LogDiagnosticWithSuggestion, KNativePointer, KNativePointer, KNativePointer, KNativePointer); \ No newline at end of file +KOALA_INTEROP_V4(LogDiagnosticWithSuggestion, KNativePointer, KNativePointer, KNativePointer, KNativePointer); diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index e509c21e3..0ca1523ec 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -831,10 +831,18 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _AstNodeSetStart(context: KNativePointer, receiver: KNativePointer, start: KNativePointer): void { + throw new Error('Not implemented'); + } + _AstNodeEndConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { throw new Error('Not implemented'); } + _AstNodeSetEnd(context: KNativePointer, receiver: KNativePointer, end: KNativePointer): void { + throw new Error('Not implemented'); + } + _ClassVariableDeclaration(context: KNativePointer, classInstance: KNativePointer): KNativePointer { throw new Error('Not implemented'); } diff --git a/koala-wrapper/src/arkts-api/peers/AstNode.ts b/koala-wrapper/src/arkts-api/peers/AstNode.ts index e60cd5c06..ffab3c5cf 100644 --- a/koala-wrapper/src/arkts-api/peers/AstNode.ts +++ b/koala-wrapper/src/arkts-api/peers/AstNode.ts @@ -20,6 +20,7 @@ import { throwError } from '../../utils'; import { Es2pandaModifierFlags } from '../../generated/Es2pandaEnums'; import { ArktsObject } from './ArktsObject'; import { Es2pandaAstNodeType } from '../../Es2pandaEnums'; +import { SourcePosition } from './SourcePosition'; export abstract class AstNode extends ArktsObject { protected constructor(peer: KNativePointer) { @@ -128,6 +129,22 @@ export abstract class AstNode extends ArktsObject { public get isStatic(): boolean { return global.generatedEs2panda._AstNodeIsStaticConst(global.context, this.peer); } + + public get startPosition(): SourcePosition { + return new SourcePosition(global.es2panda._AstNodeStartConst(global.context, this.peer)); + } + + public set startPosition(start: SourcePosition) { + global.es2panda._AstNodeSetStart(global.context, this.peer, start.peer); + } + + public get endPosition(): SourcePosition { + return new SourcePosition(global.es2panda._AstNodeEndConst(global.context, this.peer)); + } + + public set endPosition(end: SourcePosition) { + global.es2panda._AstNodeSetEnd(global.context, this.peer, end.peer); + } } export class UnsupportedNode extends AstNode { -- Gitee From 7c121d1ebf49adeeac64e3ce72cf212b992c4764 Mon Sep 17 00:00:00 2001 From: Yuxin Feng Date: Thu, 5 Jun 2025 11:10:25 +0800 Subject: [PATCH 115/123] refactor statemgmt uiplugin transform Signed-off-by: Yuxin Feng Change-Id: Ifdb04be4bf7a2ad4a2d1797bbf12a08e17cd2aa0 --- arkui-plugins/common/predefines.ts | 91 +++--- .../property-translators/consume.ts | 21 +- .../property-translators/factory.ts | 258 ++++++++++++++---- .../ui-plugins/property-translators/link.ts | 24 +- .../property-translators/objectlink.ts | 53 ++-- .../property-translators/observedTrack.ts | 209 ++++---------- .../ui-plugins/property-translators/prop.ts | 68 ++--- .../property-translators/provide.ts | 28 +- .../ui-plugins/property-translators/state.ts | 24 +- .../property-translators/storageProp.ts | 32 +-- .../property-translators/storagelink.ts | 33 +-- .../ui-plugins/property-translators/utils.ts | 3 +- .../ui-plugins/struct-translators/factory.ts | 50 +--- 13 files changed, 445 insertions(+), 449 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 044a48b95..4abbc3b52 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -78,32 +78,44 @@ export enum DecoratorIntrinsicNames { } export enum StateManagementTypes { - STATE_DECORATED = 'StateDecoratedVariable', - LINK_DECORATED = 'LinkDecoratedVariable', - STORAGE_LINK_DECORATED = 'StorageLinkDecoratedVariable', - STORAGE_PROP_DECORATED = 'StoragePropDecoratedVariable', - DECORATED_V1 = 'DecoratedV1VariableBase', - PROP_DECORATED = 'PropDecoratedVariable', + STATE_MANAGEMENT_FACTORY = 'STATE_MGMT_FACTORY', + STATE_DECORATED = 'IStateDecoratedVariable', + LINK_DECORATED = 'ILinkDecoratedVariable', + LINK_SOURCE_TYPE = 'LinkSourceType', + STORAGE_LINK_DECORATED = 'IStorageLinkDecoratedVariable', + STORAGE_PROP_DECORATED = 'IStoragePropDecoratedVariable', + PROP_DECORATED = 'IPropDecoratedVariable', MUTABLE_STATE = 'MutableState', - MUTABLE_STATE_META = 'MutableStateMeta', SYNCED_PROPERTY = 'SyncedProperty', - PROVIDE_DECORATED = 'ProvideDecoratedVariable', - CONSUME_DECORATED = 'ConsumeDecoratedVariable', - OBJECT_LINK_DECORATED = 'ObjectLinkDecoratedVariable', - BACKING_VALUE = 'BackingValue', - SET_OBSERVATION_DEPTH = 'setObservationDepth', + PROVIDE_DECORATED = 'IProvideDecoratedVariable', + CONSUME_DECORATED = 'IConsumeDecoratedVariable', + OBJECT_LINK_DECORATED = 'IObjectLinkDecoratedVariable', + MUTABLE_STATE_META = 'IMutableStateMeta', OBSERVED_OBJECT = 'IObservedObject', WATCH_ID_TYPE = 'WatchIdType', - SUBSCRIBED_WATCHES = 'SubscribedWatches', + RENDER_ID_TYPE = 'RenderIdType', + OBSERVE = 'OBSERVE', + META = '__meta', + SUBSCRIBED_WATCHES = 'ISubscribedWatches', STORAGE_LINK_STATE = 'StorageLinkState', OBSERVABLE_PROXY = 'observableProxy', PROP_STATE = 'propState', - INT_32 = 'int32', + UPDATE = 'update', + MAKE_STATE = 'makeState', + MAKE_LINK = 'makeLink', + MAKE_PROP = 'makeProp', + MAKE_STORAGE_PROP = 'makeStorageProp', + MAKE_STORAGE_LINK = 'makeStorageLink', + MAKE_PROVIDE = 'makeProvide', + MAKE_CONSUME = 'makeConsume', + MAKE_OBJECT_LINK = 'makeObjectLink', + MAKE_SUBSCRIBED_WATCHES = 'makeSubscribedWatches', + MAKE_MUTABLESTATE_META = 'makeMutableStateMeta', } export const DECORATOR_TYPE_MAP = new Map([ [DecoratorNames.STATE, StateManagementTypes.STATE_DECORATED], - [DecoratorNames.LINK, StateManagementTypes.DECORATED_V1], + [DecoratorNames.LINK, StateManagementTypes.LINK_SOURCE_TYPE], [DecoratorNames.PROP, StateManagementTypes.PROP_DECORATED], [DecoratorNames.STORAGE_LINK, StateManagementTypes.STORAGE_LINK_DECORATED], [DecoratorNames.STORAGE_PROP, StateManagementTypes.STORAGE_PROP_DECORATED], @@ -118,14 +130,14 @@ export const INTERMEDIATE_IMPORT_SOURCE: Map = new Map = new Map = new Map([ [Dollars.TRANSFORM_DOLLAR_RESOURCE, 'arkui.component.resources'], [Dollars.TRANSFORM_DOLLAR_RAWFILE, 'arkui.component.resources'], - [StateManagementTypes.STATE_DECORATED, 'arkui.stateManagement.decorators.decoratorState'], - [StateManagementTypes.LINK_DECORATED, 'arkui.stateManagement.decorators.decoratorLink'], - [StateManagementTypes.STORAGE_LINK_DECORATED, 'arkui.stateManagement.decorators.decoratorStorageLink'], - [StateManagementTypes.STORAGE_PROP_DECORATED, 'arkui.stateManagement.decorators.decoratorStorageProp'], - [StateManagementTypes.DECORATED_V1, 'arkui.stateManagement.base.decoratorBase'], - [StateManagementTypes.PROP_DECORATED, 'arkui.stateManagement.decorators.decoratorProp'], [StateManagementTypes.MUTABLE_STATE, 'arkui.stateManagement.runtime'], - [StateManagementTypes.MUTABLE_STATE_META, 'arkui.stateManagement.base.mutableStateMeta'], [StateManagementTypes.SYNCED_PROPERTY, 'arkui.stateManagement.runtime'], - [StateManagementTypes.PROVIDE_DECORATED, 'arkui.stateManagement.decorators.decoratorProvide'], - [StateManagementTypes.CONSUME_DECORATED, 'arkui.stateManagement.decorators.decoratorConsume'], - [StateManagementTypes.OBJECT_LINK_DECORATED, 'arkui.stateManagement.decorators.decoratorObjectLink'], - [StateManagementTypes.BACKING_VALUE, 'arkui.stateManagement.base.backingValue'], - [StateManagementTypes.SET_OBSERVATION_DEPTH, 'arkui.stateManagement.base.iObservedObject'], - [StateManagementTypes.OBSERVED_OBJECT, 'arkui.stateManagement.base.iObservedObject'], - [StateManagementTypes.WATCH_ID_TYPE, 'arkui.stateManagement.decorators.decoratorWatch'], - [StateManagementTypes.SUBSCRIBED_WATCHES, 'arkui.stateManagement.decorators.decoratorWatch'], [StateManagementTypes.STORAGE_LINK_STATE, 'arkui.stateManagement.runtime'], [StateManagementTypes.OBSERVABLE_PROXY, 'arkui.stateManagement.runtime'], [StateManagementTypes.PROP_STATE, 'arkui.stateManagement.runtime'], - [StateManagementTypes.INT_32, '@koalaui.runtime.common'], ]); + +export enum GetSetTypes { + GET = 'get', + SET = 'set', +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/consume.ts b/arkui-plugins/ui-plugins/property-translators/consume.ts index d4f0176b2..8bd40ec2e 100644 --- a/arkui-plugins/ui-plugins/property-translators/consume.ts +++ b/arkui-plugins/ui-plugins/property-translators/consume.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { DecoratorNames, GetSetTypes, StateManagementTypes } from '../../common/predefines'; import { generateToRecord, createGetter, @@ -56,9 +56,9 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, GetSetTypes.GET); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') + generateGetOrSetCall(thisValue, GetSetTypes.SET) ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, @@ -91,11 +91,22 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer } generateInitializeStruct(originalName: string, newName: string): arkts.AstNode { - const alias = getValueInAnnotation(this.property, DecoratorNames.CONSUME); + const args: arkts.Expression[] = [ + arkts.factory.create1StringLiteral(originalName), + arkts.factory.create1StringLiteral( + getValueInAnnotation(this.property, DecoratorNames.CONSUME) ?? originalName + ), + ]; + factory.judgeIfAddWatchFunc(args, this.property); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateInitConsumeCall(originalName, this.property, alias ?? originalName) + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_CONSUME, + this.property.typeAnnotation, + args, + true + ) ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts index 904811f12..f77047363 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -18,7 +18,7 @@ import { GenSymGenerator } from '../../common/gensym-generator'; import { DecoratorNames, DECORATOR_TYPE_MAP, StateManagementTypes } from '../../common/predefines'; import { factory as UIFactory } from '../ui-factory'; import { collectStateManagementTypeImport, getValueInAnnotation, hasDecorator, removeDecorator } from './utils'; -import { addMemoAnnotation, findCanAddMemoFromTypeAnnotation } from '../utils'; +import { addMemoAnnotation, findCanAddMemoFromTypeAnnotation, CustomComponentNames } from '../utils'; export class factory { /** @@ -235,64 +235,49 @@ export class factory { } /* - * create `this.addProvidedVar(, , initializers?. ?? , , watchFunc)`. + * create `StateMgmtFactory.(this, ...);`. */ - static generateAddProvideVarCall( - originalName: string, - property: arkts.ClassProperty, - alias: string, - allowOverride: boolean = false + static generateStateMgmtFactoryCall( + makeType: StateManagementTypes, + typeArguments: arkts.TypeNode | undefined, + args: arkts.AstNode[], + argsContainsThis: boolean ): arkts.CallExpression { - const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.create1StringLiteral(alias), - arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName - ), - property.value ?? arkts.factory.createUndefinedLiteral(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING - ), - arkts.factory.createBooleanLiteral(allowOverride), - ]; - factory.judgeIfAddWatchFunc(args, property); + collectStateManagementTypeImport(StateManagementTypes.STATE_MANAGEMENT_FACTORY); return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('addProvidedVar'), + arkts.factory.createIdentifier(StateManagementTypes.STATE_MANAGEMENT_FACTORY), + arkts.factory.createIdentifier(makeType), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ), - property.typeAnnotation ? [property.typeAnnotation.clone()] : undefined, - args + typeArguments ? [typeArguments] : undefined, + [...(argsContainsThis ? [arkts.factory.createThisExpression()] : []), ...args] ); } /* - * create `this.initConsume(, , watchFunc)`. + * create if statement in __updateStruct method. */ - static generateInitConsumeCall( + static createIfInUpdateStruct( originalName: string, - property: arkts.ClassProperty, - alias: string - ): arkts.CallExpression { - const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.create1StringLiteral(alias), - ]; - factory.judgeIfAddWatchFunc(args, property); - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('initConsume'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false + member: arkts.Expression, + args: arkts.AstNode[] + ): arkts.IfStatement { + const binaryItem = arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), + originalName ), - property.typeAnnotation ? [property.typeAnnotation.clone()] : undefined, - args + arkts.factory.createUndefinedLiteral(), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL + ); + return arkts.factory.createIfStatement( + binaryItem, + arkts.factory.createBlock([ + arkts.factory.createExpressionStatement(arkts.factory.createCallExpression(member, undefined, args)), + ]) ); } @@ -341,17 +326,13 @@ export class factory { ); } + /* + * create watch related members in Observed/Track classes + */ static createWatchMembers(): arkts.AstNode[] { const subscribedWatches: arkts.ClassProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier('subscribedWatches'), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.SUBSCRIBED_WATCHES) - ) - ), - [] - ), + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_SUBSCRIBED_WATCHES, undefined, [], false), arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier(StateManagementTypes.SUBSCRIBED_WATCHES) @@ -389,6 +370,9 @@ export class factory { return [subscribedWatches, addWatchSubscriber, removeWatchSubscriber, executeOnSubscribingWatches]; } + /* + * helper for createWatchMembers to create watch methods + */ static createWatchMethod( methodName: string, returnType: arkts.Es2pandaPrimitiveType, @@ -441,6 +425,9 @@ export class factory { ); } + /* + * helper for createWatchMethod, generates this.subscribedWatches.xxx + */ static thisSubscribedWatchesMember(member: string): arkts.MemberExpression { return arkts.factory.createMemberExpression( arkts.factory.createMemberExpression( @@ -457,6 +444,173 @@ export class factory { ); } + /* + * create ____V1RenderId related members in Observed/Track classes + */ + static createV1RenderIdMembers(): arkts.AstNode[] { + const v1RenderId: arkts.ClassProperty = arkts.factory.createClassProperty( + arkts.factory.createIdentifier('____V1RenderId'), + arkts.factory.createNumericLiteral(0), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.RENDER_ID_TYPE) + ) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + collectStateManagementTypeImport(StateManagementTypes.RENDER_ID_TYPE); + const setV1RenderId: arkts.MethodDefinition = factory.setV1RenderId(); + return [v1RenderId, setV1RenderId]; + } + + /* + * helper for createV1RenderIdMembers to generate setV1RenderId method + */ + static setV1RenderId(): arkts.MethodDefinition { + const assignRenderId: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('____V1RenderId'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + arkts.factory.createIdentifier('renderId') + ) + ); + const funcSig: arkts.FunctionSignature = arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + 'renderId', + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.RENDER_ID_TYPE) + ) + ) + ), + undefined + ), + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ); + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + arkts.factory.createIdentifier('setV1RenderId'), + arkts.factory.createScriptFunction( + arkts.factory.createBlock([assignRenderId]), + funcSig, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false + ); + } + + /* + * create conditionalAddRef method in Observed/Track classes + */ + static conditionalAddRef(): arkts.MethodDefinition { + const funcSig: arkts.FunctionSignature = arkts.factory.createFunctionSignature( + undefined, + [ + arkts.factory.createParameterDeclaration( + arkts.factory.createIdentifier( + 'meta', + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) + ) + ) + ), + undefined + ), + ], + arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false + ); + collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); + const shouldAddRef: arkts.IfStatement = factory.shouldAddRef(); + return arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + arkts.factory.createIdentifier('conditionalAddRef'), + arkts.factory.createScriptFunction( + arkts.factory.createBlock([shouldAddRef]), + funcSig, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PROTECTED + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PROTECTED, + false + ); + } + + /* + * helper for conditionalAddRef to generate shouldAddRef method + */ + static shouldAddRef(): arkts.IfStatement { + const test: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(StateManagementTypes.OBSERVE), + arkts.factory.createIdentifier('shouldAddRef'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('____V1RenderId'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + ] + ); + collectStateManagementTypeImport(StateManagementTypes.OBSERVE); + const consequent: arkts.BlockStatement = arkts.factory.createBlock([ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('meta'), + arkts.factory.createIdentifier('addRef'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + undefined + ) + ), + ]); + return arkts.factory.createIfStatement(test, consequent); + } + + /* + * helper to create meta field in classes with only @Observe and no @Track + */ + static createMetaInObservedClass(): arkts.ClassProperty { + collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); + return arkts.factory.createClassProperty( + arkts.factory.createIdentifier(StateManagementTypes.META), + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_MUTABLESTATE_META, undefined, [], false), + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) + ) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); + } + /** * add `@memo` to the `@Builder` methods in class. */ diff --git a/arkui-plugins/ui-plugins/property-translators/link.ts b/arkui-plugins/ui-plugins/property-translators/link.ts index 09a72cda4..65217d539 100644 --- a/arkui-plugins/ui-plugins/property-translators/link.ts +++ b/arkui-plugins/ui-plugins/property-translators/link.ts @@ -16,7 +16,8 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { DecoratorNames, GetSetTypes, StateManagementTypes } from '../../common/predefines'; +import { CustomComponentNames } from '../utils'; import { generateToRecord, createGetter, @@ -51,27 +52,34 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon generateInitializeStruct(newName: string, originalName: string) { const test = factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), + arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), newName ); const args: arkts.Expression[] = [ arkts.factory.create1StringLiteral(originalName), arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', newName, false, true) + factory.createNonNullOrOptionalMemberExpression( + CustomComponentNames.COMPONENT_INITIALIZERS_NAME, + newName, + false, + true + ) ), ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.LINK_DECORATED); + collectStateManagementTypeImport(StateManagementTypes.LINK_SOURCE_TYPE); const consequent = arkts.BlockStatement.createBlockStatement([ arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( generateThisBacking(newName, false, false), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.createNewDecoratedInstantiate( - StateManagementTypes.LINK_DECORATED, + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_LINK, this.property.typeAnnotation, - args + args, + true ) ) ), @@ -88,9 +96,9 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, GetSetTypes.GET); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') + generateGetOrSetCall(thisValue, GetSetTypes.SET) ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, diff --git a/arkui-plugins/ui-plugins/property-translators/objectlink.ts b/arkui-plugins/ui-plugins/property-translators/objectlink.ts index 27e7af8fc..2c2089794 100644 --- a/arkui-plugins/ui-plugins/property-translators/objectlink.ts +++ b/arkui-plugins/ui-plugins/property-translators/objectlink.ts @@ -16,7 +16,8 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { DecoratorNames, GetSetTypes, StateManagementTypes } from '../../common/predefines'; +import { CustomComponentNames } from '../utils'; import { createGetter, generateGetOrSetCall, @@ -55,60 +56,42 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const initializers = arkts.factory.createTSNonNullExpression( factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), + arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), originalName ) ); - const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), initializers]; factory.judgeIfAddWatchFunc(args, this.property); - const newClass = arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('ObjectLinkDecoratedVariable'), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - args - ); - return arkts.factory.createAssignmentExpression( generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - newClass + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_OBJECT_LINK, + this.property.typeAnnotation, + args, + true + ) ); } generateUpdateStruct(newName: string, originalName: string): arkts.AstNode { - const binaryItem = arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName - ), - arkts.factory.createUndefinedLiteral(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL - ); const member: arkts.MemberExpression = arkts.factory.createMemberExpression( generateThisBacking(newName, false, true), - arkts.factory.createIdentifier('update'), + arkts.factory.createIdentifier(StateManagementTypes.UPDATE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ); const nonNullItem = arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true) - ); - return arkts.factory.createIfStatement( - binaryItem, - arkts.factory.createBlock([ - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(member, undefined, [nonNullItem]) - ), - ]) + factory.createNonNullOrOptionalMemberExpression( + CustomComponentNames.COMPONENT_INITIALIZERS_NAME, + originalName, + false, + true + ) ); + return factory.createIfInUpdateStruct(originalName, member, [nonNullItem]); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { @@ -119,7 +102,7 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, GetSetTypes.GET); const getter: arkts.MethodDefinition = this.translateGetter( originalName, this.property.typeAnnotation, diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts index 91e3fdf99..7bf4e179a 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -16,11 +16,9 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; -import { - collectStateManagementTypeImport, - hasDecorator, -} from './utils'; +import { collectStateManagementTypeImport, hasDecorator } from './utils'; import { ClassScopeInfo } from './types'; +import { factory } from './factory'; export class ObservedTrackTranslator { protected property: arkts.ClassProperty; @@ -43,31 +41,19 @@ export class ObservedTrackTranslator { ? this.removeImplementProperty(expectName(this.property.key)) : expectName(this.property.key); const newName: string = backingField(originalName); - let properyIsClass = false; - - if (this.property.typeAnnotation && arkts.isETSTypeReference(this.property.typeAnnotation)) { - const decl = arkts.getDecl(this.property.typeAnnotation.part?.name!); - if (arkts.isClassDefinition(decl!)) { - properyIsClass = true; - } - } - const field = this.createField(originalName, newName, properyIsClass); - - this.transformGetterSetter(originalName, newName, properyIsClass); - + const field = this.createField(originalName, newName); + this.transformGetterSetter(originalName, newName); return [...field]; } - createField(originalName: string, newName: string, properyIsClass: boolean): arkts.ClassProperty[] { - const backingField = properyIsClass - ? this.propertyIsClassField(newName) - : arkts.factory.createClassProperty( - arkts.factory.createIdentifier(newName), - this.property.value, - this.property.typeAnnotation, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); + createField(originalName: string, newName: string): arkts.ClassProperty[] { + const backingField = arkts.factory.createClassProperty( + arkts.factory.createIdentifier(newName), + this.property.value, + this.property.typeAnnotation, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, + false + ); if (!this.isTracked) { return [backingField]; } @@ -75,14 +61,31 @@ export class ObservedTrackTranslator { return [backingField, metaField]; } - createGetter(originalName: string, newName: string, properyIsClass: boolean): arkts.MethodDefinition { - const ifRefDepth: arkts.IfStatement = this.getterIfRefDepth(originalName); - const returnMember: arkts.ReturnStatement = this.getterReturnMember(properyIsClass, newName); - const body = arkts.factory.createBlock([ - ifRefDepth, - ...(properyIsClass ? [this.getterSetObservationDepth(newName)] : []), - returnMember, - ]); + createGetter(originalName: string, newName: string): arkts.MethodDefinition { + const conditionalAddRef = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier('conditionalAddRef'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + this.metaIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + ] + ) + ); + const returnMember: arkts.ReturnStatement = arkts.factory.createReturnStatement(this.genThisBacking(newName)); + + const body = arkts.factory.createBlock([conditionalAddRef, returnMember]); const scriptFunction = arkts.factory.createScriptFunction( body, @@ -100,8 +103,8 @@ export class ObservedTrackTranslator { ); } - createSetter(originalName: string, newName: string, properyIsClass: boolean): arkts.MethodDefinition { - const ifEqualsNewValue: arkts.IfStatement = this.setterIfEqualsNewValue(properyIsClass, originalName, newName); + createSetter(originalName: string, newName: string): arkts.MethodDefinition { + const ifEqualsNewValue: arkts.IfStatement = this.setterIfEqualsNewValue(originalName, newName); const body = arkts.factory.createBlock([ifEqualsNewValue]); const param = arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier('newValue', this.property.typeAnnotation), @@ -134,20 +137,10 @@ export class ObservedTrackTranslator { ); } - genThisBackingValue(newName: string): arkts.MemberExpression { - return arkts.factory.createMemberExpression( - this.genThisBacking(newName), - arkts.factory.createIdentifier('value'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ); - } - metaIdentifier(originalName: string): arkts.Identifier { return this.isTracked - ? arkts.factory.createIdentifier(`__meta_${originalName}`) - : arkts.factory.createIdentifier('__meta'); + ? arkts.factory.createIdentifier(`${StateManagementTypes.META}_${originalName}`) + : arkts.factory.createIdentifier(StateManagementTypes.META); } removeImplementProperty(originalName: string): string { @@ -155,9 +148,9 @@ export class ObservedTrackTranslator { return originalName.substring(prefix.length); } - transformGetterSetter(originalName: string, newName: string, properyIsClass: boolean): void { - const newGetter = this.createGetter(originalName, newName, properyIsClass); - const newSetter = this.createSetter(originalName, newName, properyIsClass); + transformGetterSetter(originalName: string, newName: string): void { + const newGetter = this.createGetter(originalName, newName); + const newSetter = this.createSetter(originalName, newName); if (this.hasImplement) { { const idx: number = this.classScopeInfo.getters.findIndex( @@ -190,48 +183,11 @@ export class ObservedTrackTranslator { } } - propertyIsClassField(newName: string): arkts.ClassProperty { - collectStateManagementTypeImport(StateManagementTypes.BACKING_VALUE); - return arkts.factory.createClassProperty( - arkts.factory.createIdentifier(newName), - this.property.value - ? arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.BACKING_VALUE), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - [this.property.value] - ) - : undefined, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.BACKING_VALUE), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - } - metaField(originalName: string): arkts.ClassProperty { collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); return arkts.factory.createClassProperty( - arkts.factory.createIdentifier(`__meta_${originalName}`), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) - ) - ), - [arkts.factory.createStringLiteral('@Track')] - ), + arkts.factory.createIdentifier(`${StateManagementTypes.META}_${originalName}`), + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_MUTABLESTATE_META, undefined, [], false), arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) @@ -242,77 +198,8 @@ export class ObservedTrackTranslator { ); } - getterIfRefDepth(originalName: string): arkts.IfStatement { - return arkts.factory.createIfStatement( - arkts.factory.createBinaryExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('_permissibleAddRefDepth'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createNumericLiteral(0), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_GREATER_THAN - ), - arkts.factory.createBlock([ - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - this.metaIdentifier(originalName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createIdentifier('addRef'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - undefined, - false, - false - ) - ), - ]) - ); - } - - getterSetObservationDepth(newName: string): arkts.ExpressionStatement { - collectStateManagementTypeImport(StateManagementTypes.SET_OBSERVATION_DEPTH); - return arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createIdentifier(StateManagementTypes.SET_OBSERVATION_DEPTH), - undefined, - [ - this.genThisBackingValue(newName), - arkts.factory.createBinaryExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('_permissibleAddRefDepth'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createNumericLiteral(1), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_MINUS - ), - ] - ) - ); - } - - getterReturnMember(properyIsClass: boolean, newName: string): arkts.ReturnStatement { - return arkts.factory.createReturnStatement( - properyIsClass ? this.genThisBackingValue(newName) : this.genThisBacking(newName) - ); - } - - setterIfEqualsNewValue(properyIsClass: boolean, originalName: string, newName: string): arkts.IfStatement { - const backingValue = properyIsClass ? this.genThisBackingValue(newName) : this.genThisBacking(newName); + setterIfEqualsNewValue(originalName: string, newName: string): arkts.IfStatement { + const backingValue = this.genThisBacking(newName); const setNewValue = arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( diff --git a/arkui-plugins/ui-plugins/property-translators/prop.ts b/arkui-plugins/ui-plugins/property-translators/prop.ts index 8cfacd224..df2bce793 100644 --- a/arkui-plugins/ui-plugins/property-translators/prop.ts +++ b/arkui-plugins/ui-plugins/property-translators/prop.ts @@ -16,7 +16,8 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { DecoratorNames, GetSetTypes, StateManagementTypes } from '../../common/predefines'; +import { CustomComponentNames } from '../utils'; import { generateToRecord, createGetter, @@ -60,9 +61,9 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, GetSetTypes.GET); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') + generateGetOrSetCall(thisValue, GetSetTypes.SET) ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, @@ -97,7 +98,7 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { const binaryItem = arkts.factory.createBinaryExpression( factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), + arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), originalName ), this.property.value ?? arkts.factory.createUndefinedLiteral(), @@ -108,62 +109,51 @@ export class PropTranslator extends PropertyTranslator implements InitializerCon this.property.value ? binaryItem : arkts.factory.createTSAsExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true), + factory.createNonNullOrOptionalMemberExpression( + CustomComponentNames.COMPONENT_INITIALIZERS_NAME, + originalName, + false, + true + ), this.property.typeAnnotation ? this.property.typeAnnotation.clone() : undefined, false ), ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.PROP_DECORATED); - const right = arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.PROP_DECORATED), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - args - ); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - right + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_PROP, + this.property.typeAnnotation, + args, + true + ) ); return arkts.factory.createExpressionStatement(assign); } generateUpdateStruct(mutableThis: arkts.Expression, originalName: string): arkts.AstNode { - const binaryItem = arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName - ), - arkts.factory.createUndefinedLiteral(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL - ); const member: arkts.MemberExpression = arkts.factory.createMemberExpression( arkts.factory.createTSNonNullExpression(mutableThis), - arkts.factory.createIdentifier('update'), + arkts.factory.createIdentifier(StateManagementTypes.UPDATE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ); - return arkts.factory.createIfStatement( - binaryItem, - arkts.factory.createBlock([ - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(member, undefined, [ - arkts.factory.createTSAsExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true), - this.property.typeAnnotation ? this.property.typeAnnotation.clone() : undefined, - false - ), - ]) + return factory.createIfInUpdateStruct(originalName, member, [ + arkts.factory.createTSAsExpression( + factory.createNonNullOrOptionalMemberExpression( + CustomComponentNames.COMPONENT_INITIALIZERS_NAME, + originalName, + false, + true ), - ]) - ); + this.property.typeAnnotation ? this.property.typeAnnotation.clone() : undefined, + false + ), + ]); } } diff --git a/arkui-plugins/ui-plugins/property-translators/provide.ts b/arkui-plugins/ui-plugins/property-translators/provide.ts index c765413cc..c1141a5ac 100644 --- a/arkui-plugins/ui-plugins/property-translators/provide.ts +++ b/arkui-plugins/ui-plugins/property-translators/provide.ts @@ -16,7 +16,8 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { DecoratorNames, GetSetTypes, StateManagementTypes } from '../../common/predefines'; +import { CustomComponentNames } from '../utils'; import { createGetter, generateToRecord, @@ -57,9 +58,9 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, GetSetTypes.GET); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') + generateGetOrSetCall(thisValue, GetSetTypes.SET) ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, @@ -95,10 +96,29 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer const options: undefined | ProvideOptions = getValueInProvideAnnotation(this.property); const alias: string = options?.alias ?? originalName; const allowOverride: boolean = options?.allowOverride ?? false; + const args: arkts.Expression[] = [ + arkts.factory.create1StringLiteral(originalName), + arkts.factory.create1StringLiteral(alias), + arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), + originalName + ), + this.property.value ?? arkts.factory.createUndefinedLiteral(), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ), + arkts.factory.createBooleanLiteral(allowOverride), + ]; + factory.judgeIfAddWatchFunc(args, this.property); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateAddProvideVarCall(originalName, this.property, alias, allowOverride) + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_PROVIDE, + this.property.typeAnnotation, + args, + true + ) ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts index 731b0cd8c..704a56f71 100644 --- a/arkui-plugins/ui-plugins/property-translators/state.ts +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { DecoratorNames, GetSetTypes, StateManagementTypes } from '../../common/predefines'; import { CustomComponentNames } from '../utils'; import { generateToRecord, @@ -57,9 +57,9 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, GetSetTypes.GET); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') + generateGetOrSetCall(thisValue, GetSetTypes.SET) ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, @@ -103,21 +103,15 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), binaryItem]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.STATE_DECORATED); - const right = arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.STATE_DECORATED), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - args - ); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - right + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_STATE, + this.property.typeAnnotation, + args, + true + ) ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/storageProp.ts b/arkui-plugins/ui-plugins/property-translators/storageProp.ts index 2f33c03ed..ecec9362b 100644 --- a/arkui-plugins/ui-plugins/property-translators/storageProp.ts +++ b/arkui-plugins/ui-plugins/property-translators/storageProp.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { DecoratorNames, GetSetTypes, StateManagementTypes } from '../../common/predefines'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { @@ -91,28 +91,16 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.STORAGE_PROP_DECORATED); - const newClass = arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.STORAGE_PROP_DECORATED), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - args - ); return arkts.factory.createAssignmentExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(newName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), + generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - newClass + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_STORAGE_PROP, + this.property.typeAnnotation, + args, + true + ) ); } @@ -124,9 +112,9 @@ export class StoragePropTranslator extends PropertyTranslator implements Initial arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, GetSetTypes.GET); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') + generateGetOrSetCall(thisValue, GetSetTypes.SET) ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, diff --git a/arkui-plugins/ui-plugins/property-translators/storagelink.ts b/arkui-plugins/ui-plugins/property-translators/storagelink.ts index 68f3f7865..8e3256a90 100644 --- a/arkui-plugins/ui-plugins/property-translators/storagelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/storagelink.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, StateManagementTypes } from '../../common/predefines'; +import { DecoratorNames, GetSetTypes, StateManagementTypes } from '../../common/predefines'; import { InterfacePropertyTranslator, InterfacePropertyTypes, PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { @@ -91,28 +91,15 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_DECORATED); - const newClass = arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.STORAGE_LINK_DECORATED), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - args - ); - return arkts.factory.createAssignmentExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(newName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), + generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - newClass + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_STORAGE_LINK, + this.property.typeAnnotation, + args, + true + ) ); } @@ -124,9 +111,9 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); + const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, GetSetTypes.GET); const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') + generateGetOrSetCall(thisValue, GetSetTypes.SET) ); const getter: arkts.MethodDefinition = this.translateGetter( originalName, diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index c7421e7c0..2a750395a 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -23,6 +23,7 @@ import { DecoratorNames, DECORATOR_TYPE_MAP, StateManagementTypes, + GetSetTypes } from '../../common/predefines'; import { addMemoAnnotation, findCanAddMemoFromParamExpression, findCanAddMemoFromTypeAnnotation } from '../utils'; @@ -359,7 +360,7 @@ function getDifferentAnnoTypeValue(value: arkts.Expression): string | boolean { return value.dumpSrc(); } -export function generateGetOrSetCall(beforCall: arkts.AstNode, type: string) { +export function generateGetOrSetCall(beforCall: arkts.AstNode, type: GetSetTypes) { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( beforCall, diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index f3f39c246..031e865b9 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -550,6 +550,13 @@ export class factory { ) ) ), + arkts.TSClassImplements.createTSClassImplements( + arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart( + arkts.factory.createIdentifier(StateManagementTypes.SUBSCRIBED_WATCHES) + ) + ) + ), ], undefined, node.super, @@ -561,49 +568,14 @@ export class factory { return updateClassDef; } - static createPermissibleAddRefDepthInObservedClass(): arkts.ClassProperty { - return arkts.factory.createClassProperty( - arkts.factory.createIdentifier('_permissibleAddRefDepth'), - arkts.factory.createNumericLiteral(0), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(StateManagementTypes.INT_32)) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false - ); - } - - static createMutableStateMetaInObservedClass(): arkts.ClassProperty { - return arkts.factory.createClassProperty( - arkts.factory.createIdentifier('__meta'), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) - ) - ), - [arkts.factory.createStringLiteral('@Observe properties (no @Track)')] - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(StateManagementTypes.MUTABLE_STATE_META) - ) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - } - static observedTrackPropertyMembers( classHasTrack: boolean, definition: arkts.ClassDefinition, isObserved: boolean ): arkts.AstNode[] { const watchMembers: arkts.AstNode[] = propertyFactory.createWatchMembers(); - const permissibleAddRefDepth: arkts.ClassProperty = factory.createPermissibleAddRefDepthInObservedClass(); - collectStateManagementTypeImport(StateManagementTypes.INT_32); - const meta: arkts.ClassProperty = factory.createMutableStateMetaInObservedClass(); - collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); + const v1RenderIdMembers: arkts.AstNode[] = propertyFactory.createV1RenderIdMembers(); + const conditionalAddRef: arkts.MethodDefinition = propertyFactory.conditionalAddRef(); const getters: arkts.MethodDefinition[] = getGettersFromClassDecl(definition); const classScopeInfo: ClassScopeInfo = { isObserved: isObserved, @@ -623,8 +595,8 @@ export class factory { ) ); return [ - ...watchMembers, - ...(classHasTrack ? [permissibleAddRefDepth] : [permissibleAddRefDepth, meta]), + ...[...watchMembers, ...v1RenderIdMembers, conditionalAddRef], + ...(classHasTrack ? [] : [propertyFactory.createMetaInObservedClass()]), ...collect(...propertyMembers), ...nonClassPropertyOrGetter, ...classScopeInfo.getters, -- Gitee From e1180d1a0218ce99504174238d22c006227c77fe Mon Sep 17 00:00:00 2001 From: xieziang Date: Fri, 6 Jun 2025 11:25:46 +0800 Subject: [PATCH 116/123] load es2panda by absolute path Signed-off-by: xieziang Change-Id: I470114f9e64bad45908e0ce5ae6ad25b41324f39 --- koala-wrapper/native/src/common.cc | 25 +++++++++++++++-------- koala-wrapper/src/Es2pandaNativeModule.ts | 4 ++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/koala-wrapper/native/src/common.cc b/koala-wrapper/native/src/common.cc index e6c30a48b..553a1079b 100644 --- a/koala-wrapper/native/src/common.cc +++ b/koala-wrapper/native/src/common.cc @@ -41,15 +41,24 @@ static es2panda_Impl *impl = nullptr; const char* LIB_ES2PANDA_PUBLIC = LIB_PREFIX "es2panda_public" LIB_SUFFIX; +#ifdef KOALA_WINDOWS + const char *SEPARATOR = "\\"; +#else + const char *SEPARATOR = "/"; +#endif +const char *LIB_DIR = "lib"; + +static std::string ES2PANDA_LIB_PATH; + +void impl_SetUpSoPath(KStringPtr &soPath) +{ + ES2PANDA_LIB_PATH = std::string(soPath.c_str()); +} +KOALA_INTEROP_V1(SetUpSoPath, KStringPtr); + void* FindLibrary() { - std::string libraryName; - char* envValue = getenv("PANDA_SDK_PATH"); - if (envValue) { - libraryName = std::string(envValue) + ("/" PLUGIN_DIR "/lib/") + LIB_ES2PANDA_PUBLIC; - } else { - libraryName = LIB_ES2PANDA_PUBLIC; - } - return loadLibrary(libraryName); + std::string soFullPath = ES2PANDA_LIB_PATH + SEPARATOR + LIB_DIR + SEPARATOR + LIB_ES2PANDA_PUBLIC; + return loadLibrary(soFullPath); } es2panda_Impl *GetImpl() { diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index e509c21e3..b5c6629ec 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -917,6 +917,10 @@ export class Es2pandaNativeModule { suggestionInfo?: KNativePointer, range?: KNativePointer): void { throw new Error('Not implemented'); } + + _SetUpSoPath(soPath: string): void { + throw new Error('Not implemented'); + } } export function initEs2panda(): Es2pandaNativeModule { -- Gitee From d0757a81efb048566f33428ac0149d2368486132 Mon Sep 17 00:00:00 2001 From: l00913061 Date: Fri, 6 Jun 2025 18:40:51 +0800 Subject: [PATCH 117/123] Adapt to SDK updates Signed-off-by: l00913061 Change-Id: Ib1b578940c6413ba519d6eef3067badc2e833480 --- arkui-plugins/common/predefines.ts | 28 ----- arkui-plugins/common/program-visitor.ts | 2 +- .../test/demo/interop/link_link_interop.ets | 118 ++++++++++++++++++ ...onsume.ets => provide_consume_interop.ets} | 0 ...ink-example.ets => state_link_interop.ets} | 4 +- .../test/demo/interop/state_prop_interop.ets | 93 ++++++++++++++ .../ui-plugins/interop/initstatevar.ts | 42 +++---- arkui-plugins/ui-plugins/interop/interop.ts | 84 ++++++------- .../ui-plugins/interop/legacy-transformer.ts | 4 +- .../ui-plugins/interop/predefines.ts | 63 ++++++++++ arkui-plugins/ui-plugins/interop/provide.ts | 103 ++++++++------- arkui-plugins/ui-plugins/interop/utils.ts | 49 ++++---- 12 files changed, 420 insertions(+), 170 deletions(-) create mode 100644 arkui-plugins/test/demo/interop/link_link_interop.ets rename arkui-plugins/test/demo/interop/{1.2Provide-1.1Consume.ets => provide_consume_interop.ets} (100%) rename arkui-plugins/test/demo/interop/{1.2State-1.1Link-example.ets => state_link_interop.ets} (97%) create mode 100644 arkui-plugins/test/demo/interop/state_prop_interop.ets create mode 100644 arkui-plugins/ui-plugins/interop/predefines.ts diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 044a48b95..adbcd0ef3 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -169,34 +169,6 @@ export const INTERMEDIATE_IMPORT_SOURCE: Map = new Map { + this.stateVar.text += '~'; + }) + Child({stateVar: this.stateVar}) + } + } +} + +@Component +struct Child { + @Link stateVar; + build() { + Column() { + Button(this.stateVar.text) + .onClick((e: ClickEvent) => { + this.stateVar.text += '~'; + }) + Child1({stateVar: this.stateVar, text: this.stateVar}) + } + } +} + +class MyText { + text: string = 'MyText'; +} + + +//ArkT1.1 +import { MyText } from 'har2/src/main/ets/components/MainPage' + +@Component +export struct Child1{ + @Link stateVar: MyText; + @Link text: MyText; + build() { + Column() { + Button(this.stateVar.text) + .onClick(() => { + this.stateVar.text += '~'; + }) + Button(this.text.text) + .onClick(() => { + this.text.text = 'ArkTS1.1'; + }) + } + } +} + + +//transform 1.1struct 'Child1' to ArkUICompatible + +ArkUICompatible(__memo_context, ((__memo_id) + (252133223)), (() => { + let global = ESValue.getGlobal(); + let param = ESValue.instantiateEmptyObject(); + let createState = global.getProperty("createStateVariable"); + let stateVar_SetSource = ((value: MyText) => { + (this).stateVar = value; + }); + let stateVar_ProxyState = createState.invoke(ESValue.wrap((this).stateVar), ESValue.wrap(stateVar_SetSource)); + (this).__backing_stateVar!.setProxy(stateVar_ProxyState); + let stateVar_SetProxy = ((value: MyText) => { + stateVar_ProxyState.invokeMethod("set", ESValue.wrap(value)); + }); + (this).__backing_stateVar!.setProxyValue = stateVar_SetProxy; + let stateVar_NotifyCallback = ((propertyName: string) => { + stateVar_ProxyState.invokeMethod("notifyPropertyHasChangedPU"); + }); + (this).__backing_stateVar!.setNotifyCallback(stateVar_NotifyCallback); + param.setProperty("stateVar", stateVar_ProxyState); + param.setProperty("text", stateVar_ProxyState); + let extraInfo = ESValue.instantiateEmptyObject(); + extraInfo.setProperty("page", "har1/src/main/ets/components/MainPage"); + let esundefined = ESValue.wrap(undefined); + let blank = (() => {}); + let esblank = ESValue.wrap((blank as object)); + let viewStackProcessor = global.getProperty("ViewStackProcessor"); + let createId = viewStackProcessor.getProperty("AllocateNewElmetIdForNextComponent"); + let elmtId = createId.invoke(); + let har1 = ESValue.load("@normalized:N&entry&com.example.Interop2use1&har1/src/main/ets/components/MainPage&1.0.0"); + let structObject = har1.getProperty("Child1"); + let component = structObject.instantiate(esundefined, param, esundefined, elmtId, esblank, extraInfo); + let create = structObject.getProperty("create"); + create.invoke(component); + return { + component: component, + name: "Child1", + }; +}), ((instance: ESValue) => {})); \ No newline at end of file diff --git a/arkui-plugins/test/demo/interop/1.2Provide-1.1Consume.ets b/arkui-plugins/test/demo/interop/provide_consume_interop.ets similarity index 100% rename from arkui-plugins/test/demo/interop/1.2Provide-1.1Consume.ets rename to arkui-plugins/test/demo/interop/provide_consume_interop.ets diff --git a/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets b/arkui-plugins/test/demo/interop/state_link_interop.ets similarity index 97% rename from arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets rename to arkui-plugins/test/demo/interop/state_link_interop.ets index cfdff0613..ec3778ef2 100644 --- a/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets +++ b/arkui-plugins/test/demo/interop/state_link_interop.ets @@ -69,12 +69,12 @@ ArkUICompatible(__memo_context, ((__memo_id) + (252133223)), (() => { let global = ESValue.getGlobal(); let param = ESValue.instantiateEmptyObject(); let createState = global.getProperty("createStateVariable"); - let stateVar_SetSource = ((value: B) => { + let stateVar_SetSource = ((value: MyText) => { (this).stateVar = value; }); let stateVar_ProxyState = createState.invoke(ESValue.wrap((this).stateVar), ESValue.wrap(stateVar_SetSource)); (this).__backing_stateVar!.setProxy(stateVar_ProxyState); - let stateVar_SetProxy = ((value: B) => { + let stateVar_SetProxy = ((value: MyText) => { stateVar_ProxyState.invokeMethod("set", ESValue.wrap(value)); }); (this).__backing_stateVar!.setProxyValue = stateVar_SetProxy; diff --git a/arkui-plugins/test/demo/interop/state_prop_interop.ets b/arkui-plugins/test/demo/interop/state_prop_interop.ets new file mode 100644 index 000000000..99a073bbb --- /dev/null +++ b/arkui-plugins/test/demo/interop/state_prop_interop.ets @@ -0,0 +1,93 @@ +/* + * 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. + */ + + +// ArkTS1.2 +import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { ArkUICompatible, InteropComponent, Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickEvent, UserView, } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins +import { State, StateDecoratedVariable, MutableState, stateOf, observableProxy, Observed, Track, Provide, Consume } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { MyText } from 'har2/src/main/ets/components/MainPage' +import { Child1 } from 'har1' + + +@Component +struct MyStateSample { + @State stateVar: MyText = new MyText(); + build() { + Column() { + Button(this.stateVar.text) + .onClick((e: ClickEvent) => { + this.stateVar.text += '~'; + }) + Child1({stateVar: this.stateVar, text: this.stateVar}) + } + } +} + +class MyText { + text: string = 'MyText'; +} + + +//ArkT1.1 +import { MyText } from 'har2/src/main/ets/components/MainPage' + +@Component +export struct Child1{ + @Prop stateVar: MyText; + @Prop text: MyText; + build() { + Column() { + Button(this.stateVar.text) + .onClick(() => { + this.stateVar.text += '~'; + }) + Button(this.text.text) + .onClick(() => { + this.text.text = 'ArkTS1.1'; + }) + } + } +} + + +//transform 1.1struct 'Child1' to ArkUICompatible + +ArkUICompatible(__memo_context, ((__memo_id) + (252133223)), (() => { + let global = ESValue.getGlobal(); + let param = ESValue.instantiateEmptyObject(); + let createState = global.getProperty("createStateVariable"); + param.setProperty("stateVar", (this).stateVar); + param.setProperty("text", (this).stateVar); + let extraInfo = ESValue.instantiateEmptyObject(); + extraInfo.setProperty("page", "har1/src/main/ets/components/MainPage"); + let esundefined = ESValue.wrap(undefined); + let blank = (() => {}); + let esblank = ESValue.wrap((blank as object)); + let viewStackProcessor = global.getProperty("ViewStackProcessor"); + let createId = viewStackProcessor.getProperty("AllocateNewElmetIdForNextComponent"); + let elmtId = createId.invoke(); + let har1 = ESValue.load("@normalized:N&entry&com.example.Interop2use1&har1/src/main/ets/components/MainPage&1.0.0"); + let structObject = har1.getProperty("Child1"); + let component = structObject.instantiate(esundefined, param, esundefined, elmtId, esblank, extraInfo); + let create = structObject.getProperty("create"); + create.invoke(component); + return { + component: component, + name: "Child1", + }; +}), ((instance: ESValue) => { + instance.invokeMethod("updateStateVars", ESValue.wrap({stateVar: this.stateVar, text: this.stateVar})); +})); \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/interop/initstatevar.ts b/arkui-plugins/ui-plugins/interop/initstatevar.ts index a914ab4e3..9a8c143e9 100644 --- a/arkui-plugins/ui-plugins/interop/initstatevar.ts +++ b/arkui-plugins/ui-plugins/interop/initstatevar.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; -import { InteroperAbilityNames } from '../../common/predefines'; +import { ESValueMethodNames, InteroperAbilityNames } from './predefines'; import { annotation, backingField, isAnnotation } from '../../common/arkts-utils'; import { stateProxy, getPropertyESValue, getWrapValue, ifStateHasProxy, setPropertyESValue, hasLink, hasState, hasProvide, hasProp } from './utils'; @@ -90,7 +90,7 @@ function setCallbackForProxy(stateVar: () => arkts.Expression, type?: arkts.Type arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier('createState'), - arkts.factory.createIdentifier('invoke'), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -124,7 +124,7 @@ function createSourceBlock(): arkts.BlockStatement { arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier('proxyState'), - arkts.factory.createIdentifier('invokeMethod'), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKEMETHOD), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -149,7 +149,7 @@ function createNotifyBlock(): arkts.BlockStatement { arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier('proxyState'), - arkts.factory.createIdentifier('invokeMethod'), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKEMETHOD), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -196,10 +196,10 @@ function setCallbackForSource(type?: arkts.TypeNode): arkts.Statement[] { return [createValueCallback, createNotifyCallback]; } -function configureState(stateVar: () => arkts.Expression): arkts.Statement { +function bindCompatibleState(stateVar: () => arkts.Expression): arkts.Statement { return arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( - arkts.factory.createIdentifier('configureState'), + arkts.factory.createIdentifier(InteroperAbilityNames.CONFIGURESTATE), undefined, [ stateVar(), @@ -214,7 +214,7 @@ function configureState(stateVar: () => arkts.Expression): arkts.Statement { function createProxyForState(stateVar: () => arkts.Expression, type?: arkts.TypeNode): arkts.Statement[] { const setProxy = setCallbackForProxy(stateVar, type); const setSource = setCallbackForSource(type); - const cfgState = configureState(stateVar); + const cfgState = bindCompatibleState(stateVar); return [...setProxy, ...setSource, cfgState]; } @@ -246,15 +246,11 @@ function setAndGetProxy(varName: string, type: arkts.TypeNode, stateVar: () => a const getProxy = createVariableLet( stateProxy(varName), arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - stateVar(), - arkts.factory.createIdentifier('getProxy'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), + arkts.factory.createIdentifier(InteroperAbilityNames.GETPROXY), undefined, - undefined + [ + stateVar() + ] ) ); result.push(...setProxy, getProxy); @@ -271,15 +267,11 @@ function linkGetSource(varName: string, proxySet: Set): arkts.Statement[ const getState = createVariableLet( stateName, arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - backingLink, - arkts.factory.createIdentifier('getSource'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), + arkts.factory.createIdentifier(InteroperAbilityNames.GETSOURCE), undefined, - undefined + [ + backingLink + ] ) ); result.push(getState); @@ -293,7 +285,7 @@ function linkGetSource(varName: string, proxySet: Set): arkts.Statement[ * @param value * @param type * @param proxySet - * @returns 处理Link装饰器所生成的互操作代码 + * @returns generate code to process @Link data interoperability */ export function processLink(keyName: string, value: arkts.Expression, type: arkts.TypeNode, proxySet: Set): arkts.Statement[] { const valueDecl = arkts.getDecl(value); @@ -341,7 +333,7 @@ export function processLink(keyName: string, value: arkts.Expression, type: arkt * * @param keyName * @param value - * @returns 处理一般情况下的属性赋值 + * @returns generate code to process regular data interoperability */ export function processNormal(keyName: string, value: arkts.AstNode): arkts.Statement[] { const result: arkts.Statement[] = []; diff --git a/arkui-plugins/ui-plugins/interop/interop.ts b/arkui-plugins/ui-plugins/interop/interop.ts index 20305dc9a..946dc441a 100644 --- a/arkui-plugins/ui-plugins/interop/interop.ts +++ b/arkui-plugins/ui-plugins/interop/interop.ts @@ -16,12 +16,12 @@ import * as arkts from '@koalaui/libarkts'; -import { InteroperAbilityNames } from '../../common/predefines'; +import { ESValueMethodNames, InteroperAbilityNames } from './predefines'; import { getCustomComponentOptionsName } from '../utils'; import { InteropContext } from '../component-transformer'; import { annotation, backingField, isAnnotation } from '../../common/arkts-utils'; import { processLink, processNormal } from './initstatevar'; -import { createProvideInterop, resetFindProvide } from './provide'; +import { createProvideInterop, setAndResetFindProvide } from './provide'; import { getPropertyESValue, getWrapValue, setPropertyESValue, hasLink, createEmptyESValue, hasProp } from './utils'; interface propertyInfo { @@ -75,7 +75,7 @@ function instantiateComponent(params: arkts.AstNode[]): arkts.VariableDeclaratio arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier(InteroperAbilityNames.STRUCTOBJECT), - arkts.factory.createIdentifier(InteroperAbilityNames.INSTANTIATE), + arkts.factory.createIdentifier(ESValueMethodNames.INSTANTIATE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -89,7 +89,7 @@ function instantiateComponent(params: arkts.AstNode[]): arkts.VariableDeclaratio } function paramsLambdaDeclaration(name: string, args?: arkts.ObjectExpression): arkts.Statement[] { - const result = []; + const result: arkts.Statement[] = []; result.push( arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, @@ -232,10 +232,10 @@ function createGlobal(): arkts.Statement { arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [arkts.factory.createVariableDeclarator( arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier('global'), + arkts.factory.createIdentifier(InteroperAbilityNames.GLOBAL), arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), + arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE), arkts.factory.createIdentifier('getGlobal'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, @@ -250,7 +250,7 @@ function createGlobal(): arkts.Statement { function createELMTID(): arkts.Statement[] { const body: arkts.Statement[] = []; - const viewStackProcessor = getPropertyESValue('viewStackProcessor', 'global', 'ViewStackProcessor'); + const viewStackProcessor = getPropertyESValue('viewStackProcessor', InteroperAbilityNames.GLOBAL, 'ViewStackProcessor'); body.push(viewStackProcessor); const createId = getPropertyESValue('createId', 'viewStackProcessor', 'AllocateNewElmetIdForNextComponent'); body.push(createId); @@ -263,7 +263,7 @@ function createELMTID(): arkts.Statement[] { arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier('createId'), - arkts.factory.createIdentifier('invoke'), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -288,8 +288,8 @@ function createComponent(moduleName: string, className: string): arkts.Statement arkts.factory.createIdentifier(moduleName), arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(InteroperAbilityNames.LOAD), + arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE), + arkts.factory.createIdentifier(ESValueMethodNames.LOAD), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -301,7 +301,7 @@ function createComponent(moduleName: string, className: string): arkts.Statement ] ); body.push(module); - const structObject = getPropertyESValue('structObject', moduleName, className); + const structObject = getPropertyESValue(InteroperAbilityNames.STRUCTOBJECT, moduleName, className); body.push(structObject); const component = instantiateComponent( [ @@ -319,20 +319,20 @@ function createComponent(moduleName: string, className: string): arkts.Statement function invokeViewPUCreate(): arkts.Statement[] { const body: arkts.Statement[] = []; - const createMethod = getPropertyESValue('create', 'structObject', 'create'); + const createMethod = getPropertyESValue('create', InteroperAbilityNames.STRUCTOBJECT, 'create'); body.push(createMethod); const viewPUCreate = arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier('create'), - arkts.factory.createIdentifier('invoke'), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ), undefined, [ - arkts.factory.createIdentifier('component') + arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT) ] ) ); @@ -342,10 +342,10 @@ function invokeViewPUCreate(): arkts.Statement[] { function createWrapperBlock(context: InteropContext, varMap: Map, updateProp: arkts.Property[]): arkts.BlockStatement { - const className = context.className; - const path = context.path; - const args = context.arguments; - const index = path.indexOf('/'); + const className: string = context.className; + const path: string = context.path; + const args: arkts.ObjectExpression | undefined = context.arguments; + const index: number = path.indexOf('/'); if (index === -1) { throw new Error('Error path of Legacy Component.'); } @@ -353,7 +353,7 @@ function createWrapperBlock(context: InteropContext, varMap: Map, - updateProp: arkts.Property[]): arkts.ArrowFunctionExpression { +function createUpdater(updateProp: arkts.Property[]): arkts.ArrowFunctionExpression { const updateState = updateStateVars(updateProp); return arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( @@ -433,7 +432,13 @@ function createUpdater(esvalue: arkts.ETSTypeReference, varMap: Map.instantiate_Interop. */ export function generateInstantiateInterop(context: InteropContext): arkts.CallExpression { return arkts.factory.createCallExpression( @@ -504,9 +509,9 @@ export function generateInstantiateInterop(context: InteropContext): arkts.CallE } /** - * After Checked阶段 + * * @param node - * @returns {boolean} 判断节点是否为带有互操作标识的CallExpression + * @returns {boolean} Checks if a given CallExpression represents a call to .instantiate_Interop. */ export function isArkUICompatible(node: arkts.AstNode): boolean { if (node instanceof arkts.CallExpression && node.expression instanceof arkts.MemberExpression && @@ -521,7 +526,7 @@ export function isArkUICompatible(node: arkts.AstNode): boolean { /** * * @param node - * @returns After Checked阶段,将带有互操作标识的1.1组件静态方法转换为ArkUICompatible函数 + * @returns After Checked, transform instantiate_Interop -> ArkUICompatible */ export function generateArkUICompatible(node: arkts.CallExpression): arkts.CallExpression { const classInterop = (node.expression as arkts.MemberExpression).object as arkts.Identifier; @@ -540,14 +545,9 @@ export function generateArkUICompatible(node: arkts.CallExpression): arkts.CallE }; const varMap: Map = generateVarMap(classInterop); - const esvalue = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) - ) - ); const updateProp:arkts.Property[] = []; const initializer = createInitializer(context, varMap, updateProp); - const updater = createUpdater(esvalue, varMap, updateProp); + const updater = createUpdater(updateProp); return arkts.factory.updateCallExpression( node, arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), diff --git a/arkui-plugins/ui-plugins/interop/legacy-transformer.ts b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts index f5bfb7810..3d78ff48e 100644 --- a/arkui-plugins/ui-plugins/interop/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts @@ -20,7 +20,7 @@ import { getInteropPath } from '../../path'; const interop = require(getInteropPath()); const nullptr = interop.nullptr; import { AbstractVisitor, VisitorOptions } from '../../common/abstract-visitor'; -import { InteroperAbilityNames } from '../../common/predefines'; +import { ESValueMethodNames, InteroperAbilityNames } from './predefines'; import { getCustomComponentOptionsName } from '../utils'; import { annotation } from 'common/arkts-utils'; @@ -171,7 +171,7 @@ export class LegacyTransformer extends AbstractVisitor { processConstructor(node: arkts.MethodDefinition): arkts.MethodDefinition { const esvalue = arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) + arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) ) ); const script = arkts.factory.createScriptFunction( diff --git a/arkui-plugins/ui-plugins/interop/predefines.ts b/arkui-plugins/ui-plugins/interop/predefines.ts new file mode 100644 index 000000000..c70c8e017 --- /dev/null +++ b/arkui-plugins/ui-plugins/interop/predefines.ts @@ -0,0 +1,63 @@ +/* + * 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. + */ + + +export enum InteroperAbilityNames { + ARKTS_1_1 = '1.1', + ARKTS_1_2 = '1.2', + ARKUICOMPATIBLE = 'ArkUICompatible', + ELMTID = 'elmtId', + NUMBER = 'number', + PARENT = 'parent', + INSTANCE = 'instance', + PARAM = 'param', + EXTRAINFO = 'extraInfo', + COMPONENT = 'component', + CONSTRUCTOR = 'constructor', + MODULE = 'module', + STRUCTOBJECT = 'structObject', + GLOBAL = 'global', + PARAMSLAMBDA = 'paramsLambda', + INTEROPCOMPONENT = 'interopComponent', + OHMURL = '@normalized:N&entry&com.example.Interop2use1&har1/src/main/ets/components/MainPage&1.0.0', + CONFIGURESTATE = 'bindCompatibleState', + GETSOURCE = 'findBindingSourceState', + GETPROXY = 'getCompatibleState' +} + + +export enum ESValueMethodNames { + ESVALUE = 'ESValue', + INITEMPTYOBJECT = 'instantiateEmptyObject', + SETPROPERTY = 'setProperty', + GETPROPERTY = 'getProperty', + INSTANTIATE = 'instantiate', + INVOKE = 'invoke', + INVOKEMETHOD = 'invokeMethod', + LOAD = 'load', + WRAP = 'wrap', + WRAPINT = 'wrapInt', + WRAPSTRING = 'wrapString', + UNWRAP = 'unwrap', +} + +export enum InteropProvideNames { + STATICPROVIDE = 'provide', + FINDPROVIDE = 'findProvide', + PROVIDEDPROPNAME = 'providedPropName', + SETFINDPROVIDE = 'setFindProvideInterop', + SETVIEWPUFINDPROVIDE = 'setViewPUFindProvideInterop', + FINDPROVIDECALLBACK = 'findProvideInterop', +} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/interop/provide.ts b/arkui-plugins/ui-plugins/interop/provide.ts index 0f37705f7..19732e624 100644 --- a/arkui-plugins/ui-plugins/interop/provide.ts +++ b/arkui-plugins/ui-plugins/interop/provide.ts @@ -18,15 +18,16 @@ import * as arkts from '@koalaui/libarkts'; import { getPropertyESValue } from './utils'; import { createVariableLet, setStateProxy } from './initstatevar'; +import { ESValueMethodNames, InteroperAbilityNames, InteropProvideNames } from './predefines'; function findProvide(): arkts.Statement { return createVariableLet( - 'provide', + InteropProvideNames.STATICPROVIDE, arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('findProvide'), + arkts.factory.createIdentifier(InteropProvideNames.FINDPROVIDE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -39,7 +40,7 @@ function findProvide(): arkts.Statement { ) ], [ - arkts.factory.createIdentifier('providedPropName') + arkts.factory.createIdentifier(InteropProvideNames.PROVIDEDPROPNAME) ] ) ); @@ -48,7 +49,7 @@ function findProvide(): arkts.Statement { function setProvideProxy(): arkts.Statement[] { return setStateProxy( () => arkts.factory.createTSNonNullExpression( - arkts.factory.createIdentifier('provide') + arkts.factory.createIdentifier(InteropProvideNames.STATICPROVIDE) ) ); } @@ -57,17 +58,13 @@ function getProvideProxy(): arkts.Statement { return createVariableLet( 'proxy', arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createIdentifier('provide') - ), - arkts.factory.createIdentifier('getProxy'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), + arkts.factory.createIdentifier(InteroperAbilityNames.GETPROXY), undefined, - undefined + [ + arkts.factory.createTSNonNullExpression( + arkts.factory.createIdentifier(InteropProvideNames.STATICPROVIDE) + ) + ] ) ); } @@ -81,12 +78,12 @@ function returnProvide(): arkts.Statement { arkts.factory.createIdentifier('proxy'), arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('ESValue') + arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) ) ), false ), - arkts.factory.createIdentifier('unwrap'), + arkts.factory.createIdentifier(ESValueMethodNames.UNWRAP), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -109,7 +106,7 @@ function createProvideBlock(): arkts.BlockStatement { function findProvideCallback(): arkts.Statement { const block = createProvideBlock(); const callback = createVariableLet( - 'findProvideInterop', + InteropProvideNames.FINDPROVIDECALLBACK, arkts.factory.createArrowFunction( arkts.factory.createScriptFunction( block, @@ -117,7 +114,7 @@ function findProvideCallback(): arkts.Statement { undefined, [ arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('providedPropName', + arkts.factory.createIdentifier(InteropProvideNames.PROVIDEDPROPNAME, arkts.factory.createTypeReference( arkts.factory.createTypeReferencePart( arkts.factory.createIdentifier('string') @@ -143,47 +140,67 @@ function findProvideCallback(): arkts.Statement { } export function createProvideInterop(): arkts.Statement[] { - const func = getPropertyESValue( - 'setFindProvideInterop', - 'global', - 'setFindProvideInterop' + const viewPUFunc = getPropertyESValue( + InteropProvideNames.SETVIEWPUFINDPROVIDE, + InteroperAbilityNames.GLOBAL, + InteropProvideNames.SETVIEWPUFINDPROVIDE + ); + const componentFunc = getPropertyESValue( + InteropProvideNames.SETFINDPROVIDE, + InteroperAbilityNames.GLOBAL, + InteropProvideNames.SETFINDPROVIDE ); const callback = findProvideCallback(); const invokeFunc = arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('setFindProvideInterop'), - arkts.factory.createIdentifier('invoke'), + arkts.factory.createIdentifier(InteropProvideNames.SETVIEWPUFINDPROVIDE), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKE), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ), undefined, [ - arkts.factory.createIdentifier('findProvideInterop') + arkts.factory.createIdentifier(InteropProvideNames.FINDPROVIDECALLBACK) ] ) ); - return [func, callback, invokeFunc]; + return [viewPUFunc, componentFunc, callback, invokeFunc]; } -/** - * - * @returns ViewPU.resetFindInterop() - */ -export function resetFindProvide(): arkts.Statement { - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('structObject'), - arkts.factory.createIdentifier('invokeMethod'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [ - arkts.factory.createStringLiteral('resetFindProvide') - ] +export function setAndResetFindProvide(): arkts.Statement[] { + const setComponent = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteropProvideNames.SETFINDPROVIDE), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT), + arkts.factory.createIdentifier(InteropProvideNames.FINDPROVIDECALLBACK) + ] + ) + ); + const resetViewPU = arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.STRUCTOBJECT), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKEMETHOD), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.factory.createStringLiteral('resetFindInterop') + ] + ) ); + return [setComponent, resetViewPU]; } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/interop/utils.ts b/arkui-plugins/ui-plugins/interop/utils.ts index 70e997af6..c26e4051b 100644 --- a/arkui-plugins/ui-plugins/interop/utils.ts +++ b/arkui-plugins/ui-plugins/interop/utils.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; -import { InteroperAbilityNames } from '../../common/predefines'; +import { ESValueMethodNames, InteroperAbilityNames } from './predefines'; /** @@ -34,8 +34,8 @@ export function createEmptyESValue(result: string): arkts.VariableDeclaration { arkts.factory.createIdentifier(result), arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(InteroperAbilityNames.INITEMPTYOBJECT), + arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE), + arkts.factory.createIdentifier(ESValueMethodNames.INITEMPTYOBJECT), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -56,8 +56,8 @@ export function createEmptyESValue(result: string): arkts.VariableDeclaration { export function getWrapValue(value: arkts.AstNode): arkts.AstNode { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(InteroperAbilityNames.WRAP), + arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE), + arkts.factory.createIdentifier(ESValueMethodNames.WRAP), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -79,7 +79,7 @@ export function setPropertyESValue(object: string, key: string, value: arkts.Ast arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier(object), - arkts.factory.createIdentifier(InteroperAbilityNames.SETPROPERTY), + arkts.factory.createIdentifier(ESValueMethodNames.SETPROPERTY), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -96,11 +96,11 @@ export function setPropertyESValue(object: string, key: string, value: arkts.Ast /** * * @param result - * @param object + * @param obj * @param key * @returns let result = object.getProperty(key) */ -export function getPropertyESValue(result: string, object: string, key: string): arkts.VariableDeclaration { +export function getPropertyESValue(result: string, obj: string, key: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, @@ -110,8 +110,8 @@ export function getPropertyESValue(result: string, object: string, key: string): arkts.factory.createIdentifier(result), arkts.factory.createCallExpression( arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(object), - arkts.factory.createIdentifier(InteroperAbilityNames.GETPROPERTY), + arkts.factory.createIdentifier(obj), + arkts.factory.createIdentifier(ESValueMethodNames.GETPROPERTY), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false @@ -126,23 +126,19 @@ export function getPropertyESValue(result: string, object: string, key: string): /** * - * @param stateName + * @param stateVar * @param block - * @returns if (stateName.getProxy() === undefined) { block } + * @returns if (getCompatibleState(stateVar) === undefined) { block } */ export function ifStateHasProxy(stateVar: () => arkts.Expression, block: arkts.BlockStatement): arkts.Statement { return arkts.factory.createIfStatement( arkts.factory.createBinaryExpression( arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - stateVar(), - arkts.factory.createIdentifier('getProxy'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - true - ), - undefined, + arkts.factory.createIdentifier(InteroperAbilityNames.GETPROXY), undefined, + [ + stateVar() + ] ), arkts.factory.createUndefinedLiteral(), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_STRICT_EQUAL @@ -152,9 +148,9 @@ export function ifStateHasProxy(stateVar: () => arkts.Expression, block: arkts.B } /** - * - * @param decorators - * @returns 判断是否包含Link装饰器 + * Checks if an array of decorator names contains the 'Link' decorator. + * @param {string[]} decorators - Array of decorator names applied to a property. + * @returns {boolean} True if the 'Link' decorator is present, otherwise false. */ export function hasLink(decorators: string[]): boolean { return decorators.some(decorator => decorator === 'Link'); @@ -173,10 +169,9 @@ export function hasProvide(decorators: string[]): boolean { } /** - * - * @param stateVarName - * @param name - * @returns 带有状态变量标识的变量命名 + * Generates a state proxy variable name by appending "_State_Proxy" suffix. + * @param {string} stateVarName - Original state variable name to be proxied. + * @returns {string} Proxied variable name in the format: "{stateVarName}_State_Proxy". */ export function stateProxy(stateVarName: string): string { return `${stateVarName}_State_Proxy`; -- Gitee From 6511fffcaa1eee610538181a35cb16ca3cd805f6 Mon Sep 17 00:00:00 2001 From: Boren Zhang Date: Thu, 5 Jun 2025 15:38:40 +0800 Subject: [PATCH 118/123] Transform wrapBuilder. Change @Builder to @memo in type alias for functions. Signed-off-by: Boren Zhang --- arkui-plugins/ui-plugins/checked-transformer.ts | 2 ++ arkui-plugins/ui-plugins/struct-translators/factory.ts | 10 +++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index f3ccf8d29..357a41830 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -116,6 +116,8 @@ export class CheckedTransformer extends AbstractVisitor { return addMemoAnnotation(node); } else if (arkts.isEtsScript(node) && ImportCollector.getInstance().importInfos.length > 0) { ImportCollector.getInstance().insertCurrentImports(this.program); + } else if (arkts.isTSTypeAliasDeclaration(node)) { + return structFactory.transformTSTypeAlias(node); } return node; } diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index 031e865b9..fc0a1ca57 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -23,10 +23,11 @@ import { getTypeNameFromTypeParameter, getTypeParamsFromClassDecl, isCustomComponentInterface, + MemoNames, } from '../utils'; import { factory as uiFactory } from '../ui-factory'; import { factory as propertyFactory } from '../property-translators/factory'; -import { collect, filterDefined } from '../../common/arkts-utils'; +import { collect, filterDefined, annotation } from '../../common/arkts-utils'; import { classifyObservedTrack, classifyProperty, @@ -528,6 +529,13 @@ export class factory { return arkts.factory.updateClassDeclaration(node, newClassDef); } + static transformTSTypeAlias(node: arkts.TSTypeAliasDeclaration): arkts.TSTypeAliasDeclaration { + if (arkts.isETSFunctionType(node.typeAnnotation) && hasDecorator(node.typeAnnotation, DecoratorNames.BUILDER)) { + node.typeAnnotation.setAnnotations([annotation(MemoNames.MEMO)]); + } + return node; + } + static updateObservedTrackClassDef(node: arkts.ClassDefinition): arkts.ClassDefinition { const isObserved: boolean = hasDecorator(node, DecoratorNames.OBSERVED); const classHasTrack: boolean = node.body.some( -- Gitee From 1b0a026fc0bac7bb3674b803356bdfa3ecb48f4f Mon Sep 17 00:00:00 2001 From: xieziang Date: Wed, 11 Jun 2025 15:29:28 +0800 Subject: [PATCH 119/123] support set es2panda by env variables Signed-off-by: xieziang Change-Id: Ib8f80bd33a4dc1a43eaa2f6c581ffc26823b0b32 --- koala-wrapper/native/src/common.cc | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/koala-wrapper/native/src/common.cc b/koala-wrapper/native/src/common.cc index 553a1079b..d95f378fd 100644 --- a/koala-wrapper/native/src/common.cc +++ b/koala-wrapper/native/src/common.cc @@ -50,6 +50,19 @@ const char *LIB_DIR = "lib"; static std::string ES2PANDA_LIB_PATH; +std::string joinPath(vector &paths) +{ + std::string res; + for (int i = 0; i < paths.size(); ++i) { + if (i == 0) { + res = paths[i]; + } else { + res += SEPARATOR + paths[i]; + } + } + return res; +} + void impl_SetUpSoPath(KStringPtr &soPath) { ES2PANDA_LIB_PATH = std::string(soPath.c_str()); @@ -57,8 +70,16 @@ void impl_SetUpSoPath(KStringPtr &soPath) KOALA_INTEROP_V1(SetUpSoPath, KStringPtr); void* FindLibrary() { - std::string soFullPath = ES2PANDA_LIB_PATH + SEPARATOR + LIB_DIR + SEPARATOR + LIB_ES2PANDA_PUBLIC; - return loadLibrary(soFullPath); + std::vector pathArray; + char* envValue = getenv("PANDA_SDK_PATH"); + if (envValue) { + pathArray = {envValue, PLUGIN_DIR, LIB_DIR, LIB_ES2PANDA_PUBLIC}; + } else if (!ES2PANDA_LIB_PATH.empty()) { + pathArray = {ES2PANDA_LIB_PATH, LIB_DIR, LIB_ES2PANDA_PUBLIC}; + } else { + pathArray = {LIB_ES2PANDA_PUBLIC}; + } + return loadLibrary(joinPath(pathArray)); } es2panda_Impl *GetImpl() { -- Gitee From cbc5b350f752ba671b488665ba1a99f8fd8f8a35 Mon Sep 17 00:00:00 2001 From: wuhailong Date: Tue, 10 Jun 2025 16:27:21 +0800 Subject: [PATCH 120/123] Modify cache file for glue code Issue: #ICE1NU Signed-off-by: wuhailong Change-Id: Ie149d8b971991571af013ed01a82a0b7ae88093f --- .../ark_compiler/module/module_mode.ts | 10 ++-- .../ark_compiler/module/module_source_file.ts | 2 +- compiler/src/process_arkts_evolution.ts | 17 +++++- .../mock/rollup_mock/common.ts | 3 +- .../mock/rollup_mock/module_info.ts | 2 +- .../module/module_mode.test.ts | 56 ++++++++++++++++++- 6 files changed, 79 insertions(+), 11 deletions(-) diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts index 562661f77..9073aefb7 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_mode.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -120,11 +120,12 @@ import { } from '../logger'; import { addDeclFilesConfig, + arkTSModuleMap, ArkTSEvolutionModule, getDeclgenBridgeCodePath, - pkgDeclFilesConfig, - arkTSModuleMap, - isArkTSEvolutionFile + genCachePathForBridgeCode, + isArkTSEvolutionFile, + pkgDeclFilesConfig } from '../../../process_arkts_evolution'; export class ModuleInfo { @@ -521,7 +522,8 @@ export class ModuleMode extends CommonMode { let moduleName: string = metaInfo.moduleName; let recordName: string = ''; - let cacheFilePath: string = isArkTSEvolutionFile(filePath, metaInfo) ? originalFilePath : + let cacheFilePath: string = isArkTSEvolutionFile(filePath, metaInfo) ? + genCachePathForBridgeCode(originalFilePath, metaInfo, this.projectConfig.cachePath) : this.genFileCachePath(filePath, this.projectConfig.projectRootPath, this.projectConfig.cachePath, metaInfo); let packageName: string = ''; diff --git a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts index 8d9771f04..6d7407b47 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts @@ -432,7 +432,7 @@ export class ModuleSourceFile { ModuleSourceFile.logger, parentEvent, this.metaInfo); } } else { - await writeBridgeCodeFileSyncByNode( this.source, this.moduleId); + await writeBridgeCodeFileSyncByNode( this.source, this.moduleId, this.metaInfo); } } diff --git a/compiler/src/process_arkts_evolution.ts b/compiler/src/process_arkts_evolution.ts index 272db9e37..5e8ca1673 100644 --- a/compiler/src/process_arkts_evolution.ts +++ b/compiler/src/process_arkts_evolution.ts @@ -201,14 +201,25 @@ export function cleanUpProcessArkTSEvolutionObj(): void { fullNameToTmpVar = new Map(); } -export async function writeBridgeCodeFileSyncByNode(node: ts.SourceFile, moduleId: string): Promise { +export async function writeBridgeCodeFileSyncByNode(node: ts.SourceFile, moduleId: string, + metaInfo: Object): Promise { const printer: ts.Printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed }); const writer: ts.EmitTextWriter = ts.createTextWriter( // @ts-ignore ts.getNewLineCharacter({ newLine: ts.NewLineKind.LineFeed, removeComments: false })); printer.writeFile(node, writer, undefined); - mkdirsSync(path.dirname(moduleId)); - fs.writeFileSync(moduleId, writer.getText()); + const cacheFilePath: string = genCachePathForBridgeCode(moduleId, metaInfo); + mkdirsSync(path.dirname(cacheFilePath)); + fs.writeFileSync(cacheFilePath, writer.getText()); +} + +export function genCachePathForBridgeCode(moduleId: string, metaInfo: Object, cachePath?: string): string { + const bridgeCodePath: string = getDeclgenBridgeCodePath(metaInfo.pkgName); + const filePath: string = toUnixPath(moduleId); + const relativeFilePath: string = filePath.replace( + toUnixPath(path.join(bridgeCodePath, metaInfo.pkgName)), metaInfo.moduleName); + const cacheFilePath: string = path.join(cachePath ? cachePath : process.env.cachePath, relativeFilePath); + return cacheFilePath; } export function getDeclgenBridgeCodePath(pkgName: string): string { diff --git a/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts b/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts index 123f315d9..fd2db982c 100644 --- a/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts +++ b/compiler/test/ark_compiler_ut/mock/rollup_mock/common.ts @@ -83,4 +83,5 @@ export const NEWFILE: string = 'newFile'; export const DECLFILESPATH: string = '/entry/build/default/intermediates/loader_out/default/etsFortgz/decl-fileInfo.json'; export const DECLGENV2OUTPATH: string = '/entry/build/default/intermediates/declgen/default/declgenV2'; -export const HAR_DECLGENV2OUTPATH: string = '/har/build/default/intermediates/declgen/default/declgenV2'; \ No newline at end of file +export const HAR_DECLGENV2OUTPATH: string = '/har/build/default/intermediates/declgen/default/declgenV2'; +export const HAR_BRIDGECODEPATH: string = '/har/build/default/intermediates/declgen/default/declgenBridgeCode'; \ No newline at end of file diff --git a/compiler/test/ark_compiler_ut/mock/rollup_mock/module_info.ts b/compiler/test/ark_compiler_ut/mock/rollup_mock/module_info.ts index abce70bef..008cf81f2 100644 --- a/compiler/test/ark_compiler_ut/mock/rollup_mock/module_info.ts +++ b/compiler/test/ark_compiler_ut/mock/rollup_mock/module_info.ts @@ -36,7 +36,7 @@ class Meta { this.belongModulePath = `${PROJECT_ROOT}/${DEFAULT_PROJECT}/${DEFAULT_ENTRY}`; this.hostModulesInfo = []; this.moduleName = entryModuleName; - this.pkgName = ''; + this.pkgName = 'entry'; this.isLocalDependency = true; this.isNodeEntryFile = false; this.pkgPath = modulePath; diff --git a/compiler/test/ark_compiler_ut/module/module_mode.test.ts b/compiler/test/ark_compiler_ut/module/module_mode.test.ts index 42364286d..3239995d8 100644 --- a/compiler/test/ark_compiler_ut/module/module_mode.test.ts +++ b/compiler/test/ark_compiler_ut/module/module_mode.test.ts @@ -58,7 +58,8 @@ import { ENTRY_MODULE_NAME_DEFAULT, TEST, NEWFILE, - ENTRY_MODULE_VERSION_DEFAULT + ENTRY_MODULE_VERSION_DEFAULT, + HAR_BRIDGECODEPATH } from '../mock/rollup_mock/common'; import projectConfig from '../utils/processProjectConfig'; import { @@ -101,6 +102,7 @@ import { LogData, LogDataFactory } from '../../../lib/fast_build/ark_compiler/logger'; +import { arkTSEvolutionModuleMap } from '../../../lib/process_arkts_evolution'; function checkGenerateEs2AbcCmdExpect(cmdArgs: Array, compatibleSdkVersion: string, byteCodeHar: boolean): void { const fileThreads: number = cpus(); @@ -789,6 +791,58 @@ mocha.describe('test module_mode file api', function () { SourceMapGenerator.cleanSourceMapObject(); }); + mocha.it('2-8: test addModuleInfoItem under build mixCompile', function () { + this.rollup.build(); + this.rollup.share.projectConfig.useNormalizedOHMUrl = true; + this.rollup.share.projectConfig.pkgContextInfo = { + 'har': { + 'packageName': 'har', + 'bundleName': '', + 'moduleName': '', + 'version': '1.0.0', + 'entryPath': 'Index.ets', + 'isSO': false + }, + 'entry': { + 'packageName': 'entry', + 'bundleName': '', + 'moduleName': '', + 'version': '', + 'entryPath': 'Index.ets', + 'isSO': false + } + } + const arkTSEvoFile = path.join(HAR_BRIDGECODEPATH, 'har','Index.ts'); + const arkTSEvolutionModuleInfo = { + language: '1.2', + packageName: 'har', + moduleName: 'har', + declgenBridgeCodePath: HAR_BRIDGECODEPATH, + } + arkTSEvolutionModuleMap.set('har', arkTSEvolutionModuleInfo) + this.rollup.share.allFiles.add(arkTSEvoFile); + const moduleInfoMock = { + id: arkTSEvoFile, + meta: { + 'pkgName': 'har', + 'moduleName': 'har', + 'language': '1.2' + } + }; + + this.rollup.moduleInfos.push(moduleInfoMock); + const sourceMapGenerator: SourceMapGenerator = SourceMapGenerator.initInstance(this.rollup); + sourceMapGenerator.setNewSoureMaps(false); + const moduleMode = new ModuleModeMock(this.rollup); + moduleMode.addModuleInfoItemMock(this.rollup); + const cacheFilePath = moduleMode.moduleInfos.get(toUnixPath(arkTSEvoFile)).cacheFilePath; + const expectCacheFilePath = path.join(moduleMode.projectConfig.cachePath, 'har/Index.ts'); + expect(cacheFilePath === expectCacheFilePath).to.be.true; + this.rollup.share.projectConfig.useNormalizedOHMUrl = false; + this.rollup.share.allFiles.delete(arkTSEvoFile); + SourceMapGenerator.cleanSourceMapObject(); + }); + mocha.it('3-1-1: test updateCachedSourceMaps under build debug: cacheSourceMapPath not exist', function () { this.rollup.build(); const moduleMode = new ModuleModeMock(this.rollup); -- Gitee From da588b9d6d7b03b26e08e65c024d3b55735025ed Mon Sep 17 00:00:00 2001 From: l00913061 Date: Wed, 11 Jun 2025 20:19:34 +0800 Subject: [PATCH 121/123] 0611 Signed-off-by: l00913061 --- .../interop-plugins/decl_transformer.ts | 2 +- compiler/src/process_interop_ui.ts | 22 ------------------- 2 files changed, 1 insertion(+), 23 deletions(-) diff --git a/arkui-plugins/interop-plugins/decl_transformer.ts b/arkui-plugins/interop-plugins/decl_transformer.ts index 3aee2f8f8..58d5a6a6d 100644 --- a/arkui-plugins/interop-plugins/decl_transformer.ts +++ b/arkui-plugins/interop-plugins/decl_transformer.ts @@ -105,7 +105,7 @@ export class DeclTransformer extends AbstractVisitor { node.name, node.name?.name ), - arkts.factory.createFunctionExpression(updateFunc), + updateFunc, node.modifiers, false ); diff --git a/compiler/src/process_interop_ui.ts b/compiler/src/process_interop_ui.ts index 489f357da..ee086a62f 100644 --- a/compiler/src/process_interop_ui.ts +++ b/compiler/src/process_interop_ui.ts @@ -93,28 +93,6 @@ class HandleUIImports { } private visitNode(node: ts.Node): ts.Node | undefined { - // TODO, declare struct => struct - if (node.parent && isStructDeclaration(node.parent) && ts.isModifier(node) && - node.kind === ts.SyntaxKind.DeclareKeyword) { - return; - } - - // TODO, build() => build() {} - if (node.parent && isStructDeclaration(node.parent) && ts.isMethodDeclaration(node) && - node.name && ts.isIdentifier(node.name) && node.name.escapedText.toString() === "build") { - return ts.factory.updateMethodDeclaration(node, - undefined, - undefined, - undefined, - node.name, - undefined, - undefined, - undefined, - undefined, - ts.factory.createBlock([], false) - ); - } - // delete constructor if (node.parent && isStructDeclaration(node.parent) && ts.isConstructorDeclaration(node)) { return; -- Gitee From d7fd6f56e01f22f461791b194d8ec360302720c8 Mon Sep 17 00:00:00 2001 From: xieziang Date: Thu, 22 May 2025 15:23:48 +0800 Subject: [PATCH 122/123] skip some phases Change-Id: If1b5c6d801b712175f67c7aef6a88d2b83c821b6 Signed-off-by: xieziang --- arkui-plugins/memo-plugins/index.ts | 139 +++++++++--------- arkui-plugins/ui-plugins/index.ts | 58 +++++--- koala-wrapper/native/src/common.cc | 41 ++++++ koala-wrapper/src/Es2pandaEnums.ts | 2 +- koala-wrapper/src/Es2pandaNativeModule.ts | 4 + koala-wrapper/src/arkts-api/peers/Program.ts | 24 +++ .../src/arkts-api/utilities/public.ts | 2 +- 7 files changed, 180 insertions(+), 90 deletions(-) diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index aa5c2de65..72c2b577d 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -27,77 +27,78 @@ import { SignatureTransformer } from './signature-transformer'; export function unmemoizeTransform(): Plugins { return { name: 'memo-plugin', - checked(this: PluginContext) { - console.log('[MEMO PLUGIN] AFTER CHECKED ENTER'); - const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - let script = program.astNode; - - debugLog('[BEFORE MEMO SCRIPT] script: ', script.dumpSrc()); - const cachePath: string | undefined = this.getProjectConfig()?.cachePath; - debugDump( - script.dumpSrc(), - getDumpFileName(0, 'SRC', 5, 'MEMO_AfterCheck_Begin'), - true, - cachePath, - program.fileNameWithExtension - ); - - arkts.Performance.getInstance().createEvent('memo-checked'); - - const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); - const parameterTransformer = new ParameterTransformer({ - positionalIdTracker, - }); - const returnTransformer = new ReturnTransformer(); - const signatureTransformer = new SignatureTransformer(); - const functionTransformer = new FunctionTransformer({ - positionalIdTracker, - parameterTransformer, - returnTransformer, - signatureTransformer, - }); - - const programVisitor = new ProgramVisitor({ - pluginName: unmemoizeTransform.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [functionTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - - program = programVisitor.programVisitor(program); - script = program.astNode; - - arkts.Performance.getInstance().stopEvent('memo-checked', false); - - debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); - debugDump( - script.dumpSrc(), - getDumpFileName(0, 'SRC', 6, 'MEMO_AfterCheck_End'), - true, - cachePath, - program.fileNameWithExtension - ); - - arkts.Performance.getInstance().createEvent('memo-recheck'); - arkts.recheckSubtree(script); - arkts.Performance.getInstance().stopEvent('memo-recheck', false); - - arkts.Performance.getInstance().clearAllEvents(true); - arkts.Performance.getInstance().visualizeEvents(true); - arkts.Performance.getInstance().clearHistory(); - arkts.Performance.getInstance().clearTotalDuration(); - - this.setArkTSAst(script); - console.log('[MEMO PLUGIN] AFTER CHECKED EXIT'); - return script; - } - console.log('[MEMO PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); - }, + checked: checkedTransform, clean() { arkts.arktsGlobal.clearContext(); }, }; } + +function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { + console.log('[MEMO PLUGIN] AFTER CHECKED ENTER'); + const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + let script = program.astNode; + debugLog('[BEFORE MEMO SCRIPT] script: ', script.dumpSrc()); + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 5, 'MEMO_AfterCheck_Begin'), + true, + cachePath, + program.fileNameWithExtension + ); + arkts.Performance.getInstance().createEvent('memo-checked'); + program = checkedProgramVisit(program, this); + script = program.astNode; + arkts.Performance.getInstance().stopEvent('memo-checked', false); + debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 6, 'MEMO_AfterCheck_End'), + true, + cachePath, + program.fileNameWithExtension + ); + arkts.Performance.getInstance().createEvent('memo-recheck'); + arkts.recheckSubtree(script); + arkts.Performance.getInstance().stopEvent('memo-recheck', false); + arkts.Performance.getInstance().clearAllEvents(false); + arkts.Performance.getInstance().visualizeEvents(true); + arkts.Performance.getInstance().clearHistory(); + arkts.Performance.getInstance().clearTotalDuration(); + this.setArkTSAst(script); + console.log('[MEMO PLUGIN] AFTER CHECKED EXIT'); + return script; + } + console.log('[MEMO PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); + return undefined; +} + +function checkedProgramVisit(program: arkts.Program, context: PluginContext): arkts.Program { + if (program.canSkipPhases()) { + debugLog('[SKIP PHASE] phase: memo-checked, moduleName: ', program.moduleName); + } else { + debugLog('[CANT SKIP PHASE] phase: memo-checked, moduleName: ', program.moduleName); + const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); + const parameterTransformer = new ParameterTransformer({ positionalIdTracker }); + const returnTransformer = new ReturnTransformer(); + const signatureTransformer = new SignatureTransformer(); + const functionTransformer = new FunctionTransformer({ + positionalIdTracker, + parameterTransformer, + returnTransformer, + signatureTransformer, + }); + const programVisitor = new ProgramVisitor({ + pluginName: unmemoizeTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [functionTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: context, + }); + program = programVisitor.programVisitor(program); + } + return program; +} diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index a50014ecf..e1131f946 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -50,16 +50,7 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { program.fileNameWithExtension ); arkts.Performance.getInstance().createEvent('ui-parsed'); - const componentTransformer = new ComponentTransformer(); - const preprocessorTransformer = new PreprocessorTransformer(); - const programVisitor = new ProgramVisitor({ - pluginName: uiTransform.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, - visitors: [componentTransformer, preprocessorTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - program = programVisitor.programVisitor(program); + program = parsedProgramVisit(program, this); script = program.astNode; arkts.Performance.getInstance().stopEvent('ui-parsed', false); debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); @@ -78,6 +69,25 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { return script; } +function parsedProgramVisit(program: arkts.Program, context: PluginContext): arkts.Program { + if (program.canSkipPhases()) { + debugLog('[SKIP PHASE] phase: ui-parsed, moduleName: ', program.moduleName); + } else { + debugLog('[CANT SKIP PHASE] phase: ui-parsed, moduleName: ', program.moduleName); + const componentTransformer = new ComponentTransformer(); + const preprocessorTransformer = new PreprocessorTransformer(); + const programVisitor = new ProgramVisitor({ + pluginName: uiTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + visitors: [componentTransformer, preprocessorTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: context, + }); + program = programVisitor.programVisitor(program); + } + return program; +} + function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; console.log('[UI PLUGIN] AFTER CHECKED ENTER'); @@ -95,15 +105,7 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { program.fileNameWithExtension ); arkts.Performance.getInstance().createEvent('ui-checked'); - const checkedTransformer = new CheckedTransformer(this.getProjectConfig()); - const programVisitor = new ProgramVisitor({ - pluginName: uiTransform.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [checkedTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - program = programVisitor.programVisitor(program); + program = checkedProgramVisit(program, this); script = program.astNode; arkts.Performance.getInstance().stopEvent('ui-checked', false); debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); @@ -128,3 +130,21 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { console.log('[UI PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); return script; } + +function checkedProgramVisit(program: arkts.Program, context: PluginContext): arkts.Program { + if (program.canSkipPhases()) { + debugLog('[SKIP PHASE] phase: ui-checked, moduleName: ', program.moduleName); + } else { + debugLog('[CANT SKIP PHASE] phase: ui-checked, moduleName: ', program.moduleName); + const checkedTransformer = new CheckedTransformer(context.getProjectConfig()); + const programVisitor = new ProgramVisitor({ + pluginName: uiTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [checkedTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: context, + }); + program = programVisitor.programVisitor(program); + } + return program; +} diff --git a/koala-wrapper/native/src/common.cc b/koala-wrapper/native/src/common.cc index 553a1079b..123c028dc 100644 --- a/koala-wrapper/native/src/common.cc +++ b/koala-wrapper/native/src/common.cc @@ -40,6 +40,10 @@ static es2panda_Impl *impl = nullptr; #endif const char* LIB_ES2PANDA_PUBLIC = LIB_PREFIX "es2panda_public" LIB_SUFFIX; +constexpr const char* IS_UI_FLAG = "IS_UI_FLAG"; +constexpr const char* NOT_UI_FLAG = "NOT_UI_FLAG"; +const string MODULE_SUFFIX = ".d.ets"; +const string ARKUI = "arkui"; #ifdef KOALA_WINDOWS const char *SEPARATOR = "\\"; @@ -297,6 +301,43 @@ KNativePointer impl_AstNodeChildren( } KOALA_INTEROP_2(AstNodeChildren, KNativePointer, KNativePointer, KNativePointer) +static bool isUIHeaderFile(es2panda_Context* context, es2panda_Program* program) +{ + auto result = GetImpl()->ProgramFileNameWithExtensionConst(context, program); + string fileNameWithExtension(result); + result = GetImpl()->ProgramModuleNameConst(context, program); + string moduleName(result); + + return fileNameWithExtension.length() >= MODULE_SUFFIX.length() + && fileNameWithExtension.substr(fileNameWithExtension.length() - MODULE_SUFFIX.length()) == MODULE_SUFFIX + && moduleName.find(ARKUI) != std::string::npos; +} + +KBoolean impl_ProgramCanSkipPhases(KNativePointer context, KNativePointer program) +{ + KStringPtr isUiFlag(IS_UI_FLAG); + KStringPtr notUiFlag(NOT_UI_FLAG); + const auto _context = reinterpret_cast(context); + const auto _program = reinterpret_cast(program); + if (isUIHeaderFile(_context, _program)) { + return false; + } + std::size_t sourceLen; + const auto externalSources = reinterpret_cast + (GetImpl()->ProgramExternalSources(_context, _program, &sourceLen)); + for (std::size_t i = 0; i < sourceLen; ++i) { + std::size_t programLen; + auto programs = GetImpl()->ExternalSourcePrograms(externalSources[i], &programLen); + for (std::size_t j = 0; j < programLen; ++j) { + if (isUIHeaderFile(_context, programs[j])) { + return false; + } + } + } + return true; +} +KOALA_INTEROP_2(ProgramCanSkipPhases, KBoolean, KNativePointer, KNativePointer) + /* ----------------------------------------------------------------------------------------------------------------------------- */ diff --git a/koala-wrapper/src/Es2pandaEnums.ts b/koala-wrapper/src/Es2pandaEnums.ts index bf2ce0783..6a16486a7 100644 --- a/koala-wrapper/src/Es2pandaEnums.ts +++ b/koala-wrapper/src/Es2pandaEnums.ts @@ -181,7 +181,7 @@ export enum Es2pandaAstNodeType { AST_NODE_TYPE_OBJECT_PATTERN, AST_NODE_TYPE_SPREAD_ELEMENT, AST_NODE_TYPE_REST_ELEMENT, -} +}; export enum Es2pandaImportFlags { IMPORT_FLAGS_NONE, diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 6c5b48e7d..99942dce5 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -750,6 +750,10 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _ProgramCanSkipPhases(context: KNativePointer, program: KNativePointer): boolean { + throw new Error('Not implemented'); + } + _GenerateTsDeclarationsFromContext( config: KPtr, outputDeclEts: String, diff --git a/koala-wrapper/src/arkts-api/peers/Program.ts b/koala-wrapper/src/arkts-api/peers/Program.ts index 5734dc4a4..5a1099473 100644 --- a/koala-wrapper/src/arkts-api/peers/Program.ts +++ b/koala-wrapper/src/arkts-api/peers/Program.ts @@ -19,9 +19,18 @@ import { acceptNativeObjectArrayResult, unpackString } from "../utilities/privat import { KNativePointer } from "@koalaui/interop" import { EtsScript } from "../types" +enum SkipPhaseResult { + NOT_COMPUTED, + CAN_SKIP, + CANNOT_SKIP, +} + export class Program extends ArktsObject { + private canSkipPhaseResult: SkipPhaseResult; + constructor(peer: KNativePointer) { super(peer); + this.canSkipPhaseResult = SkipPhaseResult.NOT_COMPUTED; } get astNode(): EtsScript { @@ -61,6 +70,21 @@ export class Program extends ArktsObject { isASTLowered(): boolean { return global.es2panda._ProgramIsASTLoweredConst(global.context, this.peer); } + + canSkipPhases(): boolean { + if (this.canSkipPhaseResult === SkipPhaseResult.CAN_SKIP) { + return true; + } else if (this.canSkipPhaseResult === SkipPhaseResult.CANNOT_SKIP) { + return false; + } + if (global.es2panda._ProgramCanSkipPhases(global.context, this.peer)) { + this.canSkipPhaseResult = SkipPhaseResult.CAN_SKIP; + return true; + } else { + this.canSkipPhaseResult = SkipPhaseResult.CANNOT_SKIP; + return false; + } + } } export class ExternalSource extends ArktsObject { diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index d7e2dfc33..04ac973fe 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -39,7 +39,7 @@ import { type AnnotationUsage, } from '../../generated'; import { Program } from '../peers/Program'; -import { clearNodeCache } from '../class-by-peer'; +import { clearNodeCache, nodeByType } from '../class-by-peer'; import { SourcePosition } from '../peers/SourcePosition'; import { MemberExpression } from '../to-be-generated/MemberExpression'; -- Gitee From c064a349b3799b00b0fdef0900ece5a234a1a22b Mon Sep 17 00:00:00 2001 From: lixudong <3365582168@qq.com> Date: Sat, 14 Jun 2025 16:31:45 +0800 Subject: [PATCH 123/123] =?UTF-8?q?=E6=B7=BB=E5=8A=A0card=E5=88=A4?= =?UTF-8?q?=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: lixudong <3365582168@qq.com> --- compiler/main.js | 2 + .../system_api/api_check_utils_new.ts | 104 ++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 compiler/src/fast_build/system_api/api_check_utils_new.ts diff --git a/compiler/main.js b/compiler/main.js index 22dbce8fa..217f4defe 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -111,6 +111,8 @@ function initProjectConfig(projectConfig) { projectConfig.updateVersionInfo = undefined; projectConfig.allowEmptyBundleName = false; projectConfig.uiTransformOptimization = false; + projectConfig.hasReadForm = false; + projectConfig.cardPaths = []; } function initProjectPathConfig(projectConfig) { diff --git a/compiler/src/fast_build/system_api/api_check_utils_new.ts b/compiler/src/fast_build/system_api/api_check_utils_new.ts new file mode 100644 index 000000000..67ed26b95 --- /dev/null +++ b/compiler/src/fast_build/system_api/api_check_utils_new.ts @@ -0,0 +1,104 @@ +import {projectConfig} from "../../../main"; + + +import * as fs from 'fs'; +import * as path from 'path'; + +// 定义 JSON 数据结构接口 +interface WindowConfig { + designWidth: number; + autoDesignWidth: boolean; +} + +interface FormConfig { + name: string; + displayName: string; + description: string; + src: string; // 目标字段 + uiSyntax: string; + window: WindowConfig; + colorMode: string; + isDynamic: boolean; + isDefault: boolean; + updateEnabled: boolean; + scheduledUpdateTime: string; + updateDuration: number; + defaultDimension: string; + supportDimensions: string[]; +} + +interface ConfigSchema { + forms: FormConfig[]; +} + +/** + * 从 JSON 文件中提取所有 src 字段到数组 + * @param filePath JSON 文件的绝对路径 + * @returns 包含所有 src 字段的字符串数组 + * @throws 文件不存在、JSON 解析错误或数据结构不符时抛出异常 + */ +export function extractSrcPaths(filePath: string): string[] { + // 1. 验证路径格式和存在性 + if (!path.isAbsolute(filePath)) { + throw new Error(`路径必须是绝对路径: ${filePath}`); + } + + if (!fs.existsSync(filePath)) { + throw new Error(`文件不存在: ${filePath}`); + } + + try { + // 2. 读取并解析 JSON 文件 + const rawData = fs.readFileSync(filePath, 'utf-8'); + const config: ConfigSchema = JSON.parse(rawData); + + // 3. 验证数据结构 + if (!config.forms || !Array.isArray(config.forms)) { + throw new Error('JSON 缺少 forms 数组'); + } + + // 4. 提取所有 src 字段 + const srcPaths: string[] = []; + for (const form of config.forms) { + if (form.src && typeof form.src === 'string') { + srcPaths.push(form.src); + } else { + console.warn(`跳过无效 src 字段的表单项: ${form.name}`); + } + } + + // 5. 返回结果数组 + return srcPaths; + } catch (error) { + // 6. 增强错误信息 + if (error instanceof SyntaxError) { + throw new SyntaxError(`JSON 解析错误: ${error.message}`); + } + throw new Error(`处理失败: ${error instanceof Error ? error.message : String(error)}`); + } +} + + +export function isCardFile(file: string): boolean { + + let path = projectConfig.projectPath + projectConfig.aceProfilePath + projectConfig.aceModuleJsonPath; + + let paths: string[] = null; + + if (projectConfig.hasReadForm) { + paths = projectConfig.cardPaths; + } else { + paths = extractSrcPaths(path); + } + + if (paths.length > 0) { + projectConfig.hasReadForm = true; + projectConfig.cardPaths = paths; + } else { + return false; + } + + return paths.includes(file); + + +} -- Gitee