diff --git a/frameworks/bridge/arkts_frontend/BUILD.gn b/frameworks/bridge/arkts_frontend/BUILD.gn index 9f384938d023a4ae5f24b5379bc21b33ad399429..14b5c2ebe8a49ccc7d86135a08424e7ba7afa160 100644 --- a/frameworks/bridge/arkts_frontend/BUILD.gn +++ b/frameworks/bridge/arkts_frontend/BUILD.gn @@ -45,7 +45,7 @@ template("arkts_frontend") { ] external_deps = [ "hilog:libhilog", - "runtime_core:ani", + "runtime_core:ani" ] } } diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/.gitignore b/frameworks/bridge/arkts_frontend/koala_mirror/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a8fabecf693ed2e3ba01e28a1fb70d7f71d71132 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/.gitignore @@ -0,0 +1,27 @@ +**/node_modules +build +dist +arkoala/tools/peer-generator/arkoala +**/package-lock.json +.vscode +**.code-workspace +.idea +**/target +**/cjpm.lock +**/CallsiteKey.o +sdk +interface_sdk-js +.ninja_log +**/.hvigor +**/js_output +**/command-line-tools +**/libs +**/lib +**/*.abc +cachegrind.out.* +perf.data* +**/arktsconfig-unmemoized-merged.json +koala_build.log +.rollup.cache +tsconfig.tsbuildinfo +**/out diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/incremental/package.json b/frameworks/bridge/arkts_frontend/koala_mirror/incremental/package.json index 5be3485965df3ad2240e108caa8bad470aa9e5f3..f93622c755db7b336018b66cc1a702d9680a8cc2 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/incremental/package.json +++ b/frameworks/bridge/arkts_frontend/koala_mirror/incremental/package.json @@ -5,7 +5,7 @@ "build-common", "compat", "common", - "runtime", + "runtime" ], "devDependencies": { "ts-node": "^10.7.0", diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/incremental/test-utils/scripts/register.js b/frameworks/bridge/arkts_frontend/koala_mirror/incremental/test-utils/scripts/register.js new file mode 100644 index 0000000000000000000000000000000000000000..6e7df5f8c20a96d306c280e336d6cfd17c74df2f --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/incremental/test-utils/scripts/register.js @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 tsNode = require("ts-node") +const path = require("path") +const { goldenSetup } = require("@koalaui/common/golden") + +goldenSetup('.', '.') + +unmemoized_suffix = process.env.UNMEMOIZED_SUFFIX +if (unmemoized_suffix == undefined) { + unmemoized_suffix = '' +} + +tsNode.register({ + files: true, + // If uncommented, running tests doesn't perform type checks. + // transpileOnly: true, + project: path.resolve(`test`, `tsconfig${unmemoized_suffix}.json`), + compiler: "@koalaui/ets-tsc" +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/arkts/SerializerBase.ts b/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/arkts/SerializerBase.ts index d54bd27d2c8b52600916ce06015b9220416b68da..dd6e76211c8570bd08ae8d9093a3c9027b7cd6e7 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/arkts/SerializerBase.ts +++ b/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/arkts/SerializerBase.ts @@ -199,8 +199,8 @@ export class SerializerBase implements Disposable { } holdAndWriteCallbackForPromiseVoid(hold: pointer = 0, release: pointer = 0, call: pointer = 0): [Promise, ResourceId] { let resourceId: ResourceId = 0 - const promise = new Promise((resolve: (value: PromiseLike) => void, reject: (err: Object|null|undefined) => void) => { - const callback = (err: string[]|undefined) => { + const promise = new Promise((resolve: (value: PromiseLike) => void, reject: (err: Error) => void) => { + const callback = (err: Error|undefined) => { if (err !== undefined) reject(err!) else @@ -212,8 +212,8 @@ export class SerializerBase implements Disposable { } holdAndWriteCallbackForPromise(hold: pointer = 0, release: pointer = 0, call: pointer = 0): [Promise, ResourceId] { let resourceId: ResourceId = 0 - const promise = new Promise((resolve: (value: T|PromiseLike) => void, reject: (err: Object|null|undefined) => void) => { - const callback = (value?: T|undefined, err?: string[]|undefined) => { + const promise = new Promise((resolve: (value: T|PromiseLike) => void, reject: (err: Error) => void) => { + const callback = (value?: T|undefined, err?: Error|undefined) => { if (err !== undefined) reject(err!) else diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/cpp/callback-resource.cc b/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/cpp/callback-resource.cc index 32b54ae794167f4750eee9687637de42f46ef47d..32ed23e5a019fdad24bb262fc98d145263827ddf 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/cpp/callback-resource.cc +++ b/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/cpp/callback-resource.cc @@ -13,6 +13,7 @@ * limitations under the License. */ +#undef KOALA_INTEROP_MODULE #define KOALA_INTEROP_MODULE InteropNativeModule #include "common-interop.h" #include "interop-types.h" diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/cpp/napi/convertors-napi.cc b/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/cpp/napi/convertors-napi.cc index 98ddac13d1afd0177b223738676f9988023ab56d..b7e82e7e6cf00a21183b41eda0e95de5759d812f 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/cpp/napi/convertors-napi.cc +++ b/frameworks/bridge/arkts_frontend/koala_mirror/interop/src/cpp/napi/convertors-napi.cc @@ -18,6 +18,7 @@ #include #include "interop-logging.h" +#undef KOALA_INTEROP_MODULE #define KOALA_INTEROP_MODULE InteropNativeModule #include "convertors-napi.h" diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/interop/tsconfig.json b/frameworks/bridge/arkts_frontend/koala_mirror/interop/tsconfig.json index 20defe21ff0088065b1bfe0c4da0ec6ee5372591..858ec370c2c9dd5d793076f35c6f284efc215c1f 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/interop/tsconfig.json +++ b/frameworks/bridge/arkts_frontend/koala_mirror/interop/tsconfig.json @@ -24,7 +24,6 @@ }, "include": ["src/interop/**/*", "src/napi/**/*", "src/wasm/**/*", "src/arkts/ResourceManager.ts"], "references": [ - { "path": "../incremental/compiler-plugin" }, { "path": "../incremental/compat" }, { "path": "../incremental/common" } ] diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/package.json b/frameworks/bridge/arkts_frontend/koala_mirror/package.json index efdeda636cd45a057c5ff5c66cba7ca4f2451849..9cb29ae28b8408a30ea3ef933ea0dab05b207ce5 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/package.json +++ b/frameworks/bridge/arkts_frontend/koala_mirror/package.json @@ -3,21 +3,6 @@ "private": true, "//": "DO NOT ADD dependencies or devDependencies clauses to this level! Keep subfolders autonomous.", "scripts": { - "prepare": "cd incremental && npm i && cd .. && cd interop && npm i && cd .. && cd arkoala-arkts && npm i && cd .. && cd ui2abc && npm i", - "compile": "npm run compile --prefix incremental && npm run compile --prefix interop", - "release": "npm run compile && node tools/release.mjs", - "ohos-sdk": "npm run ohos-sdk --prefix arkoala-arkts/arkui-common", - "ohos-sdk:full": "node ./tools/ohos-tools/ohos-sdk/cli.mjs download", - "ohos-sdk:prebuilt": "node tools/ohos-tools/ohos-sdk/cli.mjs prebuilt:download", - "ohos-sdk:patch": "npm run ohos-sdk:prebuilt && node tools/ohos-tools/ohos-sdk/oh-sdk-patch.mjs", - "ets:plugin:compile": "npm run compile --prefix arkoala-arkts/ets-plugin", - "compiler:plugin:compile": "npm run compile --prefix incremental/compiler-plugin", - "plugins:compile": "npm run compiler:plugin:compile && npm run ets:plugin:compile", - "plugins:patch": "npm run compile:patch --prefix arkoala/tools/arkoala-transformer", - "arkoala:plugin": "npm run plugins:compile && npm run plugins:patch", - "arkoala:har": "npm run all --prefix arkoala/har", - "arkoala:har-arm64": "npm run arkoala:har", - "arkoala:har-arm32": "npm run all-arm32 --prefix arkoala/har", - "arkoala:har-universal": "npm run all-universal --prefix arkoala/har" + "prepare": "cd incremental && npm i && cd .. && cd interop && npm i && cd .. && cd ui2abc && npm i" } } diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/BUILD.gn b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6d94941a746a75b00a17eed12bff9095d3282ed6 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/BUILD.gn @@ -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("//build/ohos.gni") + +node_version = "v16.20.2" +host_arch = "${host_os}-${host_cpu}" + +koala_root = ".." +libarkts_root = "./libarkts" + +action("install") { + script = "gn/command/install.py" + + outputs = [ + "$target_out_dir/install" + ] + + args = [ + "--project-path", rebase_path("$koala_root"), + "--node-path", rebase_path("//prebuilts/build-tools/common/nodejs/node-${node_version}-${host_arch}/bin") + ] + +} + +action("panda_sdk") { + script = "gn/command/gen_sdk.py" + + outputs = [ + "$target_out_dir/panda-sdk" + ] + + external_deps = [ + "ets_frontend:libes2panda_public", + ] + + args = [ + "--config", rebase_path("gn/sdk_config.json"), + "--src", rebase_path("//"), + "--dist", rebase_path("./build/sdk"), + "--out-root", rebase_path(root_out_dir) + ] +} + +group("ui2abc") { + deps = [ + "$libarkts_root:es2panda" + ] +} \ No newline at end of file diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/command/gen_sdk.py b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/command/gen_sdk.py new file mode 100755 index 0000000000000000000000000000000000000000..eb54c8a120daea96793891e1c138edb3a783e6b0 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/command/gen_sdk.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import shutil +import json +import argparse + +def load_config(config_file): + """Load the configuration file.""" + with open(config_file, 'r') as f: + config = json.load(f) + return config + +def replace_out_root(value, out_root): + """Replace $out_root in the string with the actual value.""" + return value.replace("$out_root", out_root) + +def copy_files(config, src_base, dist_base, out_root): + """Copy files or directories based on the configuration.""" + for mapping in config['file_mappings']: + # Replace $out_root + source = replace_out_root(mapping['source'], out_root) + destination = replace_out_root(mapping['destination'], out_root) + + # Build full paths + source = os.path.join(src_base, source) + destination = os.path.join(dist_base, destination) + + # Check if the source path exists + if not os.path.exists(source): + print(f"Source path does not exist: {source}") + continue + + # Create the destination directory if it doesn't exist + dest_dir = os.path.dirname(destination) if os.path.isfile(source) else destination + os.makedirs(dest_dir, exist_ok=True) + + # If it's a file, copy the file + if os.path.isfile(source): + try: + shutil.copy2(source, destination) + print(f"File copied: {source} -> {destination}") + except Exception as e: + print(f"Failed to copy file: {source} -> {destination}, error: {e}") + # If it's a directory, recursively copy the directory + elif os.path.isdir(source): + try: + shutil.copytree(source, destination, dirs_exist_ok=True) + print(f"Directory copied: {source} -> {destination}") + except Exception as e: + print(f"Failed to copy directory: {source} -> {destination}, error: {e}") + +def main(): + # Parse command-line arguments + parser = argparse.ArgumentParser(description="Copy files or directories.") + parser.add_argument("--config", required=True, help="Path to the configuration file.") + parser.add_argument("--src", required=True, help="Base source path.") + parser.add_argument("--dist", required=True, help="Base destination path.") + parser.add_argument("--out-root", required=True, help="Relative out directory to src, used to replace $out_root.") + args = parser.parse_args() + + # Load the configuration + config = load_config(args.config) + + # Copy files or directories + copy_files(config, args.src, args.dist, args.out_root) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/command/install.py b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/command/install.py new file mode 100755 index 0000000000000000000000000000000000000000..eddd20780d2909e790968dc9e04ceac4ad9e089c --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/command/install.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import subprocess +import os +import argparse + +NPM_REPO = "https://repo.huaweicloud.com/repository/npm/" + +parser = argparse.ArgumentParser(description="npm command parser") +parser.add_argument("--project-path", help="project directory in koala repo") +parser.add_argument("--node-path", help="nodejs path") + + +args = parser.parse_args() + +project_path = args.project_path +node_path = args.node_path + +env = os.environ.copy() +env_orig = env["PATH"] +env["PATH"] = f"{node_path}:{env['PATH']}" + +koala_log = os.path.join(project_path, "koala_build.log") + +def install(dir): + os.chdir(dir) + try: + ret = subprocess.run(["npm", "install", "--registry", NPM_REPO, "--verbose"], capture_output=True, env=env, text=True, check=True) + with open(koala_log, "a+") as f: + f.write("\n") + f.write("install log:\n" + ret.stdout) + f.close() + except subprocess.CalledProcessError as e: + with open(koala_log, "a+") as f: + f.write("\n") + f.write("error message: "+ e.output + "\n") + f.close() + + +def main(): + install(project_path) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/sdk_config.json b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/sdk_config.json new file mode 100644 index 0000000000000000000000000000000000000000..7bb2f87dccfa30119765518e5771140552bfb310 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/gn/sdk_config.json @@ -0,0 +1,40 @@ +{ + "file_mappings": [ + { + "source": "$out_root/clang_x64/arkcompiler/ets_frontend/es2panda", + "destination": "linux_host_tools/bin/es2panda" + }, + { + "source": "$out_root/clang_x64/arkcompiler/ets_frontend/libes2panda_public.so", + "destination": "linux_host_tools/lib/libes2panda-public.so" + }, + { + "source": "$out_root/clang_x64/arkcompiler/runtime_core/ark_link", + "destination": "linux_host_tools/bin/ark_link" + }, + { + "source": "$out_root/clang_x64/arkcompiler/runtime_core/libarktsbase.so", + "destination": "linux_host_tools/lib/libarktsbase.so" + }, + { + "source": "arkcompiler/runtime_core/static_core/plugins/ets/stdlib/escompat", + "destination": "ets/stdlib/escompat" + }, + { + "source": "arkcompiler/runtime_core/static_core/plugins/ets/stdlib/std", + "destination": "ets/stdlib/std" + }, + { + "source": "arkcompiler/ets_frontend/ets2panda/public/es2panda_lib.h", + "destination": "linux_host_tools/include/tools/es2panda/public/es2panda_lib.h" + }, + { + "source": "$out_root/clang_x64/gen/arkcompiler/ets_frontend/ets2panda/generated/es2panda_lib", + "destination": "linux_host_tools/include/tools/es2panda/generated/es2panda_lib" + }, + { + "source": "$out_root/clang_x64/gen/arkcompiler/runtime_core/static_core/plugins/ets/etsstdlib.abc", + "destination": "ets/etsstdlib.abc" + } + ] +} \ No newline at end of file diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/BUILD.gn b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c4cef3fe24ae0811f62858ed76397620f281d523 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/BUILD.gn @@ -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("//build/ohos.gni") + +koala_root = "../.." +libarkts_path = "." +ui2abc_path = ".." +interop_root = "$koala_root/interop" +build_root = "//build" +toolchain_linux = "$build_root/toolchain/linux:clang_x64" + +node_modules_dir = "../node_modules" + +node_version = "v16.20.2" +host_arch = "${host_os}-${host_cpu}" + + +os_define = "KOALA_LINUX" + +shared_library("es2panda_lib") { + sources = [ + "$libarkts_path/native/src/common.cc", + "$libarkts_path/native/src/bridges.cc", + "$libarkts_path/native/src/generated/bridges.cc", + + "$interop_root/src/cpp/napi/convertors-napi.cc", + "$interop_root/src/cpp/callback-resource.cc", + "$interop_root/src/cpp/interop-logging.cc", + "$interop_root/src/cpp/common-interop.cc" + ] + + include_dirs = [ + "$ui2abc_path/build/sdk/linux_host_tools/include/tools/es2panda/public", + "$ui2abc_path/build/sdk/linux_host_tools/include/tools/es2panda", + + "$libarkts_path/native/src", + + "$koala_root/interop/src/cpp", + "$koala_root/interop/src/cpp/napi", + "$koala_root/interop/src/cpp/types", + + "$node_modules_dir/node-api-headers/include", + "$node_modules_dir/node-addon-api", + + ] + + defines = [ + "$os_define", + "KOALA_INTEROP_MODULE=NativeModule", + "INTEROP_LIBRARY_NAME=es2panda", + "KOALA_USE_NODE_VM", + "KOALA_NAPI" + ] + + deps = [ + "$ui2abc_path:install" + ] + + configs -= [ "//build/config/compiler:compiler" ] + + cflags_cc = [ + "-std=c++17", + "-fPIC", + ] + + ldflags = [ + "-Wl,--allow-shlib-undefined", + + ] + + output_extension = "node" +} + +action("es2panda_copy_lib") { + script = "gn/command/copy.py" + outputs = [ + "$target_out_dir/es2panda.node" + ] + deps = [ + ":es2panda_lib(${toolchain_linux})" + ] + args = [ + "--from-path", rebase_path(root_out_dir), + "--to-path", rebase_path(".") + ] +} + +action("es2panda.js") { + script = "gn/command/npm.py" + outputs = [ + "$target_out_dir/es2panda.js" + ] + deps = [ + ":es2panda_copy_lib", + "$ui2abc_path:panda_sdk" + ] + args = [ + "--root-path", rebase_path(".."), + "--project-path", rebase_path("."), + "--node-path", rebase_path("//prebuilts/build-tools/common/nodejs/node-${node_version}-${host_arch}/bin"), + "--npm-args", "run", "compile:gn" + ] +} + +group("es2panda") { + deps = [ + ":es2panda.js" + ] +} diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/gn/command/copy.py b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/gn/command/copy.py new file mode 100755 index 0000000000000000000000000000000000000000..2d349e341978ec838493263a4e9c52287957a5d9 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/gn/command/copy.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os +import shutil +import subprocess +import sys + + +def 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 copy_output(options): + + copy_files(os.path.join(options.from_path, 'clang_x64/libes2panda.node'), + os.path.join(options.to_path, 'out/native/es2panda.node'), True) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--from-path', help='path to output') + parser.add_argument('--to-path', help='path to root out') + + options = parser.parse_args() + return options + + +def main(): + options = parse_args() + copy_output(options) + + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/gn/command/npm.py b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/gn/command/npm.py new file mode 100755 index 0000000000000000000000000000000000000000..47125f97a01d498e796fd41a88c3b5edbc8b573d --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/gn/command/npm.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python + +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import subprocess +import sys +import os +import shutil +import argparse + +NPM_REPO = "https://repo.huaweicloud.com/repository/npm/" + +parser = argparse.ArgumentParser(description="npm command parser") +parser.add_argument("--root-path", help="root directory of koala repo") +parser.add_argument("--project-path", help="project directory in koala repo") +parser.add_argument("--node-path", help="nodejs path") +parser.add_argument("--arklink-path", help="ark-link path") +parser.add_argument("--es2panda-path", help="es2panda path") +parser.add_argument("--stdlib-path", help="stdlib path") +parser.add_argument("--target-out-path", help="out directory of built target", default=None) +parser.add_argument("--built-file-path", help="result of building", default=None) +parser.add_argument("--npm-args", nargs='+', help="npm command args") + + +args = parser.parse_args() + +root_path = args.root_path +project_path = args.project_path +node_path = args.node_path + +target_out_path = args.target_out_path +built_file_path = args.built_file_path +npm_args = args.npm_args + +env = os.environ.copy() +env_orig = env["PATH"] +env["PATH"] = f"{node_path}:{env['PATH']}" + +koala_log = os.path.join(project_path, "koala_build.log") + +def install(dir): + os.chdir(dir) + try: + ret = subprocess.run(["npm", "install", "--registry", NPM_REPO, "--verbose"], capture_output=True, env=env, text=True, check=True) + with open(koala_log, "a+") as f: + f.write("\n") + f.write("install log:\n" + ret.stdout) + f.close() + except subprocess.CalledProcessError as e: + with open(koala_log, "a+") as f: + f.write("\n") + f.write("error message: "+ e.output + "\n") + f.close() + +def npm_command(dir, command): + os.chdir(dir) + try: + ret = subprocess.run(["npm"] + command, capture_output=True, env=env, text=True, check=True) + with open(koala_log, "a+") as f: + f.write("\n") + f.write("install log:\n" + ret.stdout) + f.close() + except subprocess.CalledProcessError as e: + with open(koala_log, "a+") as f: + f.write("\n") + f.write("error message: "+ e.output + "\n") + f.close() + +def main(): + install(root_path) + npm_command(project_path, npm_args) + + if target_out_path and built_file_path: + if not os.path.exists(built_file_path): + print(f"Error: Built file not found at {built_file_path}") + sys.exit(1) + + out_dir = os.path.join(target_out_path, os.path.basename(built_file_path)) + shutil.copy(built_file_path, out_dir) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/native/src/common.cc b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/native/src/common.cc index 31ce9150eec6a56a552ef322d2dbe6a75b32c4f7..c648e8a4a07de13ab9a3f7eff64ce77820276d29 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/native/src/common.cc +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/native/src/common.cc @@ -58,11 +58,13 @@ es2panda_Impl *GetImpl() { } auto library = FindLibrary(); if (!library) { - throw std::runtime_error("No library (es2panda_lib.cc)"); + printf("No library (es2panda_lib.cc)"); + abort(); } auto symbol = findSymbol(library, "es2panda_GetImpl"); if (!symbol) { - throw std::runtime_error("No entry point"); + printf("No entry point"); + abort(); } impl = reinterpret_cast(symbol)(ES2PANDA_LIB_VERSION); return impl; diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/package.json b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/package.json index 977974d599457e3817f860f25d5a6c48d4dc9aa3..5ce36f46dca652e2a6e99c6824c2e102b77b65e9 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/package.json +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/package.json @@ -41,7 +41,9 @@ "copy:.node": "mkdir -p ./build/native/build && cp ./native/build/es2panda.node ./build/native/build", "compile:native": "npm run compile:koala:interop && npm run compile:meson && npm run copy:.node", "compile:src": "npx ets-tsc -p ./tsconfig.json", - "compile": "npm run compile:native && npm run compile:src && rollup -c rollup.lib.mjs && rollup -c rollup.es2panda.mjs", + "compile": "npm run compile:native && npm run compile:js", + "compile:js": "npm run compile:src && rollup -c rollup.lib.mjs && rollup -c rollup.es2panda.mjs", + "compile:gn": "npm run compile:koala:interop && npm run compile:js", "compile:plugins": "npx rollup -c ./rollup.printer-plugin.mjs && npx rollup -c ./rollup.no-visitor-plugin.mjs ", "restart": "npx fast-arktsc --config arktsconfig.json --compiler ../../incremental/tools/panda/arkts/ui2abc --link-name ./build/abc/main.abc --file-option --restart-stages && ninja -f build/abc/build.ninja", "direct": "PANDA_SDK_PATH=../../incremental/tools/panda/node_modules/@panda/sdk node . --file ./plugins/input/direct.ets --output ./build/abc/direct.abc --dump-plugin-ast --arktsconfig ./arktsconfig-direct.json && file build/abc/direct.abc", diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/src/Es2pandaNativeModule.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/src/Es2pandaNativeModule.ts index db72a97fa38a8be71246ea60710472015aca2954..768d7073faae440d9f619b2d8ace27937598dd37 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/src/Es2pandaNativeModule.ts +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/src/Es2pandaNativeModule.ts @@ -133,6 +133,7 @@ export function findNativeModule(): string { const candidates = [ path.resolve(__dirname, "../native/build/es2panda.node"), path.resolve(__dirname, "../build/native/build/es2panda.node"), + path.resolve(__dirname, "../out/native/es2panda.node") // use from gn ] let result = undefined candidates.forEach(path => { diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/expressions/call-expression.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/expressions/call-expression.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..175494dd83df1147fa98ee08303ddf8c40cb3d2e --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/expressions/call-expression.test.ts @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as arkts from "../../../src/arkts-api" + +suite(util.basename(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + function _() {}; + ` + + const sample_out = + ` + function _() {}; + console.log('out') + ` + + let script = arkts.createETSModuleFromSource(sample_in) + + script = arkts.updateETSModuleByStatements( + script, + [ + script.statements[0], + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier( + 'console' + ), + arkts.Identifier.create2Identifier( + 'log' + ), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + [ + arkts.factory.createStringLiteral( + 'out' + ) + ], + undefined, + ) + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + sample_out + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/TreeNode.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/TreeNode.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f34bedeedae371b30dd734384af9565c1666f6a --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/TreeNode.test.ts @@ -0,0 +1,29 @@ +/* + * 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 * as util from "../../test-util" +import { filterSource } from "../../../src/utils" + +import * as fs from "node:fs" +import * as path from "node:path" +import { assert } from "chai" + +suite(util.basename(__filename), () => { + test.skip("TreeNode", function() { + const input = fs.readFileSync(path.join(__dirname, `./input/TreeNode.ts`), `utf8`) + const expected = fs.readFileSync(path.join(__dirname, `./golden/TreeNode.ts`), `utf8`) + assert.equal(filterSource(input), expected) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/golden/TreeNode.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/golden/TreeNode.ts new file mode 100644 index 0000000000000000000000000000000000000000..f01419d011db0bbc4d5e4e9c09df16d450fda8c8 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/golden/TreeNode.ts @@ -0,0 +1,100 @@ +/* + * 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 { Assert as Assert, suite as suite, test as test } from "../../../../../../incremental/harness/src"; + +import { float64 as float64, int32 as int32, uint32 as uint32 } from "@koalaui/common"; + +import { TreeNode as TreeNode } from "./TreeNode"; + + function main() {} + + export function _init2() { + suite("TreeNode", (() => {})); + } + + export function contentOf(node: TreeNode): string | undefined { + return ((node as StringNode)?.content); + } + + export function assertContent(node: TreeNode, content: string) { + Assert.equal(contentOf(node), content); + } + + export function assertRoot(node: TreeNode) { + Assert.isUndefined(node.parent); + Assert.equal(node.depth, 0); + Assert.equal(node.index, -1); + } + + export function assertLeaf(node: TreeNode) { + Assert.equal(node.childrenCount, 0); + } + + export function assertNoChildAt(parent: TreeNode, index: int32) { + Assert.isUndefined(parent.childAt(index)); + } + + export function assertChildAt(parent: TreeNode, index: int32): TreeNode { + let child = parent.childAt(index); + Assert.isDefined(child); + Assert.equal((child?.parent), parent); + Assert.equal((child?.index), index); + return child!; + } + + export function assertToString(root: TreeNode, expected: string) { + Assert.equal(root.toHierarchy(), expected); + } + + export function assertRemoveChildrenAt(root: TreeNode, index: int32, count: uint32, expected: int32) { + let childrenCount = root.childrenCount; + let children = root.removeChildrenAt(index, count); + Assert.equal(children.length, expected); + Assert.equal(root.childrenCount, ((childrenCount) - (expected))); + for (let i = 0;((i) < (expected));(i++)) { + assertRoot(children[i]); + } + } + + export function createRoot() { + return new StringNode("root", new StringNode("first"), new StringNode("second"), new StringNode("third")); + } + + export function createDigitsRoot() { + return new StringNode("digits", new StringNode("0"), new StringNode("1"), new StringNode("2"), new StringNode("3"), new StringNode("4"), new StringNode("5"), new StringNode("6"), new StringNode("7"), new StringNode("8"), new StringNode("9")); + } + + export function hellohellohello() { + console.log("hello"); + } + + export const __ARKTEST__ = "tree/TreeNode.test"; + + +export class StringNode extends TreeNode { + public readonly content: string; + + public constructor(content: string, ...children: StringNode[]) { + super(); + (this).content = content; + (this).appendChildren(...children); + } + + public toString(): string { + return (this).content; + } + +} \ No newline at end of file diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/input/TreeNode.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/input/TreeNode.ts new file mode 100644 index 0000000000000000000000000000000000000000..e95a0bbee7bbf95a188413e47ba7faa47e672529 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/filter-source/input/TreeNode.ts @@ -0,0 +1,106 @@ +/* + * 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 { Assert as Assert, suite as suite, test as test } from "../../../../../../incremental/harness/src"; + +import { float64 as float64, int32 as int32, uint32 as uint32 } from "@koalaui/common"; + +import { TreeNode as TreeNode } from "./TreeNode"; + +abstract class ETSGLOBAL { + public static main() {} + + public static _$init$_() { + suite("TreeNode", (() => {})); + } + + public static contentOf(node: TreeNode): string | undefined { + return ({let gensym%%_21 = (node as StringNode); + (((gensym%%_21) == (null)) ? undefined : gensym%%_21.content)}); + } + + public static assertContent(node: TreeNode, content: string) { + Assert.equal(contentOf(node), content); + } + + public static assertRoot(node: TreeNode) { + Assert.isUndefined(node.parent); + Assert.equal(node.depth, 0); + Assert.equal(node.index, -1); + } + + public static assertLeaf(node: TreeNode) { + Assert.equal(node.childrenCount, 0); + } + + public static assertNoChildAt(parent: TreeNode, index: int32) { + Assert.isUndefined(parent.childAt(index)); + } + + public static assertChildAt(parent: TreeNode, index: int32): TreeNode { + let child = parent.childAt(index); + Assert.isDefined(child); + Assert.equal(({let gensym%%_22 = child; + (((gensym%%_22) == (null)) ? undefined : gensym%%_22.parent)}), parent); + Assert.equal(({let gensym%%_23 = child; + (((gensym%%_23) == (null)) ? undefined : gensym%%_23.index)}), index); + return child!; + } + + public static assertToString(root: TreeNode, expected: string) { + Assert.equal(root.toHierarchy(), expected); + } + + public static assertRemoveChildrenAt(root: TreeNode, index: int32, count: uint32, expected: int32) { + let childrenCount = root.childrenCount; + let children = root.removeChildrenAt(index, count); + Assert.equal(children.length, expected); + Assert.equal(root.childrenCount, ((childrenCount) - (expected))); + for (let i = 0;((i) < (expected));(i++)) { + assertRoot(children[i]); + } + } + + public static createRoot() { + return new StringNode("root", new StringNode("first"), new StringNode("second"), new StringNode("third")); + } + + public static createDigitsRoot() { + return new StringNode("digits", new StringNode("0"), new StringNode("1"), new StringNode("2"), new StringNode("3"), new StringNode("4"), new StringNode("5"), new StringNode("6"), new StringNode("7"), new StringNode("8"), new StringNode("9")); + } + + public static hellohellohello() { + console.log("hello"); + } + + public static __ARKTEST__ = "tree/TreeNode.test"; + + +} + +class StringNode extends TreeNode { + public readonly content: string; + + public constructor(content: string, ...children: StringNode[]) { + super(); + (this).content = content; + (this).appendChildren(...children); + } + + public toString(): string { + return (this).content; + } + +} \ No newline at end of file diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/functions/create.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/functions/create.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..59df9895d0a1032a9deb7fc91114f1e8f7e20a84 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/functions/create.test.ts @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as arkts from "../../../src/arkts-api" + +suite(util.basename(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + function _() {}; + ` + + const sample_out = + ` + function _() {}; + function foo() { + console.log("AAA") + } + foo() + ` + + let script = arkts.createETSModuleFromSource(sample_in) + + const scriptFunc = + arkts.factory.createScriptFunction( + arkts.factory.createBlockStatement( + [ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier( + 'console' + ), + arkts.factory.createIdentifier( + 'log' + ), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + + [ + arkts.factory.createStringLiteral( + 'AAA' + ) + ], + undefined, + ) + ) + ] + ), + undefined, + [], + undefined, + false, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + arkts.factory.createIdentifier("foo"), + undefined, + ) + + const funcDecl = + arkts.factory.createFunctionDeclaration( + scriptFunc, + [], + false + ) + funcDecl.updateModifiers(scriptFunc.modifierFlags) + + script = arkts.updateETSModuleByStatements( + script, + [ + script.statements[0], + funcDecl, + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createIdentifier( + 'foo' + ), + [], + undefined, + ) + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + sample_out + ) + }) + + test("sample-2", function() { + const sample_in = + ` + function _() {}; + ` + + const sample_out = + ` + function _() {}; + function foo(x: int, y: string = "bbb") { + console.log(x) + console.log(y) + } + foo(0) + ` + + let script = arkts.createETSModuleFromSource(sample_in) + + const scriptFunc = + arkts.factory.createScriptFunction( + arkts.factory.createBlockStatement( + [ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier( + 'console' + ), + arkts.factory.createIdentifier( + 'log' + ), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + + [ + arkts.factory.createIdentifier( + 'x' + ) + ], + undefined, + ) + ), + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier( + 'console' + ), + arkts.factory.createIdentifier( + 'log' + ), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + + [ + arkts.factory.createIdentifier( + 'y' + ) + ], + undefined, + ) + ) + ] + ), + undefined, + [ + arkts.factory.createETSParameterExpression( + arkts.factory.createIdentifier( + 'x', + arkts.factory.createETSPrimitiveType( + arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_INT + ) + ), + false + ), + arkts.factory.createETSParameterExpression( + arkts.factory.createIdentifier( + 'y', + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( + arkts.factory.createIdentifier( + 'string' + ) + ) + ) + ), + false, + arkts.factory.createStringLiteral( + 'bbb' + ) + ) + ], + undefined, + false, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + arkts.factory.createIdentifier("foo"), + undefined, + ) + + const funcDecl = + arkts.factory.createFunctionDeclaration( + scriptFunc, + [], + false + ) + funcDecl.updateModifiers(scriptFunc.modifierFlags) + + script = arkts.updateETSModuleByStatements( + script, + [ + script.statements[0], + funcDecl, + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createIdentifier( + 'foo' + ), + [ + arkts.factory.createNumberLiteral( + 0 + ) + ], + undefined, + ) + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + sample_out + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/annotations.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/annotations.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..05c00320ecf4d573abd558a70e28dd86bb8fca05 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/annotations.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as arkts from "../../../src/arkts-api" +import { assert } from "chai" + +suite(util.basename(__filename), () => { + test("annotated-function-1", function() { + const sample_in = + ` + @annotation1 + @annotation2 + function foo() {} + ` + + let script = arkts.createETSModuleFromSource( + sample_in, + arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED + ) + + const annotations = arkts.getAnnotations(script.statements[0]) + + const names = annotations.map((annot) => { + if (annot.expr === undefined) { + throw new Error('annotation expression is undefined') + } + if (!arkts.isIdentifier(annot.expr)) { + throw new Error('annotation expected to be Identifier') + } + return annot.expr.name + }) + + assert.equal(names.join(', '), 'annotation1, annotation2') + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/basic.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/basic.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..84e8044f3e817916c6c949ebfba4ef232df57b1a --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/basic.test.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 * as util from "../../test-util" +import * as arkts from "../../../src/arkts-api" + +suite(util.basename(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + ` + + let script = arkts.createETSModuleFromSource(sample_in) + + script = arkts.updateETSModuleByStatements( + script, + [ + arkts.factory.createExpressionStatement( + arkts.factory.createIdentifier( + 'abc' + ) + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + abc + `, + arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/recheck.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/recheck.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b266cb474803f70dbab9a2f02d3b1f208513ceb --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/general/recheck.test.ts @@ -0,0 +1,356 @@ +/* + * 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 * as util from "../../test-util" +import * as arkts from "../../../src/arkts-api" + +function createConfig() { + arkts.arktsGlobal.config = arkts.Config.create([ + '_', + '--arktsconfig', + 'arktsconfig.json', + './plugins/input/main.ets', + '--extension', + 'ets', + '--stdlib', + '../../incremental/tools/panda/node_modules/@panda/sdk/ets/stdlib', + '--output', + './build/main.abc' + ]).peer +} + +function updateTopLevelClass( + module: arkts.ETSModule, + className: string, + update: (node: arkts.ClassDefinition) => arkts.ClassDefinition +) { + return arkts.updateETSModuleByStatements( + module, + [ + ...module.statements.map((node) => { + if (!arkts.isClassDeclaration(node)) { + return node + } + if (!arkts.isClassDefinition(node.definition)) { + return node + } + if (node.definition.ident?.name == className) { + return arkts.factory.updateClassDeclaration( + node, + update(node.definition) + ) + } + return node + }) + ] + ) +} + +suite(util.basename(__filename), () => { + + test("static (function)", function() { + createConfig() + + const code = + ` + function foo() {} + ` + + arkts.arktsGlobal.compilerContext = arkts.Context.createFromString(code) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) + + arkts.recheckSubtree(arkts.createETSModuleFromContext()) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED) + }) + + test.skip("static (property)", function() { + createConfig() + + const code = + ` + interface I { + prop: boolean + } + + class C implements I { + prop = true + } + ` + + arkts.arktsGlobal.compilerContext = arkts.Context.createFromString(code) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) + + arkts.recheckSubtree(arkts.createETSModuleFromContext()) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED) + }) + + test("rename class", function() { + createConfig() + + const code = + ` + class C { + f(): void { + } + } + ` + + arkts.arktsGlobal.compilerContext = arkts.Context.createFromString(code) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) + + const module = arkts.createETSModuleFromContext() + + updateTopLevelClass(module, "C", (node: arkts.ClassDefinition) => { + return arkts.factory.updateClassDefinition( + node, + node.ident ? arkts.factory.updateIdentifier( + node.ident, + "D" + ) : undefined, + node.typeParams, + node.superTypeParams, + node.implements, + undefined, + node.super, + node.body, + node.modifiers, + node.modifierFlags + ) + }) + + arkts.arktsGlobal.es2panda._AstNodeUpdateAll(arkts.arktsGlobal.context, module.peer) + arkts.recheckSubtree(module) + + util.assert( + module.dumpSrc() == ` +function main() {} + + + +class D { + public f(): void {} + + public constructor() {} + +} + +`, + `invalid result: ${module.dumpSrc()}`) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED) + }) + + test("add class method", function() { + createConfig() + + const code = + ` + class C { + } + ` + + arkts.arktsGlobal.compilerContext = arkts.Context.createFromString(code) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) + + const module = arkts.createETSModuleFromContext() + + updateTopLevelClass(module, "C", (node: arkts.ClassDefinition) => { + return arkts.factory.updateClassDefinition( + node, + node.ident, + node.typeParams, + node.superTypeParams, + node.implements, + undefined, + node.super, + [ + arkts.factory.createMethodDefinition( + arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + arkts.factory.createIdentifier("g"), + arkts.factory.createFunctionExpression( + arkts.factory.createIdentifier("g"), + arkts.factory.createScriptFunction( + arkts.factory.createBlockStatement([ + arkts.factory.createReturnStatement( + arkts.factory.createNumberLiteral(5) + ) + ]), + undefined, + [], + arkts.factory.createETSPrimitiveType( + arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_DOUBLE, + ), + false, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + arkts.factory.createIdentifier("g"), + undefined, + ) + ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + false, + ), + ...node.body, + ], + node.modifiers, + node.modifierFlags + ) + }) + + arkts.arktsGlobal.es2panda._AstNodeUpdateAll(arkts.arktsGlobal.context, module.peer) + arkts.recheckSubtree(module) + + util.assert( + module.dumpSrc() == ` +function main() {} + + + +class C { + public g(): double { + return 5; + } + + public constructor() {} + +} + +`, + `invalid result: ${module.dumpSrc()}`) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED) + }) + + test("add variable declaration", function() { + createConfig() + + const code = + ` + class C { + f(): void { + } + } + ` + + arkts.arktsGlobal.compilerContext = arkts.Context.createFromString(code) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) + + const module = arkts.createETSModuleFromContext() + + updateTopLevelClass(module, "C", (node: arkts.ClassDefinition) => { + return arkts.factory.updateClassDefinition( + node, + node.ident, + node.typeParams, + node.superTypeParams, + node.implements, + undefined, + node.super, + [ + ...node.body.map((node: arkts.AstNode) => { + if (!arkts.isMethodDefinition(node)) { + return node + } + if (node.id?.name != "f") { + return node + } + if (!arkts.isFunctionExpression(node.value)) { + return node + } + const func = node.value.function + if (!func || !arkts.isBlockStatement(func.body)) { + return node + } + return arkts.factory.updateMethodDefinition( + node, + node.kind, + node.key, + arkts.factory.updateFunctionExpression( + node.value, + node.id, + arkts.factory.updateScriptFunction( + func, + arkts.factory.updateBlockStatement( + func.body, + [ + arkts.factory.createVariableDeclaration( + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, + [ + arkts.factory.createVariableDeclarator( + arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_CONST, + arkts.factory.createIdentifier("x"), + arkts.factory.createBinaryExpression( + arkts.factory.createNumberLiteral(1), + arkts.factory.createNumberLiteral(4), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS, + ), + ), + ], + ), + ...func.body.statements, + ], + ), + func.typeParams, + func.params, + func.returnTypeAnnotation, + func.hasReceiver, + func.flags, + func.modifierFlags, + func.id, + func.annotations, + ), + ), + node.modifierFlags, + node.isComputed, + node.overloads, + ) + }) + ], + node.modifiers, + node.modifierFlags + ) + }) + + arkts.arktsGlobal.es2panda._AstNodeUpdateAll(arkts.arktsGlobal.context, module.peer) + arkts.recheckSubtree(module) + + util.assert( + module.dumpSrc() == ` +function main() {} + + + +class C { + public f(): void { + const x = ((1) + (4)); + } + + public constructor() {} + +} + +`, + `invalid result: ${module.dumpSrc()}`) + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/import-export/import.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/import-export/import.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c5d42e44677068e45456bc1ea1a08e862d1b119 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/arkts-api/import-export/import.test.ts @@ -0,0 +1,224 @@ +/* + * 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 * as util from "../../test-util" +import * as arkts from "../../../src/arkts-api" +import { global } from "../../../src/arkts-api/static/global" + + +suite(util.basename(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + ` + + let script = arkts.createETSModuleFromSource(sample_in) + + script = arkts.updateETSModuleByStatements( + script, + [ + arkts.factory.createETSImportDeclaration( + arkts.factory.createStringLiteral( + './variable' + ), + [ + arkts.factory.createImportSpecifier( + arkts.factory.createIdentifier( + 'X' + ), + arkts.factory.createIdentifier( + 'X' + ) + ) + ], + arkts.Es2pandaImportKinds.IMPORT_KINDS_ALL, + global.compilerContext.program, + arkts.Es2pandaImportFlags.IMPORT_FLAGS_DEFAULT_IMPORT + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + import { X } from "./variable" + `, + arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED + ) + }) + + test("sample-2-rewrite", function() { + const sample_in = + ` + import { Y } from "./variable" + ` + + let script = arkts.createETSModuleFromSource(sample_in) + const importDeclaration = script.statements[0] as arkts.ETSImportDeclaration + + script = arkts.updateETSModuleByStatements( + script, + [ + arkts.factory.updateETSImportDeclaration( + importDeclaration, + importDeclaration.source, + [ + arkts.factory.createImportSpecifier( + arkts.factory.createIdentifier( + 'X' + ), + arkts.factory.createIdentifier( + 'X' + ) + ) + ], + arkts.Es2pandaImportKinds.IMPORT_KINDS_ALL, + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + import { X } from "./variable" + `, + arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED + ) + }) + + test("rewrite-imported-variable", function() { + const sample_in = + ` + import { Y } from "./variable" + + function main() { + console.log(X) + } + ` + + let script = arkts.createETSModuleFromSource(sample_in) + const importDeclaration = script.statements[0] as arkts.ETSImportDeclaration + + script = arkts.updateETSModuleByStatements( + script, + [ + arkts.factory.updateETSImportDeclaration( + importDeclaration, + importDeclaration.source, + [ + arkts.factory.createImportSpecifier( + arkts.factory.createIdentifier( + 'X' + ), + arkts.factory.createIdentifier( + 'X' + ) + ) + ], + arkts.Es2pandaImportKinds.IMPORT_KINDS_ALL, + ), + script.statements[1] + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + import { X } from "./variable" + + function main() { + console.log(X) + } + `, + arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED + ) + + // util.cleanGenerated() + // util.fileToAbc(`./input/variable.sts`, true) + // util.contextToAbc() + // util.runAbc(`./generated/main.abc`, ['./generated/variable.abc']) + }) + + test("rewrite-imported-function", function() { + const sample_in = + ` + import { f } from "./f" + function main() {} + ` + + let script = arkts.createETSModuleFromSource(sample_in) + const functionDeclaration: arkts.FunctionDeclaration = script.statements[1] as arkts.FunctionDeclaration + const scriptFunction: arkts.ScriptFunction = functionDeclaration.function! + + const newScriptFunc = + arkts.factory.updateScriptFunction( + scriptFunction, + arkts.factory.createBlockStatement( + [ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createIdentifier( + 'f' + ), + [],undefined, + + ) + ) + ] + ), + undefined, + [], + undefined, + false, + scriptFunction.flags, + scriptFunction.modifierFlags, + scriptFunction.id!, + undefined, + ) + + const newFuncDecl = + arkts.factory.updateFunctionDeclaration( + functionDeclaration, + newScriptFunc, + [], + false + ) + newFuncDecl.updateModifiers(newScriptFunc.modifierFlags) + + script = arkts.updateETSModuleByStatements( + script, + [ + script.statements[0], + newFuncDecl + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + import { f } from "./f" + function main() { + f() + } + `, + arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED + ) + + // util.cleanGenerated() + // util.fileToAbc(`./input/f.sts`, true) + // util.contextToAbc() + // util.runAbc(`./generated/main.abc`, ['./generated/f.abc']) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/test-util.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/test-util.ts new file mode 100644 index 0000000000000000000000000000000000000000..35269334e73f9bf0ede38cc16042d1125612f199 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/test-util.ts @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 "../src/arkts-api/static/global" +import * as arkts from "../src/arkts-api" + +import * as pth from "path" +import { assert } from "chai" +import { exec, execSync } from "child_process" + +export { Es2pandaNativeModule } from "../src/Es2pandaNativeModule" +export { assert } from "chai" + +export function alignText(text: string): string { + const lines = text.replace(/\t/gy, ' ').split('\n') + + const shift = + lines + .map((str: string) => str.search(/\S/)) + .reduce( + (prev: number, curr: number) => { + if (prev === -1) { + return curr + } + if (curr === -1) { + return prev + } + return Math.min(prev, curr) + } + ) + return lines.map(str => str.slice((shift === -1) ? 0 : shift)).join('\n').trim() +} + +export function basename(fileName: string) { + return pth.basename(fileName).split('.')[0] +} + +export function assertEqualsSource(sourceResult: string, sourceExpect: string, message?: string) { + assert.equal( + sourceResult.trim().split('\n').map((line: string) => line.trim()).join('\n'), + sourceExpect.trim().split('\n').map((line: string) => line.trim()).join('\n'), + message + ) +} + +export function ARKTS_TEST_ASSERTION(node: arkts.ETSModule, source: string, state?: arkts.Es2pandaContextState) { + const finalState: arkts.Es2pandaContextState = (() => { + if (state !== undefined) { + return state + } + if (process.env.STATE_CHECKED !== undefined) { + return arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED + } + return arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED + })() + arkts.proceedToState(finalState) + + const ast = node.dumpJson() + const src = node.dumpSrc() + const dump = node.dump() + global.es2panda._DestroyContext(global.context) + + try { + const script = arkts.createETSModuleFromSource(source, finalState) + assertEqualsSource(src, script.dumpSrc(), 'Error on SOURCE comparison') + assert.equal(ast, script.dumpJson(), 'Error on JSON comparison') + assert.equal(dump, script.dump(), 'Error on DUMP comparison') + } finally { + global.es2panda._DestroyContext(global.context) + } +} + + + +export function cleanGenerated(): void { + exec('npm run clean:generated') +} + +export function fileToAbc(path: string, isModule?: boolean): void { + const file = pth.basename(path).split('.')[0] + + execSync(`../../../incremental/tools/panda/node_modules/@panda/sdk/linux_host_tools/bin/es2panda ${path} --arktsconfig ./arktsconfig.json ${isModule ? '--ets-module' : ''}`) + execSync('mkdir -p ./generated') + execSync(`mv ./${file}.abc ./generated/${file}.abc`) +} + +export function contextToAbc(): void { + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED) + // TODO: get name of file + execSync('mkdir -p ./generated') + execSync('mv ./main.abc ./generated/main.abc') +} + +export function runAbc(path: string = './generated/main.abc', modules?: readonly string[]): void { + const modulesStr: string = (modules === undefined) ? '' : (':' + modules.join(':')) + + exec(`../../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${modulesStr} ${path} ETSGLOBAL::main`, + (error: any, stdout: string, stderr: string) => { + if (error !== null) { + assert(false, `failed to run abc: ${error}`) + } + console.log(`stdout: ${stdout}`); + console.log(`stderr: ${stderr}`); + } + ) +} + +export function assertEqualsBinaryOutput(output: string, ctx: Mocha.Context): void { + if (process.env.TEST_BIN === undefined) { + ctx.skip() + } + try { + contextToAbc() + exec( + 'npm run run:abc', + (error: any, stdout: string, stderr: string) => { + if (error !== null) { + assert(false, `failed to run abc: ${error}`) + } + const lines = stdout.trim().split('\n') + assert(lines.length >= 2) + assert.equal(lines[0], '> run:abc') + assert.equal(stderr, '') + if (lines.length === 2) { + assert.equal('', output.trim()) + } else { + assert.equal(lines.splice(2).join('\n').trim(), output.trim()) + } + } + ) + } finally { + global.es2panda._DestroyContext(global.context) + } +} diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/classes/heritage/extends.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/classes/heritage/extends.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d8a4e554140097e6582d55fa25fc90c59723a53 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/classes/heritage/extends.test.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../../test-util" +import * as ts from "../../../../src/ts-api" +import { factory } from "../../../../src/ts-api" + +// TODO: +suite.skip(util.basename(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + abstract class A {}; + abstract class C {}; + interface D {}; + class B extends A implements C, D {}; + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + // sourceFile = factory.updateSourceFile( + // sourceFile, + // [ + // factory.createClassDeclaration( + // [ + // factory.createToken(ts.SyntaxKind.AbstractKeyword) + // ], + // factory.createIdentifier("A"), + // undefined, + // undefined, + // [] + // ), + // factory.createClassDeclaration( + // undefined, + // factory.createIdentifier("B"), + // undefined, + // [ + // factory.createHeritageClause( + // ts.SyntaxKind.ExtendsKeyword, + // [ + // factory.createExpressionWithTypeArguments( + // factory.createIdentifier("A"), + // undefined + // ) + // ] + // ) + // ], + // [] + // ) + // ] + // ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + abstract class A {}; + class B extends A {}; + ` + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/cross/cross.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/cross/cross.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..de273c4aa9f445211ab1277e1431dce527eee9f6 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/cross/cross.test.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as ts from "../../../src/ts-api" + +suite.skip(util.basename(__filename), () => { + test("imported-function-call", function() { + const sample_in = + ` + import { X } from "./variable" + + export function main() { + console.log(X) + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + util.cleanGenerated() + util.fileToAbc(`./input/variable.sts`, true) + util.contextToAbc() + util.runAbc(`./generated/main.abc`, ['./generated/variable.abc']) + }) + + test("rewrite-imported-function-call", function() { + const sample_in = + ` + import { X } from "./variable" + + export function main() { + console.log(Y) + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + util.cleanGenerated() + util.fileToAbc(`./input/variable.sts`, true) + util.contextToAbc() + util.runAbc(`./generated/main.abc`, ['./generated/variable.abc']) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/classes.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/classes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6bd1167c97432c27abc5cc3a5ad947bc36b5c57 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/classes.test.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +// import * as ts from "../../../src/ts-api" +// import { MemoTransformer } from "../../../plugins/src/memo-transformer" +// +// suite(util.basename(__filename), () => { +// test.skip("stinger-node-class", function() { +// const sample_in = +// ` +// // import { uint32 } from "@koalaui/common" +// // import { CONTEXT_ROOT_SCOPE, IncrementalNode, NodeAttach, ReadonlyTreeNode, +// // contextLocalValue, memoRoot, mutableState, updateStateManager, +// // } from "@koalaui/runtime" +// +// // type uint32 = int +// +// abstract class IncrementalNode { +// constructor(kind: int) {} +// }; +// +// class StringerNode extends IncrementalNode { +// constructor(kind: int = 1) { +// super(kind) +// } +// data: string | undefined = undefined +// } +// ` +// +// const sourceFile = ts.factory.createSourceFile(sample_in, ts.ContextState.ES2PANDA_STATE_CHECKED) +// util.assert(ts.isSourceFile(sourceFile)) +// +// const result = (new MemoTransformer()).visitor(sourceFile) +// util.assert(ts.isSourceFile(result)) +// +// util.assertEqualsSource( +// result.node.dumpSrc(), +// ` +// ` +// ) +// }) +// }) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/main.sts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/main.sts new file mode 100644 index 0000000000000000000000000000000000000000..464b0be3c00a5905d108c2bc4ee72c9f4bed22e3 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/main.sts @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { uint32 } from "@koalaui/common" +import { CONTEXT_ROOT_SCOPE, IncrementalNode, NodeAttach, ReadonlyTreeNode, + contextLocalValue, memoRoot, mutableState, updateStateManager, +} from "@koalaui/runtime" + +class StringerNode extends IncrementalNode { + constructor(kind: uint32 = 1) { + super(kind) + } + data: string | undefined = undefined +} + +/** @memo */ +function Stringer( + arg: string, + /** @memo */ + content?: () => void +): void { + NodeAttach(() => new StringerNode(), (node: StringerNode): void => { + node.data = arg + console.log("I am recomputing with arg: ", arg) + content?.() + }) +} + +const state = mutableState(17) + +/** @memo */ +function demo(node: StringerNode): void { + Stringer("First", () => { + console.log("Content of the first") + Stringer(`Second ${state.value}`, () => { + console.log("Content of the second") + Stringer("Third") + }) + Stringer("Fourth", () => { + console.log("Content of the 4th") + Stringer("5th") + }) + }) + + // This is to dump the complete managed incremental scope tree + const scope = contextLocalValue(CONTEXT_ROOT_SCOPE) + console.log(scope?.toHierarchy()) +} + +// memoRoot is the entry point here. +// It initializes the incremental runtime and computes the first frame. +// Have a look at its implementation. +const root = memoRoot(new StringerNode(0), demo) +console.log(root.value.toHierarchy()) // dump ui subtree + +updateStateManager() // Compute next frame. +console.log(root.value.toHierarchy()) + +state.value = 19 + +updateStateManager() // Compute the next frame. +console.log(root.value.toHierarchy()) +console.log("-----END-----") diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/memo-rewrites.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/memo-rewrites.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..142c57c212d36e32138bd0b59e5e215651749d2c --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/demo-playground/memo-rewrites.test.ts @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +// import * as ts from "../../../src/ts-api" +// import { MemoTransformer } from "../../../plugins/src/memo-transformer" +// +// suite(util.getSuiteTitle(__filename), () => { +// test.skip("function-stinger", function() { +// const sample_in = +// ` +// /** @memo */ +// function _MEMO_Stringer( +// arg: string, +// /** @memo */ +// _MEMO_content: () => void +// ): void { +// _MEMO_content() +// } +// ` +// +// const sourceFile = ts.factory.createSourceFile(sample_in, ts.ContextState.ES2PANDA_STATE_CHECKED) +// util.assert(ts.isSourceFile(sourceFile)) +// +// const result = (new MemoTransformer()).visitor(sourceFile) +// util.assert(ts.isSourceFile(result)) +// +// util.assertEqualsSource( +// result.node.dumpSrc(), +// ` +// abstract class ETSGLOBAL { +// public static _$init$_() {} +// +// public static Stringer(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: string, _MEMO_content: (()=> void)) { +// if (__memo_scope.unchanged) { +// return __memo_scope.cached; +// } +// content(__memo_context, ((__memo_id) + ("key_id_main.ts"))); +// content(__memo_context, __memo_id); +// return __memo_scope.recache(); +// } +// +// +// } +// ` +// ) +// }) +// }) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/function-declaration/create-function-declaration.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/function-declaration/create-function-declaration.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ba2dfc927c2faf19acd6a9a0460ee322fdfd3d9 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/function-declaration/create-function-declaration.test.ts @@ -0,0 +1,442 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../../test-util" +import * as ts from "../../../../src/ts-api" +import { factory } from "../../../../src/ts-api" + +suite.skip(util.basename(__filename), () => { + test("empty-function", function() { + // function test_func() { + // // empty + // } + + const sample_in = `` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const funcDecl = ts.factory.createFunctionDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("test_func"), + undefined, + [], + undefined, + ts.factory.createBlock( + [], + true + ) + ) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function test_func() {} + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + test("empty-function-with-param", function() { + const sample_in = `` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const funcParams = [ + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("x"), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + undefined + ) + ] + const funcDecl = ts.factory.createFunctionDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("test_func"), + undefined, + funcParams, + undefined, + ts.factory.createBlock( + [], + true + ) + ) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function test_func(x: number) {} + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + test("empty-function-with-string-param", function() { + // function test_func(x: string) { + // // empty + // } + + const sample_in = `` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const funcParams = [ + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("x"), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + undefined + ) + ] + const funcDecl = ts.factory.createFunctionDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("test_func"), + undefined, + funcParams, + undefined, + ts.factory.createBlock( + [], + true + ) + ) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function test_func(x: string) {} + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + test("async-empty-function", function() { + // async function test_func() {} + + const sample_in = `` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const funcDecl = ts.factory.createFunctionDeclaration( + [ + ts.factory.createToken(ts.SyntaxKind.AsyncKeyword) + ], + undefined, + ts.factory.createIdentifier("test_func"), + undefined, + [], + undefined, + ts.factory.createBlock( + [], + true + ) + ) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + async function test_func() {} + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + test.skip("empty-method-with-public-static-modifiers", function() { + const sample_in = + ` + class A { + } + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let classDecl = sourceFile.statements[0] + util.assert(ts.isClassDeclaration(classDecl)) + + classDecl = factory.updateClassDeclaration( + classDecl, + undefined, + factory.createIdentifier("A"), + undefined, + undefined, + [ + factory.createMethodDeclaration( + [ + factory.createToken(ts.SyntaxKind.PublicKeyword), + factory.createToken(ts.SyntaxKind.StaticKeyword) + ], + undefined, + factory.createIdentifier("test_func"), + undefined, + undefined, + [], + undefined, + factory.createBlock( + [], + false + ) + ), + factory.createConstructorDeclaration( + [ + factory.createToken(ts.SyntaxKind.PublicKeyword) + ], + [], + factory.createBlock( + [], + false + ) + ) + ] + ) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + classDecl + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + class A { + public static test_func() {} + + public constructor() {} + + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + test("function-with-type-parameters", function() { + // function test_func(): void {} + + const sample_in = + ` + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const funcDecl = ts.factory.createFunctionDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("test_func"), + [ + ts.factory.createTSTypeParameterDeclaration( + undefined, + ts.factory.createIdentifier("T"), + undefined, + undefined + ), + ts.factory.createTSTypeParameterDeclaration( + undefined, + ts.factory.createIdentifier("K"), + undefined, + undefined + ) + ], + [], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword), + ts.factory.createBlock( + [], + true + ) + ) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function test_func(): void {} + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + // TODO: change 0 -> 777 (waiting fix) + test("sample-1", function() { + const sample_in = + ` + console.log("OK") + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const funcDecl = factory.createFunctionDeclaration( + undefined, + undefined, + factory.createIdentifier("foo"), + undefined, + [ + factory.createParameterDeclaration( + undefined, + undefined, + factory.createIdentifier("x"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + factory.createNumericLiteral(0) + ), + factory.createParameterDeclaration( + undefined, + undefined, + factory.createIdentifier("y"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + factory.createStringLiteral("abc") + ) + ], + factory.createETSUnionTypeNode([ + factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword) + ]), + factory.createBlock( + [factory.createReturnStatement(factory.createBinaryExpression( + factory.createIdentifier("x"), + factory.createToken(ts.SyntaxKind.PlusToken), + factory.createIdentifier("y") + ))], + true + ) + ) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + funcDecl, + sourceFile.statements[0] + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo(x: number = 0, y: string = "abc"): number | string { + return x + y + } + console.log("OK") + ` + ) + }) + + // TODO: change 0 -> 777 (waiting fix) + test("sample-2", function() { + const sample_in = + ` + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const funcDecl = ts.factory.createFunctionDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("foo"), + undefined, + [ + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("x"), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + ts.factory.createNumericLiteral(0) + ), + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("y"), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + ts.factory.createStringLiteral("abc") + ) + ], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + ts.factory.createBlock( + [ + ts.factory.createReturnStatement( + ts.factory.createIdentifier("x") + ) + ], + true + ) + ) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + funcDecl, + // sourceFile.statements[0] + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo(x: number = 0, y: string = "abc"): number { + return x + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/function-declaration/update-function-declaration.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/function-declaration/update-function-declaration.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed3b74fe70182bc40478dc2bd9a5308c63621911 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/function-declaration/update-function-declaration.test.ts @@ -0,0 +1,567 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../../test-util" +import * as ts from "../../../../src/ts-api" + +suite.skip(util.basename(__filename), () => { + // adding y: string to signature + test("update-name-and-add-param-to-function", function() { + // function new_test_func(x: number, y: string) { + // // empty + // } + + const sample_in = + ` + function test_func(x: number) { + // empty + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + + const newParam = ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("y"), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + undefined + ) + testFunc = ts.factory.updateFunctionDeclaration( + testFunc, + undefined, + undefined, + ts.factory.createIdentifier("new_test_func"), + undefined, + [ + ...testFunc.parameters, + newParam + ], + undefined, + testFunc.body + ) + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function new_test_func(x: number, y: string) {} + ` + ) + }) + + // adding memo params to signature + test("add-params-to-memo-function", function() { + // function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number) { + // // empty + // } + + const sample_in = + ` + function foo(x: number) { + // empty + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + + testFunc = util.addMemoParamsToFunctionDeclaration(testFunc) + util.assert(ts.isFunctionDeclaration(testFunc)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number) {} + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + // adding identifier x + test("add-identifier-to-function-body", function() { + // function foo() { + // x + // } + + const sample_in = + ` + function foo(x: string) { + // empty + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + util.assert(testFunc.body !== undefined) + + let body_statements = [ + ...testFunc.body.statements, + ts.factory.createExpressionStatement(ts.factory.createIdentifier("x")) + ] + + testFunc = ts.factory.updateFunctionDeclaration( + testFunc, + undefined, + undefined, + testFunc.name, + undefined, + testFunc.parameters, + undefined, + ts.factory.updateBlock( + testFunc.body, + body_statements + ) + ) + util.assert(ts.isFunctionDeclaration(testFunc)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo(x: string) { + x + } + ` + ) + }) + + // adding __memo_scope.recache + test("add-property-access-expression-to-function-body", function() { + // function foo() { + // __memo_scope.recache + // } + + const sample_in = + ` + function foo() { + // empty + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + util.assert(testFunc.body !== undefined) + + let body_statements = [ + ...testFunc.body.statements, + ts.factory.createExpressionStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("recache") + ) + ) + ] + + testFunc = ts.factory.updateFunctionDeclaration( + testFunc, + undefined, + undefined, + testFunc.name, + undefined, + testFunc.parameters, + undefined, + ts.factory.updateBlock( + testFunc.body, + body_statements + ) + ) + util.assert(ts.isFunctionDeclaration(testFunc)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo() { + __memo_scope.recache; + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + // body memo rewrite (adding return statement) + test("add-return-statement-to-function-body", function() { + // function foo() { + // return __memo_scope.recache() + // } + + const sample_in = + ` + function foo() { + // empty + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + util.assert(testFunc.body !== undefined) + + let body_statements = [ + ...testFunc.body.statements, + ts.factory.createReturnStatement( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("recache") + ), + undefined, + undefined + ) + ) + ] + + testFunc = ts.factory.updateFunctionDeclaration( + testFunc, + undefined, + undefined, + testFunc.name, + undefined, + testFunc.parameters, + undefined, + ts.factory.updateBlock( + testFunc.body, + body_statements + ) + ) + util.assert(ts.isFunctionDeclaration(testFunc)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo() { + return __memo_scope.recache(); + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + // body memo rewrite (adding if statement) + test("add-if-statement-to-function-body", function() { + // function foo() { + // if (__memo_scope.unchanged) + // return __memo_scope.cached + // } + + const sample_in = + ` + function foo() { + // empty + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + util.assert(testFunc.body !== undefined) + + let body_statements = [ + ts.factory.createIfStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("unchanged") + ), + ts.factory.createBlock([ + ts.factory.createReturnStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("cached") + ) + ) + ]), + undefined + ), + ...testFunc.body.statements + ] + + testFunc = ts.factory.updateFunctionDeclaration( + testFunc, + undefined, + undefined, + testFunc.name, + undefined, + testFunc.parameters, + undefined, + ts.factory.updateBlock( + testFunc.body, + body_statements + ) + ) + util.assert(ts.isFunctionDeclaration(testFunc)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo() { + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + // body memo rewrite + test("function-declaration-memo-rewrite", function() { + // function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type) { + // if (__memo_scope.unchanged) + // return __memo_scope.cached + // content(__memo_context, __memo_id + "key_id_main.ts") + // return __memo_scope.recache() + // } + + const sample_in = + ` + function foo() { + // empty + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + util.assert(testFunc.body !== undefined) + + let body_statements = [ + ts.factory.createIfStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("unchanged") + ), + ts.factory.createBlock([ + ts.factory.createReturnStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("cached") + ) + ) + ]), + undefined + ), + ts.factory.createExpressionStatement( + ts.factory.createCallExpression( + ts.factory.createIdentifier("content"), + undefined, + [ + ts.factory.createIdentifier("__memo_context"), + ts.factory.createBinaryExpression( + ts.factory.createIdentifier("__memo_id"), + ts.factory.createToken(ts.SyntaxKind.PlusToken), + ts.factory.createStringLiteral("key_id_main.ts") + ) + ] + )), + ts.factory.createReturnStatement( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("recache") + ), + undefined, + undefined + ) + ), + ...testFunc.body.statements + ] + + testFunc = util.addMemoParamsToFunctionDeclaration(testFunc) + util.assert(ts.isFunctionDeclaration(testFunc)) + util.assert(testFunc.body !== undefined) + + testFunc = ts.factory.updateFunctionDeclaration( + testFunc, + undefined, + undefined, + testFunc.name, + undefined, + testFunc.parameters, + undefined, + ts.factory.updateBlock( + testFunc.body, + body_statements + ) + ) + util.assert(ts.isFunctionDeclaration(testFunc)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type) { + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + content(__memo_context, ((__memo_id) + ("key_id_main.ts"))); + return __memo_scope.recache(); + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + test("return-lambda", function() { + const sample_in = + ` + function foo() {} + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + + testFunc = ts.factory.updateFunctionDeclaration( + testFunc, + undefined, + undefined, + ts.factory.createIdentifier("foo"), + undefined, + [ + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("x"), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + undefined + ) + ], + undefined, + ts.factory.createBlock( + [ + ts.factory.createReturnStatement( + ts.factory.createCallExpression( + ts.factory.createParenthesizedExpression( + ts.factory.createArrowFunction( + undefined, + undefined, + [ + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("val"), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + ts.factory.createIdentifier("x") + ) + ], + undefined, + ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), + ts.factory.createBlock( + [ + ts.factory.createExpressionStatement( + ts.factory.createIdentifier("val") + ) + ], + false + ) + ) + ), + undefined, + [] + ) + ) + ], + true + ) + ) + util.assert(ts.isFunctionDeclaration(testFunc)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo(x: string) { + return ((val: string = x) => { val })() + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/lambda-function/builder-lambda.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/lambda-function/builder-lambda.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fd8ffb5f9c7115c533a0fdc4473102f58fa97a3 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/lambda-function/builder-lambda.test.ts @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../../test-util" +import * as ts from "../../../../src/ts-api" + +suite.skip(util.basename(__filename), () => { + test("adding-lambda-param-to-signature", function() { + // _Foo((instance: string) => { + // // empty + // }, "label"); + + const sample_in = + ` + Foo("label") + + function Foo(text: string): void { + console.log(text) + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const newName = "_Foo" + const paramName = "instance" + + const firstStatement = sourceFile.statements[0] + util.assert(ts.isExpressionStatement(firstStatement)) + const node = firstStatement.expression + util.assert(ts.isCallExpression(node)) + + const instanceLambdaBody = ts.factory.createBlock([]) + const lambdaParams = [ + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier(paramName), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + undefined + ) + ] + + const lambda = ts.factory.createArrowFunction( + undefined, + undefined, + lambdaParams, + undefined, + undefined, + instanceLambdaBody + ) + + const result = ts.factory.updateCallExpression( + node, + ts.factory.createIdentifier(newName), + undefined, + [ + lambda, + ...node.arguments + ] + ) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + ts.factory.createExpressionStatement(result) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + _Foo(((instance: string) => {}), "label") + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) + + test("adding-body-to-lambda-param", function() { + // _Foo((instance: string) => { + // instance.bar().qux(); + // }, "label1", "label2"); + + const sample_in = + ` + Foo(instance.bar().qux(), "label1", "label2") + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const newName = "_Foo" + const paramName = "instance" + + const firstStatement = sourceFile.statements[0] + util.assert(ts.isExpressionStatement(firstStatement)) + + const node = firstStatement.expression + util.assert(ts.isCallExpression(node)) + + const instanceLambdaBody = ts.factory.createBlock([ + ts.factory.createExpressionStatement( + node.arguments[0] + ) + ]) + const lambdaParams = [ + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier(paramName), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + undefined + ) + ] + + const lambda = ts.factory.createArrowFunction( + undefined, + undefined, + lambdaParams, + undefined, + undefined, + instanceLambdaBody + ) + + const result = ts.factory.updateCallExpression( + node, + ts.factory.createIdentifier(newName), + undefined, + [ + lambda, + ...node.arguments.slice(1) + ] + ) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + ts.factory.createExpressionStatement(result) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + _Foo(((instance: string) => { + instance.bar().qux(); + }), "label1", "label2") + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/lambda-function/lambda-param-memoization.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/lambda-function/lambda-param-memoization.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2982ad6eaa21113e6345af17cd86d0977e908e49 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/functions/lambda-function/lambda-param-memoization.test.ts @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../../test-util" +import * as ts from "../../../../src/ts-api" + +suite.skip(util.basename(__filename), () => { + // full memo rewrite + test("memo-function-with-lambda-memo-param", function() { + // function foo( + // __memo_context: __memo_context_type, + // __memo_id: __memo_id_type, + // content: (__memo_context: __memo_context_type, __memo_id: __memo_id_type) => void + // ) { + // if (__memo_scope.unchanged) + // return __memo_scope.cached + // content(__memo_context, __memo_id + "key_id_main.ts") + // return __memo_scope.recache() + // } + + const sample_in = + ` + function foo( + content: () => void + ) { + content() + } + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(testFunc)) + + let body_statements = [ + ts.factory.createIfStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("unchanged") + ), + ts.factory.createBlock([ + ts.factory.createReturnStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("cached") + ) + ) + ]), + undefined + ), + ts.factory.createExpressionStatement( + ts.factory.createCallExpression( + ts.factory.createIdentifier("content"), + undefined, + [ + ts.factory.createIdentifier("__memo_context"), + ts.factory.createBinaryExpression( + ts.factory.createIdentifier("__memo_id"), + ts.factory.createToken(ts.SyntaxKind.PlusToken), + ts.factory.createStringLiteral("key_id_main.ts") + ) + ] + )), + ts.factory.createReturnStatement( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("recache") + ), + undefined, + undefined + ) + ) + ] + + testFunc = util.addMemoParamsToFunctionDeclaration(testFunc) + util.assert(ts.isFunctionDeclaration(testFunc)) + util.assert(testFunc.body !== undefined) + + const newLambdaParams = [ + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("__memo_context"), + undefined, + ts.factory.createETSTypeReferenceNode( + ts.factory.createIdentifier("__memo_context_type"), + undefined + ) + ), + ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("__memo_id"), + undefined, + ts.factory.createETSTypeReferenceNode( + ts.factory.createIdentifier("__memo_id_type"), + undefined + ), + ) + ] + + const newLambdaParam = ts.factory.createParameterDeclaration( + undefined, + undefined, + ts.factory.createIdentifier("content"), + undefined, + ts.factory.createFunctionTypeNode( + undefined, + newLambdaParams, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword) + ), + undefined + ) + + testFunc = ts.factory.updateFunctionDeclaration( + testFunc, + undefined, + undefined, + testFunc.name, + undefined, + [ + testFunc.parameters[0], + testFunc.parameters[1], + newLambdaParam + ], + undefined, + ts.factory.updateBlock( + testFunc.body, + body_statements + ) + ) + util.assert(ts.isFunctionDeclaration(testFunc)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, content: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) { + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + content(__memo_context, ((__memo_id) + ("key_id_main.ts"))); + return __memo_scope.recache(); + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED, + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/abc-gen.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/abc-gen.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a8411de1c3e965ef51d80ddcfc59605c7635b4c --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/abc-gen.test.ts @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as ts from "../../../src/ts-api" + +// tests for abc generation (now failing on CI) +suite.skip(util.basename(__filename), () => { + test("updating-expression-statement", function() { + const sample_in = + ` + function foo(lambda: (instance: string) => string): void { + console.log(lambda("ABC")) + } + + foo((instance: string) => { return instance }) + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const expressionStatement = sourceFile.statements[1] + util.assert(ts.isExpressionStatement(expressionStatement)) + + const newStatements = [ + sourceFile.statements[0], + ts.factory.updateExpressionStatement( + expressionStatement, + expressionStatement.expression + ) + ] + + ts.factory.updateSourceFile(sourceFile, newStatements) + + util.assertEqualsBinaryOutput('ABC', this) + }) + + test("updating-function-declaration", function() { + const sample_in = + ` + function foo(): void { + console.log("A") + return + } + + foo() + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const funcDecl = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(funcDecl)) + + const newStatements = [ + ts.factory.updateFunctionDeclaration( + funcDecl, + undefined, + undefined, + funcDecl.name, + undefined, + funcDecl.parameters, + undefined, + funcDecl.body, + ), + sourceFile.statements[1], + ] + + ts.factory.updateSourceFile(sourceFile, newStatements) + + util.assertEqualsBinaryOutput('A', this) + }) + + test("updating-lambda-call", function() { + const sample_in = + ` + function foo(builder: () => void) {} + foo(() => {}) + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + const exprStatement = sourceFile.statements[1] + util.assert(ts.isExpressionStatement(exprStatement)) + const callExpr = exprStatement.expression + util.assert(ts.isCallExpression(callExpr)) + + util.assert(ts.isArrowFunction(callExpr.arguments[0])) + const lambdaArg = + ts.factory.createArrowFunction( + undefined, + undefined, + [], + undefined, + undefined, + callExpr.arguments[0].body + ) + + util.assert(ts.isIdentifier(callExpr.expression)) + const newStatements = [ + sourceFile.statements[0], + ts.factory.updateExpressionStatement( + exprStatement, + ts.factory.updateCallExpression( + callExpr, + ts.factory.createIdentifier('foo'), + undefined, + [ + lambdaArg, + ] + ) + ) + ] + ts.factory.updateSourceFile(sourceFile, newStatements) + + util.assertEqualsBinaryOutput('', this) + }) + + test("changing-variable-annotation", function() { + const sample_in = + ` + class A {} + + let x: AB + + console.log("ok") + ` + + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const varDecl = sourceFile.statements[1] + util.assert(ts.isVariableStatement(varDecl)) + + const declList = varDecl.declarationList + util.assert(ts.isVariableDeclarationList(declList)) + + const x = declList.declarations[0] + util.assert(ts.isVariableDeclaration(x)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + sourceFile.statements[0], + ts.factory.updateVariableStatement( + varDecl, + undefined, + // declList + ts.factory.createVariableDeclarationList( + [ts.factory.createVariableDeclaration( + ts.factory.createIdentifier("x"), + undefined, + ts.factory.createETSTypeReferenceNode( + ts.factory.createIdentifier("A") + ), + undefined + )], + undefined + ) + ), + sourceFile.statements[2] + ] + ) + + util.assertEqualsBinaryOutput('ok', this) + }) + + test.skip("function-expression", function() { + const sample_in = + ` + const foo = function() { console.log("abc"); }; + foo(); + ` + + ts.factory.createSourceFile(sample_in) + util.assertEqualsBinaryOutput('abc', this) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/basic.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/basic.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f5a1a236a6ac581d1846d10fb330a240dec3523 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/basic.test.ts @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" + +suite.skip(util.basename(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + factory.createExpressionStatement( + factory.createIdentifier("abc") + ) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + abc + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) + + test("sample-2", function() { + const sample_in = + ` + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + factory.createFunctionDeclaration( + undefined, + undefined, + factory.createIdentifier("test"), + undefined, + [], + undefined, + factory.createBlock( + [], + true + ) + ) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function test() {} + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) + + test("sample-3", function() { + const sample_in = + ` + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + factory.createFunctionDeclaration( + undefined, + undefined, + factory.createIdentifier("test"), + undefined, + [ + factory.createParameterDeclaration( + undefined, + undefined, + factory.createIdentifier("x"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + undefined + ) + ], + factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + factory.createBlock( + [ + factory.createReturnStatement( + factory.createNumericLiteral(0) + ) + ], + true + ) + ) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function test(x: string): number { + return 0; + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) + + test("sample-4", function() { + const sample_in = + ` + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + factory.createFunctionDeclaration( + undefined, + undefined, + factory.createIdentifier("test"), + [ + factory.createTSTypeParameterDeclaration( + undefined, + factory.createIdentifier("T"), + factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + undefined + ) + ], + [ + factory.createParameterDeclaration( + undefined, + undefined, + factory.createIdentifier("x"), + undefined, + factory.createETSTypeReferenceNode( + factory.createIdentifier("T"), + undefined + ), + undefined + ) + ], + factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + factory.createBlock( + [ + factory.createReturnStatement( + factory.createStringLiteral("aaa") + ) + ], + true + ) + ) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function test(x: T): string { + return "aaa" + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/import.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/import.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ad99df8e991d61ae404ad457018048296e71c0b --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/general/import.test.ts @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as ts from "../../../src/ts-api" + +suite.skip(util.basename(__filename), () => { + // TODO: doesn't running now, but compiles (config gets only one file) + test("sample-1", function() { + const sample_in = + ` + import { TEST } from "./export" + console.log(TEST) + ` + + // util.getDefaultSetup(sample_in) + + // util.generateBinAndRun() + }) + + test("sample-2", function() { + const sample_in = + ` + import { power as F } from "std/math" + console.log(F(2, 10)) + ` + + // util.getDefaultSetup(sample_in) + + // arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_CHECKED) + + // const classDecl = arkts.nodeByPeer(util.getStatement(1)) + // util.assert(arkts.isClassDeclaration(classDecl)) + + // const method = classDecl.members[1] + // util.assert(arkts.isMethodDeclaration(method)) + + // const body = method.body! + // util.assert(arkts.isBlock(body)) + + // const exprStatement = body.statements[0] + // util.assert(arkts.isExpressionStatement(exprStatement)) + + // const callExpr = exprStatement.expression + // util.assert(arkts.isCallExpression(callExpr)) + + // const F = callExpr.arguments[0] + // util.assert(arkts.isCallExpression(F)) + + // const ident = F.expression + // util.assert(arkts.isIdentifier(ident)) + + // console.log(arkts.dumpJsonNode(ident)) + + // const decl = arkts.getDecl(ident) + // if (decl !== undefined) { + // console.log(arkts.dumpJsonNode(decl)) + // } else { + // console.log(decl) + // } + + // util.generateBinAndRun() + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/import-export/import.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/import-export/import.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..59763246b0ccc61717e0afbc5f2c4854d4ed124a --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/import-export/import.test.ts @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" + +// TODO: +suite.skip(util.basename(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + import { X } from "./variable" + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + // sourceFile = factory.updateSourceFile( + // sourceFile, + // [ + // factory.createImportDeclaration( + // undefined, + // factory.createImportClause( + // false, + // undefined, + // factory.createNamedImports( + // [ + // factory.createImportSpecifier( + // false, + // undefined, + // factory.createIdentifier("X") + // ) + // ] + // ) + // ), + // factory.createStringLiteral("./variable"), + // undefined + // ) + // ] + // ) + + // util.assertEqualsAfter( + // sourceFile, + // ` + // import { X } from "./variable" + // `, + // ts.ContextState.ES2PANDA_STATE_PARSED + // ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/keyword-super/in-constructor.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/keyword-super/in-constructor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..569ec3a012854782839929fe54d3a0b2cd415689 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/keyword-super/in-constructor.test.ts @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" + +// TODO: +suite.skip(util.basename(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + // sourceFile = factory.updateSourceFile( + // sourceFile, + // [ + // factory.createClassDeclaration( + // [factory.createToken(ts.SyntaxKind.AbstractKeyword)], + // factory.createIdentifier("A"), + // undefined, + // undefined, + // [factory.createConstructorDeclaration( + // undefined, + // [factory.createParameterDeclaration( + // undefined, + // undefined, + // factory.createIdentifier("x"), + // undefined, + // factory.createETSTypeReferenceNode( + // factory.createIdentifier("int"), + // undefined + // ), + // undefined + // )], + // factory.createBlock( + // [], + // false + // ) + // )] + // ), + // factory.createClassDeclaration( + // undefined, + // factory.createIdentifier("B"), + // undefined, + // [factory.createHeritageClause( + // ts.SyntaxKind.ExtendsKeyword, + // [factory.createExpressionWithTypeArguments( + // factory.createIdentifier("A"), + // undefined + // )] + // )], + // [factory.createConstructorDeclaration( + // undefined, + // [factory.createParameterDeclaration( + // undefined, + // undefined, + // factory.createIdentifier("x"), + // undefined, + // factory.createETSTypeReferenceNode( + // factory.createIdentifier("int"), + // undefined + // ), + // undefined + // )], + // factory.createBlock( + // [factory.createExpressionStatement(factory.createCallExpression( + // factory.createSuper(), + // undefined, + // [factory.createIdentifier("x")] + // ))], + // true + // ) + // )] + // ) + // ] + // ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + abstract class A { + constructor(x: int) {} + }; + + class B extends A { + constructor(x: int) { + super(x) + } + } + ` + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/variables/create-variable.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/variables/create-variable.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6de1aa33ea9821e84cb917afa3a218db2b6495c1 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/variables/create-variable.test.ts @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" + +suite.skip(util.basename(__filename), () => { + test("const-number", function() { + const sample_in = + ` + function f() {} + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const varDecl = factory.createVariableStatement( + undefined, + factory.createVariableDeclarationList( + [ + factory.createVariableDeclaration( + factory.createIdentifier("x"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + factory.createNumericLiteral(0) + ) + ], + ts.NodeFlags.Const + ) + ) + + const f = sourceFile.statements[0] + util.assert(ts.isFunctionDeclaration(f)) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + factory.updateFunctionDeclaration( + f, + f.modifiers, + undefined, + f.name, + f.typeParameters, + f.parameters, + f.type, + factory.createBlock([ + varDecl + ]) + ) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function f() { + const x: number = 0 + } + ` + ) + }) + + test("declaration-list", function() { + // const x: number = 0, y: string = "a", z = 0 + + const sample_in = `const x = 1` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const varStatement = sourceFile.statements[0] + util.assert(ts.isVariableStatement(varStatement)) + + sourceFile = ts.factory.updateSourceFile( + sourceFile, + [ + factory.updateVariableStatement( + varStatement, + [ + // TODO: not ok maybe (problem with ModifierFlags) + factory.createToken(ts.SyntaxKind.PublicKeyword), + factory.createToken(ts.SyntaxKind.StaticKeyword), + factory.createToken(ts.SyntaxKind.ConstKeyword), + ], + factory.createVariableDeclarationList( + [ + factory.createVariableDeclaration( + factory.createIdentifier("x"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + factory.createNumericLiteral(0) + ), + factory.createVariableDeclaration( + factory.createIdentifier("y"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + factory.createStringLiteral("a") + ), + factory.createVariableDeclaration( + factory.createIdentifier("z"), + undefined, + undefined, + factory.createNumericLiteral(0) + ) + ], + ts.NodeFlags.Const + ) + ) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + const x: number = 0, y: string = "a", z = 0 + ` + ) + }) + + test.skip("let-vars", function() { + const sample_in = + ` + const x = 0 + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + const varStatement = sourceFile.statements[0] + util.assert(ts.isVariableStatement(varStatement)) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + factory.updateVariableStatement( + varStatement, + [ + // TODO: not ok maybe (problem with ModifierFlags) + factory.createToken(ts.SyntaxKind.PublicKeyword), + factory.createToken(ts.SyntaxKind.StaticKeyword), + ], + factory.createVariableDeclarationList( + [ + factory.createVariableDeclaration( + factory.createIdentifier("x"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + factory.createNumericLiteral(0) + ), + factory.createVariableDeclaration( + factory.createIdentifier("y"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + factory.createStringLiteral("a") + ), + factory.createVariableDeclaration( + factory.createIdentifier("z"), + undefined, + undefined, + factory.createNumericLiteral(0) + ) + ], + ts.NodeFlags.Let + ) + ) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + let x: number = 0, y: string = "a", z = 0 + ` + ) + }) + + test("parenthesized-expression", function() { + const sample_in = + ` + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + sourceFile = factory.updateSourceFile( + sourceFile, + [ + factory.createVariableStatement( + [ + // TODO: not ok maybe (problem with ModifierFlags) + factory.createToken(ts.SyntaxKind.PublicKeyword), + factory.createToken(ts.SyntaxKind.StaticKeyword), + factory.createToken(ts.SyntaxKind.ConstKeyword), + ], + factory.createVariableDeclarationList( + [ + factory.createVariableDeclaration( + factory.createIdentifier("x"), + undefined, + factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + factory.createBinaryExpression( + factory.createParenthesizedExpression( + factory.createBinaryExpression( + factory.createNumericLiteral(0), + factory.createToken(ts.SyntaxKind.PlusToken), + factory.createNumericLiteral(0) + ) + ), + factory.createToken(ts.SyntaxKind.AsteriskToken), + factory.createNumericLiteral(0) + ) + ) + ], + ts.NodeFlags.Const + ) + ) + ] + ) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + const x: number = (0 + 0) * 0 + ` + ) + }) + + test.skip("question-mark", function() { + const sample_in = + ` + function foo(x?: number | undefined) { + console.log(x); + } + foo() + ` + + let sourceFile = factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) + + util.TS_TEST_ASSERTION( + sourceFile, + ` + function foo(x?: number | undefined) { + console.log(x); + } + foo() + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/analysis-visitor.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/analysis-visitor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..357d2204347ddb88855aa555e0007fe4927384cc --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/analysis-visitor.test.ts @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +// import * as ts from "../../../src/ts-api" +// import { AnalysisVisitor } from "../../../plugins/src/analysis-visitor" +// import { Tracer } from "../../../plugins/src/util" +// import { Rewrite } from "../../../plugins/src/transformation-context" +// +// suite(util.getSuiteTitle(__filename), () => { +// test("sample-1", function() { +// const sample_in = +// ` +// const _memo_x: string = "A" +// +// function _memo_foo() {} +// +// _memo_foo() +// ` +// +// let sourceFile = ts.factory.createSourceFile(sample_in) +// util.assert(ts.isSourceFile(sourceFile)) +// +// // ts.proceedToState(ts.ContextState.ES2PANDA_STATE_CHECKED) +// +// const options = {} +// +// const tracer = new Tracer(options) +// const rewrite = new Rewrite(sourceFile, options) +// +// const result = new AnalysisVisitor(tracer, rewrite).visitor(sourceFile) +// util.assert(ts.isSourceFile(result)) +// +// util.assert(rewrite.functionTable.size === 1) +// util.assert(rewrite.callTable.size === 1) +// util.assert(rewrite.variableTable.size === 1) +// }) +// }) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/builder-lambda-rewrite.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/builder-lambda-rewrite.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3dd4d4a519a77ed141376cabe56c8849a1ae9d77 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/builder-lambda-rewrite.test.ts @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +// import * as ts from "../../../src/ts-api" +// import { factory } from "../../../src/ts-api" +// import { BuilderLambdaTransformer } from "../../../plugins/src/builder-lambda-transformer" +// +// suite.skip(util.getSuiteTitle(__filename), () => { +// test("builder-lambda-transformer-sample-1", function() { +// // foo((instance: string) => { +// // return instance; +// // }, "label"); +// +// const sample_in = +// ` +// _BuilderLambdaCall_foo("label") +// ` +// +// let sourceFile = factory.createSourceFile(sample_in) +// util.assert(ts.isSourceFile(sourceFile)) +// +// const builderLambdaTransformer = new BuilderLambdaTransformer() +// +// const result = builderLambdaTransformer.visitor(sourceFile) +// util.assert(ts.isSourceFile(result)) +// +// util.TS_TEST_ASSERTION( +// result, +// ` +// foo(((instance: string) => { +// return instance; +// }), "label") +// `, +// ts.ContextState.ES2PANDA_STATE_PARSED, +// ) +// }) +// +// test("builder-lambda-transformer-sample-2", function() { +// // foo((instance: string) => { +// // return instance.bar().qux(); +// // }, "label1", "label2"); +// +// const sample_in = +// ` +// _BuilderLambdaCall_foo("label1", "label2").bar().qux() +// ` +// +// let sourceFile = factory.createSourceFile(sample_in) +// util.assert(ts.isSourceFile(sourceFile)) +// +// const builderLambdaTransformer = new BuilderLambdaTransformer() +// +// const result = builderLambdaTransformer.visitor(sourceFile) +// util.assert(ts.isSourceFile(result)) +// +// util.TS_TEST_ASSERTION( +// result, +// ` +// foo(((instance: string) => { +// return instance.bar().qux(); +// }), "label1", "label2") +// `, +// ts.ContextState.ES2PANDA_STATE_PARSED, +// ) +// }) +// +// // TODO: update nodes properly (now failing to generate bin) +// test("builder-lambda-transformer-sample-3", function() { +// // function Foo(builder: (instance: string) => string, arg1: string): void { +// // console.log(arg1 + builder("ABC")) +// // } +// // Foo((instance: string) => { +// // return instance.charAt(1) +// // }, "> second_char_of_ABC: ") +// +// const sample_in = +// ` +// function Foo(builder: (instance: string) => string, arg1: string): void { +// console.log(arg1 + builder("ABC")) +// } +// +// _BuilderLambdaCall_Foo("> second_char_of_ABC: ").charAt(1) +// ` +// +// let sourceFile = factory.createSourceFile(sample_in) +// util.assert(ts.isSourceFile(sourceFile)) +// +// const builderLambdaTransformer = new BuilderLambdaTransformer() +// +// const result = builderLambdaTransformer.visitor(sourceFile) +// util.assert(ts.isSourceFile(result)) +// +// util.TS_TEST_ASSERTION( +// result, +// ` +// function Foo(builder: ((instance: string)=> string), arg1: string): void { +// console.log(((arg1) + (builder("ABC")))); +// } +// +// Foo(((instance: string) => { +// return instance.charAt(1); +// }), "> second_char_of_ABC: ") +// `, +// ts.ContextState.ES2PANDA_STATE_PARSED, +// ) +// }) +// }) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/function-rewrite.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/function-rewrite.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..38f4b85da7666fcd1443ba9d2a147cc1afe66b4e --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/function-rewrite.test.ts @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +// import * as ts from "../../../src/ts-api" +// import global from "src/arkts-api/static/global" +// import { FunctionTransformer } from "../../../plugins/src/function-transformer" +// import { PrintVisitor } from "../../../plugins/src/print-visitor" +// +// suite.skip(util.getSuiteTitle(__filename), () => { +// test("function-transformer-sample-1", function() { +// const sample_in = +// ` +// const x: string = "A" +// +// function _REWRITE_foo() { +// console.log("FUNC CALLED: " + x) +// } +// +// _REWRITE_foo() +// ` +// +// const sourceFile = ts.factory.createSourceFile(sample_in, ts.ContextState.ES2PANDA_STATE_CHECKED) +// util.assert(ts.isSourceFile(sourceFile)) +// +// // util.nativeModule._VarBinderSetContext(global.context) +// // util.nativeModule._VarBinderSetProgram(global.context) +// // util.nativeModule._VarBinderSetGenStdLib(global.context, false) +// // util.nativeModule._VarBinderInitTopScope(global.context) +// // util.nativeModule._VarBinderIdentifierAnalysis(global.context) +// +// const result = (new FunctionTransformer()).visitor(sourceFile) +// util.assert(ts.isSourceFile(result)) +// +// util.TS_TEST_ASSERTION( +// sourceFile, +// ` +// const x: string = "A" +// +// function foo(x: string) { +// console.log("FUNC CALLED: " + x) +// } +// +// foo("SAMPLE") +// `, +// ts.ContextState.ES2PANDA_STATE_CHECKED, +// ) +// +// // TODO: +// util.nativeModule._VarBinderInitTopScope(global.context) +// util.nativeModule._VarBinderIdentifierAnalysis(global.context) +// ts.proceedToState(ts.ContextState.ES2PANDA_STATE_BIN_GENERATED) +// }) +// }) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/memo-rewrite.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/memo-rewrite.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2aa9d54d53f53f74a95b73e8b93e854371e7a217 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/memo-rewrite.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { MemoTransformer } from "../../../plugins/src/memo-transformer" + +suite.skip(util.basename(__filename), () => { + test("memo-transformer-sample-1", function() { + const sample_in = + ` + function _MEMO_foo() { + console.log("MEMO FUNC CALLED!") + } + + _MEMO_foo() + ` + + // util.getDefaultSetup(sample_in) + + // arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_CHECKED) + + // const sourceFile = arkts.makeView(util.AstProvider.provideAst()) + + // const memoTransformer = new MemoTransformer() + // const transformed = memoTransformer.visitor(sourceFile) + + // console.log(arkts.dumpSrcNode(sourceFile)) + }) +}) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/print-visitor.test.ts b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/print-visitor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..736a67e53db03887c81855e15bea58c92bd16f96 --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/ts-api/visitors-and-transformers/print-visitor.test.ts @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 ts from "../../../src/ts-api" +// import * as util from "../../test-util" +// import { PrintVisitor } from "../../../plugins/src/print-visitor" +// +// suite.skip(util.getSuiteTitle(__filename), () => { +// test("sample-1", function() { +// const source = +// ` +// class Base { +// public a: int = 1; +// public method() { +// this.a = 2; +// } +// } +// class Derived extends Base {} +// function foo() { +// } +// function goo() { +// } +// function main(): void { +// let derived: Base = new Derived(); +// derived.method(); +// } +// ` +// const expected = +// ` +// SourceFile (mods: []) +// ClassDeclaration (mods: [1,4]) +// Identifier (mods: []) +// PropertyDeclaration (mods: [4]) +// MethodDeclaration (mods: [4]) +// Identifier (mods: []) +// Block (mods: []) +// ExpressionStatement (mods: []) +// AssignmentExpression (mods: []) +// MethodDeclaration (mods: []) +// Identifier (mods: []) +// Block (mods: []) +// ClassDeclaration (mods: [1,4]) +// Identifier (mods: []) +// MethodDeclaration (mods: []) +// Identifier (mods: []) +// Block (mods: []) +// FunctionDeclaration (mods: [1,4]) +// Identifier (mods: []) +// Block (mods: []) +// FunctionDeclaration (mods: [1,4]) +// Identifier (mods: []) +// Block (mods: []) +// FunctionDeclaration (mods: [1,4]) +// Identifier (mods: []) +// ETSPrimitiveType (mods: []) +// Block (mods: []) +// VariableStatement (mods: []) +// VariableDeclarationList (mods: []) +// VariableDeclaration (mods: []) +// ExpressionStatement (mods: []) +// CallExpression (mods: []) +// PropertyAccessExpression (mods: []) +// Identifier (mods: []) +// Identifier (mods: []) +// ` +// let sourceFile = ts.factory.createSourceFile(source) +// const output = (new PrintVisitor()).astToString(sourceFile) +// +// util.assert.equal(util.alignText(output), util.alignText(expected)) +// }) +// }) diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/tsconfig.json b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..b66a126a9af084f18e03fae9afd97279dcdb50cc --- /dev/null +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/test/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "@koalaui/build-common/tsconfig.json", + "compilerOptions": { + "rootDir": "../", + "baseUrl": "../", + "outDir": "build/test", + "module": "CommonJS" + }, + "include": [ + "../src/**/*.ts", + "../test/**/*.ts", + "../examples/**/*.ts" + ], + "exclude": [ + "./ts-api/**/*" + ] +} diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/tsconfig.json b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/tsconfig.json index 40575c88c1de110c80a91c586c0c6252d33fbc0c..baa252e2361b92a1b9fcd3e31be0f6d29d9db982 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/tsconfig.json +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "build", "baseUrl": ".", "rootDir": "./src", - "module": "esnext" + "module": "esnext", + "tsBuildInfoFile": "./build/tsconfig.tsbuildinfo" }, "include": [ "./src/**/*.ts" diff --git a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/package.json b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/package.json index 2731c1bb2bd19a0a54da657edf439a014826848e..ef3fcdbcb79292a0609a240b2eeb2bdbbc3e7666 100644 --- a/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/package.json +++ b/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/package.json @@ -35,9 +35,9 @@ "commander": "^13.1.0" }, "scripts": { - "clean:all": "npm run clean --prefix libarkts && npm run clean:plugins --prefix libarkts && npm run clean --prefix memo-plugin && npm run runtime:clean --prefix memo-plugin && npm run clean --prefix memo-plugin/demo && npm run clean --prefix ../arkoala-arkts/arkui && npm run clean --prefix ../arkoala-arkts/trivial/user", + "clean:all": "npm run clean --prefix libarkts && npm run clean:plugins --prefix libarkts && npm run clean --prefix memo-plugin && npm run runtime:clean --prefix memo-plugin && npm run clean --prefix memo-plugin/demo", "build:all": "npm run compile --prefix libarkts && npm run compile:plugins --prefix libarkts && npm run compile --prefix memo-plugin && npm run runtime:prepare --prefix memo-plugin && npm run compile --prefix ui-plugins", - "test:all": "npm run build:arkui:pure-ets --prefix ../arkoala-arkts/arkui && npm run run --prefix libarkts && npm run test --prefix libarkts && npm run demo:run --prefix memo-plugin && npm run test:all --prefix memo-plugin && npm run run:user:pure-ets --prefix ../arkoala-arkts/trivial/user", + "test:all": "npm run build:arkui:pure-ets --prefix ../arkoala-arkts/arkui && npm run run --prefix libarkts && npm run test --prefix libarkts && npm run demo:run --prefix memo-plugin && npm run test:all --prefix memo-plugin", "all": "npm run clean:all && npm run build:all && npm run test:all" } }