From 3fe2f24f629bb3104e0ec37f20ef9a7cbae415ae Mon Sep 17 00:00:00 2001 From: Victor Chernishev Date: Fri, 22 Nov 2024 15:22:49 +0000 Subject: [PATCH] rebased to new panda plugin-api (from master) support all old tests and types trying to add CI refactoring (ts types standartization) refactoring (remove utilites from factory) CI fix and (rebasing on new api fixes) and add tests file structure moved node_modules dependencies from libarkts to arkoala-arkts + changed paths and scripts + improved CI renamed enums in src/api/static/enums.ts changes in package.json's CI change (install node modules (arkoala-arkts)) add dump method for arkts nodes in ts (using in tests for comparison) CI fix (reduced artifact files amount) add NodeFlags and add translations of flags (removed from global) move method throwError from global to utilities fix CI (removed job - install node modules (arkoala-arkts/libarkts)) add let support to VariableDeclaration and fixed some bugs add proper update for Program in arkts CI fix (changed package.json's and paths for panda sdk) new create in libarkts for ExpressionStatement new dump in libarkts (add dump scriptFunctionFlags, now tests failing) new create methods in arkts and ts updates rewrite first steps to compile and execute src/index.ts from demo_playground add new tests test commit add ETSUndefinedType, add UndefinedLiteral, enums rename _GetKind replaced with provided _AstNodeTypesConst fix bug with ProceedToState error message, add tool for issue generation add support some scriptFunctionFlags for current tests, add superExpression delete node.h from native refactoring (separated playground from native, .meson files rewrite, some minor changes) add test for parenthesized expression, add test for variable decl and test lambda function return delete native/subprojects move nativePtrDecoder to utilities finally something working with imports separate testing for arkts and ts api, partly add import syntax support for ts and arkts api's refactoring (separating ts-api and arkts-api) rewriting and calling imported functions and variables refactoring add more tests for arkts api refactoring (magic numbers in new tests replaced with enum values) delete tests duplicates, changed webpack configs beginning of works with new arkts plugin-api, fixed .gitignore issue (some test files were ignored) wip/ npm fails Signed-off-by: naumovdmitrii --- .gitignore | 1 + .gitlab-ci.yml | 3 +- arkoala-arkts/libarkts/.gitignore | 17 +- arkoala-arkts/libarkts/.gitlab-ci.yml | 21 +- arkoala-arkts/libarkts/.mocha.json | 2 +- arkoala-arkts/libarkts/README.md | 2 +- arkoala-arkts/libarkts/arktsconfig.json | 4 +- arkoala-arkts/libarkts/compatible/.gitignore | 1 + .../libarkts/compatible/arkts-tsconfig.json | 38 +- .../compatible/src/AbstractVisitor.ts | 2 +- .../compatible/src/analysis-visitor.ts | 19 +- .../src/builder-lambda-transformer.ts | 2 +- .../compatible/src/example-transformer.ts | 33 +- .../compatible/src/function-transformer.ts | 16 +- .../compatible/src/memo-transformer.ts | 109 +- .../libarkts/compatible/src/print-visitor.ts | 56 +- .../compatible/src/transformation-context.ts | 15 +- arkoala-arkts/libarkts/compatible/src/util.ts | 49 +- .../compatible/typescript-tsconfig.json | 18 - .../compatible/typescript.webpack.config.js | 38 - ...ts.webpack.config.js => webpack.config.js} | 82 +- arkoala-arkts/libarkts/es2panda-tsconfig.json | 7 +- arkoala-arkts/libarkts/input/f.sts | 3 + arkoala-arkts/libarkts/input/tsconfig.json | 13 - arkoala-arkts/libarkts/input/variable.sts | 1 + arkoala-arkts/libarkts/native/.gitignore | 4 +- arkoala-arkts/libarkts/native/meson.build | 109 +- .../libarkts/native/meson_options.txt | 8 + .../libarkts/native/src/es2panda_lib.cc | 563 +++++------ arkoala-arkts/libarkts/native/src/node.h | 123 --- .../native/subprojects/node/meson.build | 30 - .../native/subprojects/node/meson_options.txt | 6 - arkoala-arkts/libarkts/package.json | 49 +- arkoala-arkts/libarkts/playground/meson.build | 31 + .../libarkts/playground/meson_options.txt | 4 + .../{native => playground}/src/playground.cc | 19 +- arkoala-arkts/libarkts/src/NativeModule.ts | 197 ---- .../libarkts/src/api/factory/utilities.ts | 50 - .../src/api/layers/arkts/utilities.ts | 157 --- .../libarkts/src/api/static/global.ts | 148 --- .../src/arkts-api/factory/nodeFactory.ts | 54 + .../src/{api/layers/ts => arkts-api}/index.ts | 6 +- .../src/{api => arkts-api}/static/enums.ts | 321 ++++-- .../libarkts/src/arkts-api/static/global.ts | 46 + .../{api/layers/arkts => arkts-api}/types.ts | 935 +++++++++++++----- .../utilities/nativePtrDecoder.ts} | 2 +- .../src/arkts-api/utilities/private.ts | 186 ++++ .../utilities/public.ts} | 89 +- arkoala-arkts/libarkts/src/es2panda.ts | 52 +- arkoala-arkts/libarkts/src/nativeModule.ts | 202 ++++ .../{api => ts-api}/factory/nodeFactory.ts | 668 +++++++++---- .../src/{api => ts-api}/factory/nodeTests.ts | 66 +- .../libarkts/src/{api => ts-api}/index.ts | 19 +- .../arkts/index.ts => ts-api/static/enums.ts} | 5 +- .../src/{api/layers/ts => ts-api}/types.ts | 554 ++++++----- .../utilities/private.ts} | 240 +++-- .../libarkts/src/ts-api/utilities/public.ts | 66 ++ .../src/{api => ts-api}/visitor/visitor.ts | 37 +- arkoala-arkts/libarkts/src/utils.ts | 22 + .../expressions/call-expression.test.ts | 53 + .../test/arkts-api/functions/create.test.ts | 212 ++++ .../test/arkts-api/general/basic.test.ts | 33 + .../arkts-api/import-export/import.test.ts | 209 ++++ .../test/es2panda/function-rewrite.test.ts | 45 - .../es2panda/literal-declarations.test.ts | 121 --- .../es2panda/simple-transformations.test.ts | 54 - arkoala-arkts/libarkts/test/test-util.ts | 126 +-- .../ts-api/classes/heritage/extends.test.ts | 59 ++ .../libarkts/test/ts-api/cross/cross.test.ts | 42 + .../ts-api/demo-playground/classes.test.ts | 40 + .../test/ts-api/demo-playground/main.sts | 75 ++ .../demo-playground/memo-rewrites.test.ts | 45 + .../create-function-declaration.test.ts | 33 +- .../update-function-declaration.test.ts | 105 +- .../lambda-function/builder-lambda.test.ts} | 115 +-- .../lambda-param-memoization.test.ts | 6 +- .../general}/abc-gen.test.ts | 66 +- .../general}/basic.test.ts | 14 +- .../general}/import.test.ts | 4 +- .../test/ts-api/import-export/import.test.ts | 48 + .../keyword-super/in-constructor.test.ts | 94 ++ .../ts-api/variables/create-variable.test.ts | 249 +++++ .../analysis-visitor.test.ts | 23 +- .../builder-lambda-rewrite.test.ts | 105 ++ .../function-rewrite.test.ts | 51 + .../memo-rewrite.test.ts | 8 +- .../print-visitor.test.ts | 6 +- arkoala-arkts/libarkts/test/tsconfig.json | 5 - .../utilities.ts => tools/issue_gen.mjs} | 72 +- ...da.webpack.config.js => webpack.config.js} | 8 +- arkoala-arkts/package.json | 13 +- interop/src/cpp/dynamic-loader.h | 7 +- 92 files changed, 4842 insertions(+), 2924 deletions(-) create mode 100644 arkoala-arkts/libarkts/compatible/.gitignore delete mode 100644 arkoala-arkts/libarkts/compatible/typescript-tsconfig.json delete mode 100644 arkoala-arkts/libarkts/compatible/typescript.webpack.config.js rename arkoala-arkts/libarkts/compatible/{arkts.webpack.config.js => webpack.config.js} (63%) create mode 100644 arkoala-arkts/libarkts/input/f.sts delete mode 100644 arkoala-arkts/libarkts/input/tsconfig.json create mode 100644 arkoala-arkts/libarkts/input/variable.sts delete mode 100644 arkoala-arkts/libarkts/native/src/node.h delete mode 100644 arkoala-arkts/libarkts/native/subprojects/node/meson.build delete mode 100644 arkoala-arkts/libarkts/native/subprojects/node/meson_options.txt create mode 100644 arkoala-arkts/libarkts/playground/meson.build create mode 100644 arkoala-arkts/libarkts/playground/meson_options.txt rename arkoala-arkts/libarkts/{native => playground}/src/playground.cc (90%) delete mode 100644 arkoala-arkts/libarkts/src/NativeModule.ts delete mode 100644 arkoala-arkts/libarkts/src/api/factory/utilities.ts delete mode 100644 arkoala-arkts/libarkts/src/api/layers/arkts/utilities.ts delete mode 100644 arkoala-arkts/libarkts/src/api/static/global.ts create mode 100644 arkoala-arkts/libarkts/src/arkts-api/factory/nodeFactory.ts rename arkoala-arkts/libarkts/src/{api/layers/ts => arkts-api}/index.ts (78%) rename arkoala-arkts/libarkts/src/{api => arkts-api}/static/enums.ts (65%) create mode 100644 arkoala-arkts/libarkts/src/arkts-api/static/global.ts rename arkoala-arkts/libarkts/src/{api/layers/arkts => arkts-api}/types.ts (41%) rename arkoala-arkts/libarkts/src/{node/Platform.ts => arkts-api/utilities/nativePtrDecoder.ts} (95%) create mode 100644 arkoala-arkts/libarkts/src/arkts-api/utilities/private.ts rename arkoala-arkts/libarkts/src/{api/utilities/utilitiesPublic.ts => arkts-api/utilities/public.ts} (42%) create mode 100644 arkoala-arkts/libarkts/src/nativeModule.ts rename arkoala-arkts/libarkts/src/{api => ts-api}/factory/nodeFactory.ts (65%) rename arkoala-arkts/libarkts/src/{api => ts-api}/factory/nodeTests.ts (61%) rename arkoala-arkts/libarkts/src/{api => ts-api}/index.ts (67%) rename arkoala-arkts/libarkts/src/{api/layers/arkts/index.ts => ts-api/static/enums.ts} (81%) rename arkoala-arkts/libarkts/src/{api/layers/ts => ts-api}/types.ts (65%) rename arkoala-arkts/libarkts/src/{api/layers/ts/utilities.ts => ts-api/utilities/private.ts} (36%) create mode 100644 arkoala-arkts/libarkts/src/ts-api/utilities/public.ts rename arkoala-arkts/libarkts/src/{api => ts-api}/visitor/visitor.ts (84%) create mode 100644 arkoala-arkts/libarkts/src/utils.ts create mode 100644 arkoala-arkts/libarkts/test/arkts-api/expressions/call-expression.test.ts create mode 100644 arkoala-arkts/libarkts/test/arkts-api/functions/create.test.ts create mode 100644 arkoala-arkts/libarkts/test/arkts-api/general/basic.test.ts create mode 100644 arkoala-arkts/libarkts/test/arkts-api/import-export/import.test.ts delete mode 100644 arkoala-arkts/libarkts/test/es2panda/function-rewrite.test.ts delete mode 100644 arkoala-arkts/libarkts/test/es2panda/literal-declarations.test.ts delete mode 100644 arkoala-arkts/libarkts/test/es2panda/simple-transformations.test.ts create mode 100644 arkoala-arkts/libarkts/test/ts-api/classes/heritage/extends.test.ts create mode 100644 arkoala-arkts/libarkts/test/ts-api/cross/cross.test.ts create mode 100644 arkoala-arkts/libarkts/test/ts-api/demo-playground/classes.test.ts create mode 100644 arkoala-arkts/libarkts/test/ts-api/demo-playground/main.sts create mode 100644 arkoala-arkts/libarkts/test/ts-api/demo-playground/memo-rewrites.test.ts rename arkoala-arkts/libarkts/test/{es2panda => ts-api/functions/function-declaration}/create-function-declaration.test.ts (94%) rename arkoala-arkts/libarkts/test/{es2panda => ts-api/functions/function-declaration}/update-function-declaration.test.ts (78%) rename arkoala-arkts/libarkts/test/{es2panda/builder-lambda-rewrite.test.ts => ts-api/functions/lambda-function/builder-lambda.test.ts} (52%) rename arkoala-arkts/libarkts/test/{es2panda => ts-api/functions/lambda-function}/lambda-param-memoization.test.ts (97%) rename arkoala-arkts/libarkts/test/{es2panda => ts-api/general}/abc-gen.test.ts (62%) rename arkoala-arkts/libarkts/test/{es2panda => ts-api/general}/basic.test.ts (95%) rename arkoala-arkts/libarkts/test/{es2panda => ts-api/general}/import.test.ts (95%) create mode 100644 arkoala-arkts/libarkts/test/ts-api/import-export/import.test.ts create mode 100644 arkoala-arkts/libarkts/test/ts-api/keyword-super/in-constructor.test.ts create mode 100644 arkoala-arkts/libarkts/test/ts-api/variables/create-variable.test.ts rename arkoala-arkts/libarkts/test/{es2panda => ts-api/visitors-and-transformers}/analysis-visitor.test.ts (46%) create mode 100644 arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/builder-lambda-rewrite.test.ts create mode 100644 arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/function-rewrite.test.ts rename arkoala-arkts/libarkts/test/{es2panda => ts-api/visitors-and-transformers}/memo-rewrite.test.ts (80%) rename arkoala-arkts/libarkts/test/{es2panda => ts-api/visitors-and-transformers}/print-visitor.test.ts (93%) rename arkoala-arkts/libarkts/{src/api/utilities/utilities.ts => tools/issue_gen.mjs} (47%) rename arkoala-arkts/libarkts/{es2panda.webpack.config.js => webpack.config.js} (80%) diff --git a/.gitignore b/.gitignore index 3df284284..963497a80 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ dist arkoala/tools/peer-generator/arkoala **/package-lock.json .vscode +**.code-workspace .idea **/target **/cjpm.lock diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 01902ea52..4901f0f6e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,7 +4,6 @@ stages: - install-deps - prebuild - build-compiler - - build-plugin-api - build - test - idlize @@ -27,4 +26,6 @@ include: - arkoala/ets-plugin/.gitlab-ci.yml - arkoala/tools/peer-generator/.gitlab-ci.yml - arkoala-arkts/.gitlab-ci.yml + - arkoala-arkts/user/.gitlab-ci.yml + - arkoala-arkts/libarkts/.gitlab-ci.yml - interop/.gitlab-ci.yml diff --git a/arkoala-arkts/libarkts/.gitignore b/arkoala-arkts/libarkts/.gitignore index d37d63bfd..4e8da0800 100644 --- a/arkoala-arkts/libarkts/.gitignore +++ b/arkoala-arkts/libarkts/.gitignore @@ -1,8 +1,9 @@ -prebuilt -build* -native/build-* -native/*.ini -lib -!test/es2panda/* -!test/golden/* -!compatible/src/* +./prebuilt +./build* +./native/build-* +./native/*.ini +./generated/** +**.abc + +!test/es2panda/** +!compatible/src/** diff --git a/arkoala-arkts/libarkts/.gitlab-ci.yml b/arkoala-arkts/libarkts/.gitlab-ci.yml index baadfeb5d..0bafba90a 100644 --- a/arkoala-arkts/libarkts/.gitlab-ci.yml +++ b/arkoala-arkts/libarkts/.gitlab-ci.yml @@ -19,23 +19,32 @@ build plugin-api: - !reference [.setup, script] - cd arkoala-arkts/libarkts script: - - npm i && npm run compile + - npm i + - npm run compile artifacts: - expire_in: 2 days + expire_in: 1 days paths: - - arkoala-arkts/libarkts/compatible/build - - arkoala-arkts/libarkts/compatible/build_arkts - arkoala-arkts/libarkts/native/build_es2panda + - arkoala-arkts/libarkts/node_modules + needs: + - install node modules (arkoala) + - install node modules (arkoala-arkts) + - install node modules (incremental) + - install node modules (interop) test plugin-api: stage: test - allow_failure: true interruptible: true extends: .linux-vm-shell-task before_script: - !reference [.setup, script] - cd arkoala-arkts/libarkts script: - - npm i && npm run test + - npm run test + - npm run test:all needs: + - install node modules (arkoala) + - install node modules (arkoala-arkts) + - install node modules (incremental) + - install node modules (interop) - build plugin-api diff --git a/arkoala-arkts/libarkts/.mocha.json b/arkoala-arkts/libarkts/.mocha.json index 0068e6466..faa829cc4 100644 --- a/arkoala-arkts/libarkts/.mocha.json +++ b/arkoala-arkts/libarkts/.mocha.json @@ -1,6 +1,6 @@ { "ui": "tdd", - "spec": "./test/es2panda/**/*.test.ts", + "spec": "./test/**/*.test.ts", "extension": ["ts"], "require": ["../../incremental/test-utils/scripts/register"], "timeout": 10000 diff --git a/arkoala-arkts/libarkts/README.md b/arkoala-arkts/libarkts/README.md index d37da203e..6c874ff34 100644 --- a/arkoala-arkts/libarkts/README.md +++ b/arkoala-arkts/libarkts/README.md @@ -33,4 +33,4 @@ npm run run node build/api/es2panda.js --help ``` -Runs __ArkTS__ compiler for sources contained in compilable, invoking plugins specified in __arktsconfig.json__ +Runs __ArkTS__ compiler for __./input/main.sts__ invoking plugins specified in __arktsconfig.json__ diff --git a/arkoala-arkts/libarkts/arktsconfig.json b/arkoala-arkts/libarkts/arktsconfig.json index 45fa27795..b74b92a0e 100644 --- a/arkoala-arkts/libarkts/arktsconfig.json +++ b/arkoala-arkts/libarkts/arktsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "baseUrl": "./node_modules/@koalaui/plugin-api-panda-sdk/@panda/sdk", + "baseUrl": "node_modules/@panda/sdk", "paths": { "std": [ "./ets/stdlib/std" @@ -11,7 +11,7 @@ }, "plugins": [ { - "transform": "./compatible/build_arkts/example-transformer.js" + "transform": "./compatible/build/arkts/compatible/src/example-transformer.js" } ] } diff --git a/arkoala-arkts/libarkts/compatible/.gitignore b/arkoala-arkts/libarkts/compatible/.gitignore new file mode 100644 index 000000000..4de766de8 --- /dev/null +++ b/arkoala-arkts/libarkts/compatible/.gitignore @@ -0,0 +1 @@ +./build* diff --git a/arkoala-arkts/libarkts/compatible/arkts-tsconfig.json b/arkoala-arkts/libarkts/compatible/arkts-tsconfig.json index d448e43e4..97ccfcb4b 100644 --- a/arkoala-arkts/libarkts/compatible/arkts-tsconfig.json +++ b/arkoala-arkts/libarkts/compatible/arkts-tsconfig.json @@ -1,18 +1,20 @@ -{ - "extends": "@koalaui/build-common/tsconfig.json", - "compilerOptions": { - "rootDir": "../", - "baseUrl": "../", - "outDir": "build/arkts", - "paths": { - "api": [ - "src/arkts/index.ts" - ] - } - }, - "include": [ - "../src/**/*.ts", - "../test/**/*.ts", - "../compatible/**/*.ts" - ] -} +{ + "extends": "@koalaui/build-common/tsconfig.json", + "compilerOptions": { + "rootDir": "..", + "baseUrl": ".", + "outDir": "./build/arkts", + "paths": { + "api": [ + "src/arkts/index.ts" + ] + }, + "module": "CommonJS" + }, + "include": [ + "./src/**/*.ts", + ], + "exclude": [ + "../src/es2panda.ts" + ] +} diff --git a/arkoala-arkts/libarkts/compatible/src/AbstractVisitor.ts b/arkoala-arkts/libarkts/compatible/src/AbstractVisitor.ts index 0fdac256a..27c84097b 100644 --- a/arkoala-arkts/libarkts/compatible/src/AbstractVisitor.ts +++ b/arkoala-arkts/libarkts/compatible/src/AbstractVisitor.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import * as ts from "../../src/api" +import * as ts from "@koalaui/libarkts" export abstract class AbstractVisitor { constructor( diff --git a/arkoala-arkts/libarkts/compatible/src/analysis-visitor.ts b/arkoala-arkts/libarkts/compatible/src/analysis-visitor.ts index f7c1f48a3..7d8b92b1a 100644 --- a/arkoala-arkts/libarkts/compatible/src/analysis-visitor.ts +++ b/arkoala-arkts/libarkts/compatible/src/analysis-visitor.ts @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* -import * as ts from "../../src/api" + +import * as ts from "@koalaui/libarkts" import { AbstractVisitor } from "./AbstractVisitor"; import { Rewrite } from './transformation-context'; @@ -32,7 +32,6 @@ import { // isMemoEntry, // skipParenthesizedExpression, } from "./util" -// import { ImportExport } from './import-export'; function parseComment(comment: string): FunctionKind { let kind = FunctionKind.REGULAR @@ -77,7 +76,7 @@ export class AnalysisVisitor extends AbstractVisitor { return FunctionKind.REGULAR } if (!ts.isIdentifier(node)) { - ts.throwError('node expected to be Identifier') + throw new Error('node expected to be Identifier') } const kind = parseComment(node.text) this.traceAnnotation(traceAnnotation, kind, node) @@ -231,14 +230,11 @@ export class AnalysisVisitor extends AbstractVisitor { this.processFunctionExpression(node) } else if (ts.isParameter(node)) { this.processParameter(node) - } - // else if (arkts.isVariableDeclaration(node)) { - // this.processVariableDeclaration(node) - // } - else if (ts.isVariableDeclarationList(node)) { + } else if (ts.isVariableDeclaration(node)) { + this.processVariableDeclaration(node) + } else if (ts.isVariableDeclarationList(node)) { this.processVariableDeclarationList(node) - } - else if (ts.isPropertyDeclaration(node)) { + } else if (ts.isPropertyDeclaration(node)) { this.processPropertyDeclaration(node) } else if (ts.isPropertySignature(node)) { this.processPropertySignature(node) @@ -255,4 +251,3 @@ export class AnalysisVisitor extends AbstractVisitor { return this.visitEachChild(node) } } -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/compatible/src/builder-lambda-transformer.ts b/arkoala-arkts/libarkts/compatible/src/builder-lambda-transformer.ts index 9aaac429c..0f547470c 100644 --- a/arkoala-arkts/libarkts/compatible/src/builder-lambda-transformer.ts +++ b/arkoala-arkts/libarkts/compatible/src/builder-lambda-transformer.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import * as ts from "../../src/api" +import * as ts from "@koalaui/libarkts" import { AbstractVisitor } from "./AbstractVisitor"; export class BuilderLambdaTransformer extends AbstractVisitor { diff --git a/arkoala-arkts/libarkts/compatible/src/example-transformer.ts b/arkoala-arkts/libarkts/compatible/src/example-transformer.ts index 16984619c..91a669e24 100644 --- a/arkoala-arkts/libarkts/compatible/src/example-transformer.ts +++ b/arkoala-arkts/libarkts/compatible/src/example-transformer.ts @@ -1,17 +1,16 @@ -import * as ts from "../../src/api" -import { BuilderLambdaTransformer } from "./builder-lambda-transformer" - -export interface TransformerOptions { - trace?: boolean, -} - -// TODO: remove question marks -export default function exampleTransformer(program?: ts.Program, userPluginOptions?: TransformerOptions) { - return (ctx?: ts.TransformationContext) => { - return (node: ts.SourceFile) => { - const builderLambdaTransformer = (ctx !== undefined) ? new BuilderLambdaTransformer(ctx) : new BuilderLambdaTransformer() - const transformed = builderLambdaTransformer.visitor(node) - return transformed - } - } -} +import * as ts from "@koalaui/libarkts" +import { BuilderLambdaTransformer } from "./builder-lambda-transformer" + +export interface TransformerOptions { + trace?: boolean, +} + +export default function exampleTransformer(program?: ts.Program, userPluginOptions?: TransformerOptions) { + return (ctx?: ts.TransformationContext) => { + return (node: ts.SourceFile) => { + const builderLambdaTransformer = (ctx !== undefined) ? new BuilderLambdaTransformer(ctx) : new BuilderLambdaTransformer() + const transformed = builderLambdaTransformer.visitor(node) + return transformed + } + } +} diff --git a/arkoala-arkts/libarkts/compatible/src/function-transformer.ts b/arkoala-arkts/libarkts/compatible/src/function-transformer.ts index eaad17604..b6b77810b 100644 --- a/arkoala-arkts/libarkts/compatible/src/function-transformer.ts +++ b/arkoala-arkts/libarkts/compatible/src/function-transformer.ts @@ -12,9 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* -import global from "../../src/api/static/global" -import * as ts from "../../src/api" + +import * as ts from "@koalaui/libarkts" import { AbstractVisitor } from "./AbstractVisitor"; const ANNOTATION = "_REWRITE_" @@ -30,16 +29,15 @@ function isAnnotatedMethodDeclaration(node: ts.Node): boolean { function transformCallExpression(node: ts.CallExpression): ts.Node { const decl = ts.getDecl(node.expression) if (decl === undefined) { - global.throwError('memo function not found') + throw new Error('memo function for call not found') } if (!ts.isIdentifier(node.expression)) { - global.throwError('expression should be Identifier') + throw new Error('expression should be Identifier') } return ts.factory.updateCallExpression( node, - ts.factory.updateIdentifier( - node.expression, + ts.factory.createIdentifier( node.expression.text.slice(ANNOTATION.length) ), undefined, @@ -64,8 +62,7 @@ function transformMethodDeclaration(node: ts.MethodDeclaration): ts.Node { node, undefined, undefined, - ts.factory.updateIdentifier( - node.name, + ts.factory.createIdentifier( node.name.text.slice(ANNOTATION.length) ), undefined, @@ -98,4 +95,3 @@ export class FunctionTransformer extends AbstractVisitor { return node } } -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/compatible/src/memo-transformer.ts b/arkoala-arkts/libarkts/compatible/src/memo-transformer.ts index b32004b4f..01a245171 100644 --- a/arkoala-arkts/libarkts/compatible/src/memo-transformer.ts +++ b/arkoala-arkts/libarkts/compatible/src/memo-transformer.ts @@ -12,112 +12,110 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* -import * as arkts from "../../src/arkts" + +import * as ts from "@koalaui/libarkts" import { AbstractVisitor } from "./AbstractVisitor"; const ANNOTATION = "_MEMO_" -function isAnnotatedCallExpression(node: arkts.Node): boolean { - return arkts.isCallExpression(node) && arkts.isIdentifier(node.expression) && node.expression.text.startsWith(ANNOTATION) +function isAnnotatedCallExpression(node: ts.Node): boolean { + return ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text.startsWith(ANNOTATION) } -function isAnnotatedMethodDeclaration(node: arkts.Node): boolean { - return arkts.isMethodDeclaration(node) && node.name.text.startsWith(ANNOTATION) +function isAnnotatedMethodDeclaration(node: ts.Node): boolean { + return ts.isMethodDeclaration(node) && node.name.text.startsWith(ANNOTATION) } -function transformCallExpression(node: arkts.CallExpression): arkts.Node { - const decl = arkts.getDecl(node.expression) +function transformCallExpression(node: ts.CallExpression): ts.Node { + const decl = ts.getDecl(node.expression) if (decl === undefined) { - arkts.throwError('memo function not found') + throw new Error('memo function not found') } - if (!arkts.isIdentifier(node.expression)) { - arkts.throwError('expression should be Identifier') + if (!ts.isIdentifier(node.expression)) { + throw new Error('expression should be Identifier') } - return arkts.factory.updateCallExpression( + return ts.factory.updateCallExpression( node, - arkts.factory.updateIdentifier( - node.expression, + ts.factory.createIdentifier( node.expression.text.slice(ANNOTATION.length) ), undefined, [ - arkts.factory.createIdentifier("__memo_context"), - arkts.factory.createIdentifier("__memo_id"), + ts.factory.createIdentifier("__memo_context"), + ts.factory.createIdentifier("__memo_id"), ...node.arguments ] ) } -function transformMethodDeclaration(node: arkts.MethodDeclaration): arkts.Node { +function transformMethodDeclaration(node: ts.MethodDeclaration): ts.Node { const memoContextParam = - arkts.factory.createParameterDeclaration( + ts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier("__memo_context"), + ts.factory.createIdentifier("__memo_context"), undefined, - arkts.factory.createTypeReferenceNode( - arkts.factory.createIdentifier("__memo_context_type") + ts.factory.createTypeReferenceNode( + ts.factory.createIdentifier("__memo_context_type") ), undefined ) const memoIdParam = - arkts.factory.createParameterDeclaration( + ts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier("__memo_id"), + ts.factory.createIdentifier("__memo_id"), undefined, - arkts.factory.createTypeReferenceNode( - arkts.factory.createIdentifier("__memo_id_type") + ts.factory.createTypeReferenceNode( + ts.factory.createIdentifier("__memo_id_type") ), undefined ) const bodyStatements = [ - arkts.factory.createIfStatement( - arkts.factory.createPropertyAccessExpression( - arkts.factory.createIdentifier("__memo_scope"), - arkts.factory.createIdentifier("unchanged") + ts.factory.createIfStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("unchanged") ), - arkts.factory.createReturnStatement( - arkts.factory.createPropertyAccessExpression( - arkts.factory.createIdentifier("__memo_scope"), - arkts.factory.createIdentifier("cached") + ts.factory.createReturnStatement( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("cached") ) ), undefined ), - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createIdentifier("content"), + ts.factory.createExpressionStatement( + ts.factory.createCallExpression( + ts.factory.createIdentifier("content"), undefined, [ - arkts.factory.createIdentifier("__memo_context"), - arkts.factory.createBinaryExpression( - arkts.factory.createIdentifier("__memo_id"), - arkts.factory.createToken(arkts.SyntaxKind.PlusToken), - arkts.factory.createStringLiteral("key_id_main.ts") + 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") ) ] )), ...(node.body?.statements ?? []), - arkts.factory.createReturnStatement( - arkts.factory.createCallExpression( - arkts.factory.createPropertyAccessExpression( - arkts.factory.createIdentifier("__memo_scope"), - arkts.factory.createIdentifier("recache") + ts.factory.createReturnStatement( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier("__memo_scope"), + ts.factory.createIdentifier("recache") ), undefined, undefined ) ), ] - return arkts.factory.updateMethodDeclaration( + return ts.factory.updateMethodDeclaration( node, undefined, undefined, - arkts.factory.updateIdentifier( - node.name, + ts.factory.createIdentifier( node.name.text.slice(ANNOTATION.length) ), undefined, @@ -129,7 +127,7 @@ function transformMethodDeclaration(node: arkts.MethodDeclaration): arkts.Node { ], undefined, node.body ? - arkts.factory.updateBlock( + ts.factory.updateBlock( node.body, bodyStatements ) : undefined @@ -138,21 +136,20 @@ function transformMethodDeclaration(node: arkts.MethodDeclaration): arkts.Node { export class MemoTransformer extends AbstractVisitor { constructor( - ctx?: arkts.TransformationContext + ctx?: ts.TransformationContext ) { super(ctx) } - visitor(beforeChildren: arkts.Node): arkts.Node { - const node: arkts.Node = this.visitEachChild(beforeChildren) + visitor(beforeChildren: ts.Node): ts.Node { + const node: ts.Node = this.visitEachChild(beforeChildren) - if (isAnnotatedMethodDeclaration(node) && arkts.isMethodDeclaration(node)) { + if (isAnnotatedMethodDeclaration(node) && ts.isMethodDeclaration(node)) { return transformMethodDeclaration(node) - } else if (isAnnotatedCallExpression(node) && arkts.isCallExpression(node) && arkts.isIdentifier(node.expression)) { + } else if (isAnnotatedCallExpression(node) && ts.isCallExpression(node) && ts.isIdentifier(node.expression)) { return transformCallExpression(node) } return node } } -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/compatible/src/print-visitor.ts b/arkoala-arkts/libarkts/compatible/src/print-visitor.ts index e28b65221..8e8244460 100644 --- a/arkoala-arkts/libarkts/compatible/src/print-visitor.ts +++ b/arkoala-arkts/libarkts/compatible/src/print-visitor.ts @@ -1,29 +1,27 @@ -import * as ts from "../../src/api" -import { AbstractVisitor } from "./AbstractVisitor"; - -export class PrintVisitor extends AbstractVisitor { - constructor( - ctx?: ts.TransformationContext - ) { - super(ctx) - } - - private result = "" - - private print(s: string) { - this.result += " ".repeat(4 * this.indentation) + s + '\n' - } - - visitor(beforeChildren: ts.Node): ts.Node { - this.print(beforeChildren.constructor.name + " (mods: [" + beforeChildren.modifiers + "])") - const node = this.visitEachChild(beforeChildren) - - return node - } - - astToString(node: ts.Node): string { - this.result = "" - this.visitor(node) - return this.result.trim() - } -} +import * as ts from "@koalaui/libarkts" +import { AbstractVisitor } from "./AbstractVisitor"; + +export class PrintVisitor extends AbstractVisitor { + constructor( + ctx?: ts.TransformationContext + ) { + super(ctx) + } + + private result = "" + + private print(s: string) { + this.result += " ".repeat(4 * this.indentation) + s + '\n' + } + + visitor(node: ts.Node): ts.Node { + this.print(`${node.constructor.name} ${node.node?.peer} mods: [${node.modifiers}]`) + return this.visitEachChild(node) + } + + astToString(node: ts.Node): string { + this.result = "" + this.visitor(node) + return this.result.trim() + } +} diff --git a/arkoala-arkts/libarkts/compatible/src/transformation-context.ts b/arkoala-arkts/libarkts/compatible/src/transformation-context.ts index ab4764808..681e3d124 100644 --- a/arkoala-arkts/libarkts/compatible/src/transformation-context.ts +++ b/arkoala-arkts/libarkts/compatible/src/transformation-context.ts @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* -import * as arkts from "../../src/arkts" + +import * as ts from "@koalaui/libarkts" import { CallTable, EntryTable, FunctionKind, FunctionTable, TransformerOptions, VariableTable } from "./util" export class Rewrite { @@ -23,14 +23,13 @@ export class Rewrite { public entryTable: EntryTable // public positionalIdTracker: PositionalIdTracker - constructor(sourceFile: arkts.SourceFile, public pluginOptions: TransformerOptions) { - this.functionTable = new Map() - this.callTable = new Map() - this.variableTable = new Map() - this.entryTable = new Set() + constructor(sourceFile: ts.SourceFile, public pluginOptions: TransformerOptions) { + this.functionTable = new Map() + this.callTable = new Map() + this.variableTable = new Map() + this.entryTable = new Set() // this.positionalIdTracker = new PositionalIdTracker(sourceFile, pluginOptions.stableForTest ?? false) } public importTypesFrom: string | undefined = undefined } -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/compatible/src/util.ts b/arkoala-arkts/libarkts/compatible/src/util.ts index c8622f4b2..3bbd8f639 100644 --- a/arkoala-arkts/libarkts/compatible/src/util.ts +++ b/arkoala-arkts/libarkts/compatible/src/util.ts @@ -12,9 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* -import * as arkts from "../../src/arkts" -import * as fs from "fs" + +import * as ts from "@koalaui/libarkts" +import * as fs from 'fs' export enum FunctionKind { REGULAR, @@ -22,38 +22,38 @@ export enum FunctionKind { MEMO_INTRINSIC, } -export type FunctionTable = Map -export type CallTable = Map -export type EntryTable = Set -export type VariableTable = Map +export type FunctionTable = Map +export type CallTable = Map +export type EntryTable = Set +export type VariableTable = Map -export function isNamedDeclaration(node: arkts.Node): node is arkts.NamedDeclaration { +export function isNamedDeclaration(node: ts.Node): node is ts.NamedDeclaration { return ("name" in node ) } -export function asString(node: arkts.Node | undefined): string { +export function asString(node: ts.Node | undefined): string { if (node === undefined) { return "undefined node" } - if (arkts.isIdentifier(node)) { + if (ts.isIdentifier(node)) { return node.text } if (isNamedDeclaration(node)) { if (node.name === undefined) { - return `${arkts.SyntaxKind[node.kind]}(undefined name)` + return `${ts.SyntaxKind[node.kind]}(undefined name)` } else { - return `${arkts.SyntaxKind[node.kind]}(${asString(node.name)})` + return `${ts.SyntaxKind[node.kind]}(${asString(node.name)})` } } else { - return `${arkts.SyntaxKind[node.kind]}` + return `${ts.SyntaxKind[node.kind]}` } } -export function isFunctionOrMethod(node: arkts.Node): node is arkts.FunctionLikeDeclaration { - return arkts.isFunctionDeclaration(node) || - arkts.isMethodDeclaration(node) || - arkts.isFunctionExpression(node) || - arkts.isArrowFunction(node) +export function isFunctionOrMethod(node: ts.Node): node is ts.FunctionLikeDeclaration { + return ts.isFunctionDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isFunctionExpression(node) || + ts.isArrowFunction(node) } export interface TransformerOptions { @@ -96,7 +96,7 @@ export class Tracer { fs.mkdirSync(dirs, { recursive: true }); } - dumpFileName(sourceFile: arkts.SourceFile, transformed: arkts.FunctionLikeDeclarationBase): string | undefined { + dumpFileName(sourceFile: ts.SourceFile, transformed: ts.FunctionLikeDeclarationBase): string | undefined { if (!this.options.keepTransformed) { return undefined } @@ -109,12 +109,12 @@ export class Tracer { const sourceBaseName = baseName(sourceFile.fileName) if (!transformed.name) return - if (!arkts.isIdentifier(transformed.name)) return + if (!ts.isIdentifier(transformed.name)) return const fileName = `${transformed.name.text}_${sourceBaseName}` return `${outDir}/${fileName}_dump` } - keepTransformedFunction(transformed: arkts.FunctionLikeDeclarationBase, sourceFile: arkts.SourceFile) { + keepTransformedFunction(transformed: ts.FunctionLikeDeclarationBase, sourceFile: ts.SourceFile) { const fileName = this.dumpFileName(sourceFile, transformed) if (!fileName) return @@ -152,13 +152,12 @@ export enum RuntimeNames { ANNOTATION_STABLE = "_memo:stable", // assume this should not be tracked } -export function findFunctionDeclaration(node: arkts.Node): arkts.FunctionDeclaration | undefined { - while (node.kind !== arkts.SyntaxKind.SourceFile) { - if (arkts.isFunctionDeclaration(node)) { +export function findFunctionDeclaration(node: ts.Node): ts.FunctionDeclaration | undefined { + while (node.kind !== ts.SyntaxKind.SourceFile) { + if (ts.isFunctionDeclaration(node)) { return node } node = node.parent } return undefined } -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/compatible/typescript-tsconfig.json b/arkoala-arkts/libarkts/compatible/typescript-tsconfig.json deleted file mode 100644 index 4034257f1..000000000 --- a/arkoala-arkts/libarkts/compatible/typescript-tsconfig.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "extends": "@koalaui/build-common/tsconfig.json", - "compilerOptions": { - "baseUrl": "../../", - "outDir": "build/typescript", - "paths": { - "api": [ - "node_modules/typescript/lib/typescript.d.ts" - ] - }, - "module": "CommonJS", - "moduleResolution": "node" - }, - "include": [ - "src/**/*" - ] -} - diff --git a/arkoala-arkts/libarkts/compatible/typescript.webpack.config.js b/arkoala-arkts/libarkts/compatible/typescript.webpack.config.js deleted file mode 100644 index e5e12c3f1..000000000 --- a/arkoala-arkts/libarkts/compatible/typescript.webpack.config.js +++ /dev/null @@ -1,38 +0,0 @@ -const path = require("path") -const minimize = !process.env.WEBPACK_NO_MINIMIZE - -const makeConfig = () => ({ - target: "node", - entry: `./src/example-transformer.ts`, - output: { - filename: "example-transformer.js", - library: { - type: 'commonjs-module', - }, - path: path.resolve(__dirname, "./build_typescript") - }, - resolve: { - alias: { - api: "typescript" - }, - extensions: ['.ts', '...'] - }, - module: { - rules: [ - { - test: /\.ts$/, - use: [{ - loader: 'ts-loader', - options: { - configFile: "typescript-tsconfig.json" - } - }] - } - ] - }, - mode: minimize ? "production" : "development" -}) - -module.exports = env => { - return makeConfig() -} diff --git a/arkoala-arkts/libarkts/compatible/arkts.webpack.config.js b/arkoala-arkts/libarkts/compatible/webpack.config.js similarity index 63% rename from arkoala-arkts/libarkts/compatible/arkts.webpack.config.js rename to arkoala-arkts/libarkts/compatible/webpack.config.js index 2d7b5d99d..1130d0e91 100644 --- a/arkoala-arkts/libarkts/compatible/arkts.webpack.config.js +++ b/arkoala-arkts/libarkts/compatible/webpack.config.js @@ -1,38 +1,44 @@ -const path = require("path") -const minimize = !process.env.WEBPACK_NO_MINIMIZE - -const makeConfig = () => ({ - target: "node", - entry: `./src/example-transformer.ts`, - output: { - filename: "example-transformer.js", - library: { - type: 'commonjs-module', - }, - path: path.resolve(__dirname, "./build_arkts") - }, - resolve: { - alias: { - api: "typescript" - }, - extensions: ['.ts', '...'] - }, - module: { - rules: [ - { - test: /\.ts$/, - use: [{ - loader: 'ts-loader', - options: { - configFile: "arkts-tsconfig.json" - } - }] - } - ] - }, - mode: minimize ? "production" : "development" -}) - -module.exports = env => { - return makeConfig() -} +const path = require("path") +const minimize = !process.env.WEBPACK_NO_MINIMIZE + +const makeConfig = () => ({ + target: "node", + entry: `./src/example-transformer.ts`, + output: { + filename: "example-transformer.js", + // library: { + // type: 'commonjs-module', + // }, + path: path.resolve(__dirname, "./build_arkts") + }, + resolve: { + // alias: { + // api: "typescript" + // }, + extensions: ['.ts', '...'], + modules: [ + path.resolve(__dirname, "../node_modules"), + ] + }, + module: { + rules: [ + { + use: [{ + loader: 'ts-loader', + options: { + configFile: "arkts-tsconfig.json" + } + }] + }, + // { + // test: /\.node$/, + // loader: "node-loader" + // } + ] + }, + mode: minimize ? "production" : "development" +}) + +module.exports = env => { + return makeConfig() +} diff --git a/arkoala-arkts/libarkts/es2panda-tsconfig.json b/arkoala-arkts/libarkts/es2panda-tsconfig.json index 6ae3be937..e72996d30 100644 --- a/arkoala-arkts/libarkts/es2panda-tsconfig.json +++ b/arkoala-arkts/libarkts/es2panda-tsconfig.json @@ -12,8 +12,9 @@ "module": "CommonJS" }, "include": [ - "src/**/*.ts", - "test/**/*.ts", - "compatible/**/*.ts" + "./src/**/*.ts", + ], + "exclude": [ + "./input/**/*" ] } \ No newline at end of file diff --git a/arkoala-arkts/libarkts/input/f.sts b/arkoala-arkts/libarkts/input/f.sts new file mode 100644 index 000000000..369304938 --- /dev/null +++ b/arkoala-arkts/libarkts/input/f.sts @@ -0,0 +1,3 @@ +export function f() { + console.log("Hello, world!") +} diff --git a/arkoala-arkts/libarkts/input/tsconfig.json b/arkoala-arkts/libarkts/input/tsconfig.json deleted file mode 100644 index b80001e93..000000000 --- a/arkoala-arkts/libarkts/input/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "include": [ - "./**/*.ts" - ], - "compilerOptions": { - "outDir": "../build/tsc", - "plugins": [ - { - "transform": "../compatible/build_arkts/example-transformer.js", - } - ] - } -} diff --git a/arkoala-arkts/libarkts/input/variable.sts b/arkoala-arkts/libarkts/input/variable.sts new file mode 100644 index 000000000..2322ed6f0 --- /dev/null +++ b/arkoala-arkts/libarkts/input/variable.sts @@ -0,0 +1 @@ +export const X: double = 1.2345; diff --git a/arkoala-arkts/libarkts/native/.gitignore b/arkoala-arkts/libarkts/native/.gitignore index 8ef7ae46c..9442d2bf7 100644 --- a/arkoala-arkts/libarkts/native/.gitignore +++ b/arkoala-arkts/libarkts/native/.gitignore @@ -1,3 +1 @@ -prebuilt -build-* -*.abc +build_* diff --git a/arkoala-arkts/libarkts/native/meson.build b/arkoala-arkts/libarkts/native/meson.build index 76a002823..20f220b0a 100644 --- a/arkoala-arkts/libarkts/native/meson.build +++ b/arkoala-arkts/libarkts/native/meson.build @@ -1,96 +1,57 @@ -project('Es2panda interop', 'cpp', - version: '0.1', - default_options: ['cpp_std=c++17', 'buildtype=debug'], +project( + 'es2panda_interop', + 'cpp', + version: '1.0', + default_options: [ + 'cpp_std=c++17', + 'buildtype=debug', + ], ) -source_dir = meson.current_source_dir() -interop_src = '../../../interop/src/cpp' -es2panda_header = '../node_modules/@koalaui/plugin-api-panda-sdk/@panda/sdk/ohos_arm64/include/tools/es2panda/public' -es2panda_gen = '../node_modules/@koalaui/plugin-api-panda-sdk/@panda/sdk/ohos_arm64/include/tools/es2panda/' -is_msvc = meson.get_compiler('cpp').get_id() == 'msvc' - -implementation = './src/es2panda_lib.cc' - -os = target_machine.system() - sources = [ - implementation, - interop_src / 'common-interop.cc', - interop_src / 'interop-logging.cc' + './src/es2panda_lib.cc', + get_option('interop_src_dir') / 'common-interop.cc', + get_option('interop_src_dir') / 'interop-logging.cc', + get_option('interop_src_dir') / 'napi/convertors-napi.cc', ] -include_dirs = [ - es2panda_header, - es2panda_gen + +cflags = [ + '-DINTEROP_LIBRARY_NAME=' + get_option('lib_name'), + '-DKOALA_USE_NODE_VM', + '-DKOALA_NAPI', ] -library_use_name = 'Es2panda' -cflags = ['-DINTEROP_LIBRARY_NAME=' + library_use_name] -ldflags = [] -deps = [] -if os == 'windows' +if (target_machine.system() == 'windows') cflags += ['-DKOALA_WINDOWS'] - if is_msvc + if (meson.get_compiler('cpp').get_id() == 'msvc') # apply node.exe symbol loading hook sources += [ - interop_src / 'napi/win-dynamic-node.cc' + get_option('interop_src_dir') / 'napi/win-dynamic-node.cc' ] endif -endif - -if os == 'linux' +else cflags += ['-DKOALA_LINUX'] endif -include_dirs += [ - interop_src, - interop_src / 'types', -] - -sources += [ - interop_src / 'napi/convertors-napi.cc', -] - -node_addon_api = '../node_modules/node-addon-api' -node_api_headers = '../node_modules/node-api-headers' - -include_dirs += [ - interop_src / 'napi', - node_api_headers / 'include', - node_addon_api, -] -cflags += [ - '-DKOALA_USE_NODE_VM', - '-DKOALA_NAPI' -] - -module_prefix = '' -module_suffix = 'node' - shared_library( - library_use_name, + get_option('lib_name'), sources, override_options: [ 'b_lundef=false', ], install: true, - name_prefix: module_prefix, - name_suffix: module_suffix, - include_directories: include_dirs, - install_dir: source_dir / '..' / 'build', + name_prefix: '', + name_suffix: 'node', + include_directories: [ + get_option('panda_sdk_dir') / 'ohos_arm64/include/tools/es2panda/public', + get_option('panda_sdk_dir') / 'ohos_arm64/include/tools/es2panda', + get_option('interop_src_dir'), + get_option('interop_src_dir') / 'types', + get_option('interop_src_dir') / 'napi', + get_option('node_modules_dir') / 'node-api-headers/include', + get_option('node_modules_dir') / 'node-addon-api', + ], cpp_args: cflags, - link_args: ldflags, - dependencies: deps -) - -playground_exec_name = 'playground_exec' - -sources = [ - './src/playground.cc' -] - -executable( - playground_exec_name, - sources, - include_directories: include_dirs, - cpp_args: cflags + link_args: [], + dependencies: [] ) diff --git a/arkoala-arkts/libarkts/native/meson_options.txt b/arkoala-arkts/libarkts/native/meson_options.txt index e69de29bb..e31a92eff 100644 --- a/arkoala-arkts/libarkts/native/meson_options.txt +++ b/arkoala-arkts/libarkts/native/meson_options.txt @@ -0,0 +1,8 @@ +option('node_modules_dir', type : 'string', value : '../node_modules/', + description : 'path to node_modules') +option('panda_sdk_dir', type : 'string', value : '../node_modules/@panda/sdk/', + description : 'path to panda sdk') +option('interop_src_dir', type : 'string', value : '../../../interop/src/cpp/', + description : 'path to interop') +option('lib_name', type : 'string', value : 'es2panda', + description : 'name of shared library') diff --git a/arkoala-arkts/libarkts/native/src/es2panda_lib.cc b/arkoala-arkts/libarkts/native/src/es2panda_lib.cc index da206a1f7..d1d376c2e 100644 --- a/arkoala-arkts/libarkts/native/src/es2panda_lib.cc +++ b/arkoala-arkts/libarkts/native/src/es2panda_lib.cc @@ -27,20 +27,26 @@ using std::string, std::cout, std::endl, std::vector; static es2panda_Impl *impl = nullptr; #ifdef KOALA_WINDOWS -#include -#define PLUGIN_DIR "windows_host_tools" -#define LIB_PREFIX "" -#define LIB_SUFFIX ".dll" + #include + #define PLUGIN_DIR "windows_host_tools" + #define LIB_PREFIX "" + #define LIB_SUFFIX ".dll" #endif #ifdef KOALA_LINUX -#include -#define PLUGIN_DIR "linux_host_tools" -#define LIB_PREFIX "lib" -#define LIB_SUFFIX ".so" + #include + + #ifdef __x86_64__ + #define PLUGIN_DIR "linux_host_tools" + #else + #define PLUGIN_DIR "linux_arm64_host_tools" + #endif + + #define LIB_PREFIX "lib" + #define LIB_SUFFIX ".so" #endif -const char* libpath = "./node_modules/@koalaui/plugin-api-panda-sdk/@panda/sdk/" PLUGIN_DIR "/lib/" LIB_PREFIX "es2panda-public" LIB_SUFFIX; +const char* libpath = "node_modules/@panda/sdk/" PLUGIN_DIR "/lib/" LIB_PREFIX "es2panda-public" LIB_SUFFIX; es2panda_Impl *GetImpl() { if (impl) { @@ -48,7 +54,7 @@ es2panda_Impl *GetImpl() { } auto library = loadLibrary(libpath); if (!library) { - throw std::runtime_error("No library"); + throw std::runtime_error("No library (es2panda_lib.cc)"); } auto symbol = findSymbol(library, "es2panda_GetImpl"); if (!symbol) { @@ -119,6 +125,12 @@ KNativePointer impl_CreateContextFromString(KNativePointer configPtr, KStringPtr } KOALA_INTEROP_3(CreateContextFromString, KNativePointer, KNativePointer, KStringPtr, KStringPtr) +KNativePointer impl_CreateContextFromFile(KNativePointer configPtr, KStringPtr filenamePtr) { + auto config = reinterpret_cast(configPtr); + return GetImpl()->CreateContextFromFile(config, getStringCopy(filenamePtr)); +} +KOALA_INTEROP_2(CreateContextFromFile, KNativePointer, KNativePointer, KStringPtr) + KNativePointer impl_DestroyContext(KNativePointer contextPtr) { auto context = reinterpret_cast(contextPtr); GetImpl()->DestroyContext(context); @@ -204,6 +216,14 @@ KNativePointer impl_CreateETSPrimitiveType(KNativePointer contextPtr, KInt type) } KOALA_INTEROP_2(CreateETSPrimitiveType, KNativePointer, KNativePointer, KInt) +KInt impl_ETSPrimitiveTypeGetPrimitiveTypeConst(KNativePointer contextPtr, KNativePointer nodePtr) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->ETSPrimitiveTypeGetPrimitiveTypeConst(context, node); +} +KOALA_INTEROP_2(ETSPrimitiveTypeGetPrimitiveTypeConst, KInt, KNativePointer, KNativePointer) + KNativePointer impl_CreateETSFunctionTypeIr(KNativePointer contextPtr, KNativePointer signaturePtr, KInt funcFlagsT) { auto context = reinterpret_cast(contextPtr); auto signature = reinterpret_cast(signaturePtr); @@ -300,154 +320,6 @@ KNativePointer impl_ETSParserCreateExpression(KNativePointer contextPtr, KString } KOALA_INTEROP_3(ETSParserCreateExpression, KNativePointer, KNativePointer, KStringPtr, KInt) - -/* - TODO: AstNodeKind should be provided by es2panda - */ -enum AstNodeKind { - Identifier = 1, - StringLiteral = 2, - BlockStatement = 3, - MethodDefinition = 4, - ClassDeclaration = 5, - FunctionDeclaration = 6, - ClassProperty = 7, - TSTypeParameterDeclaration = 8, - ETSFunctionType = 9, - CallExpression = 10, - ExpressionStatement = 11, - MemberExpression = 12, - ArrowFunctionExpression = 13, - ReturnStatement = 14, - ETSParameterExpression = 15, - NumberLiteral = 16, - VariableDeclaration = 17, - ClassStaticBlock = 18, - Program = 19, - BinaryExpression = 20, - FunctionExpression = 21, - ScriptFunction = 22, - VariableDeclarator = 23, - TSTypeParameter = 24, - ETSPrimitiveType = 25, - AssignmentExpression = 26, - ETSTypeReference = 27, - TSUnionType = 28, - ETSUnionType = 29, - ClassDefinition = 30, - ETSTypeReferencePart = 31, - IfStatement = 32, -}; - -static KInt GetKind(es2panda_Context* context, es2panda_AstNode* node) { - if (GetImpl()->IsIdentifier(node)) { - return AstNodeKind::Identifier; - } - if (GetImpl()->IsStringLiteral(node)) { - return AstNodeKind::StringLiteral; - } - if (GetImpl()->IsBlockStatement(node)) { - return AstNodeKind::BlockStatement; - } - if (GetImpl()->IsMethodDefinition(node)) { - return AstNodeKind::MethodDefinition; - } - if (GetImpl()->IsClassDeclaration(node)) { - return AstNodeKind::ClassDeclaration; - } - if (GetImpl()->IsFunctionDeclaration(node)) { - return AstNodeKind::FunctionDeclaration; - } - if (GetImpl()->IsClassProperty(node)) { - return AstNodeKind::ClassProperty; - } - if (GetImpl()->IsTSTypeParameterDeclaration(node)) { - return AstNodeKind::TSTypeParameterDeclaration; - } - if (GetImpl()->IsETSFunctionType(node)) { - return AstNodeKind::ETSFunctionType; - } - if (GetImpl()->IsCallExpression(node)) { - return AstNodeKind::CallExpression; - } - if (GetImpl()->IsExpressionStatement(node)) { - return AstNodeKind::ExpressionStatement; - } - if (GetImpl()->IsMemberExpression(node)) { - return AstNodeKind::MemberExpression; - } - if (GetImpl()->IsArrowFunctionExpression(node)) { - return AstNodeKind::ArrowFunctionExpression; - } - if (GetImpl()->IsReturnStatement(node)) { - return AstNodeKind::ReturnStatement; - } - if (GetImpl()->IsETSParameterExpression(node)) { - return AstNodeKind::ETSParameterExpression; - } - if (GetImpl()->IsNumberLiteral(node)) { - return AstNodeKind::NumberLiteral; - } - if (GetImpl()->IsVariableDeclaration(node)) { - return AstNodeKind::VariableDeclaration; - } - if (GetImpl()->IsClassStaticBlock(node)) { - return AstNodeKind::ClassStaticBlock; - } - if (GetImpl()->IsBinaryExpression(node)) { - return AstNodeKind::BinaryExpression; - } - if (GetImpl()->IsFunctionExpression(node)) { - return AstNodeKind::FunctionExpression; - } - if (GetImpl()->IsScriptFunction(node)) { - return AstNodeKind::ScriptFunction; - } - if (GetImpl()->IsVariableDeclarator(node)) { - return AstNodeKind::VariableDeclarator; - } - if (GetImpl()->IsTSTypeParameter(node)) { - return AstNodeKind::TSTypeParameter; - } - if (GetImpl()->IsETSPrimitiveType(node)) { - return AstNodeKind::ETSPrimitiveType; - } - if (GetImpl()->IsAssignmentExpression(node)) { - return AstNodeKind::AssignmentExpression; - } - if (GetImpl()->IsETSTypeReference(node)) { - return AstNodeKind::ETSTypeReference; - } - if (GetImpl()->IsTSUnionType(node)) { - return AstNodeKind::TSUnionType; - } - if (GetImpl()->IsETSUnionType(node)) { - return AstNodeKind::ETSUnionType; - } - if (GetImpl()->IsClassDefinition(node)) { - return AstNodeKind::ClassDefinition; - } - if (GetImpl()->IsETSTypeReferencePart(node)) { - return AstNodeKind::ETSTypeReferencePart; - } - if (GetImpl()->IsIfStatement(node)) { - return AstNodeKind::IfStatement; - } - - if (GetImpl()->AstNodeIsProgramConst(context, node)) { - return AstNodeKind::Program; - } - return 0; -} - -KInt impl_GetKind(KNativePointer contextPtr, KNativePointer nodePtr) { - auto context = reinterpret_cast(contextPtr); - auto node = reinterpret_cast(nodePtr); - - return GetKind(context, node); -} -KOALA_INTEROP_2(GetKind, KInt, KNativePointer, KNativePointer) - KBoolean impl_IsProgram(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -479,15 +351,13 @@ KNativePointer impl_VariableDeclarationDeclaratorsConst(KNativePointer contextPt } KOALA_INTEROP_2(VariableDeclarationDeclaratorsConst, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_BlockStatementUpdateStatements(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointerArray statementListPtr, KInt statementListLen, KNativePointer returnTypeLenPtr) { +KInt impl_VariableDeclarationKindConst(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); - auto statementList = reinterpret_cast(statementListPtr); - size_t n; - auto statements = GetImpl()->BlockStatementUpdateStatements(context, node, statementList, statementListLen, &n); - return new vector(statements, statements + n); + + return GetImpl()->VariableDeclarationKindConst(context, node); } -KOALA_INTEROP_5(BlockStatementUpdateStatements, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KNativePointer) +KOALA_INTEROP_2(VariableDeclarationKindConst, KInt, KNativePointer, KNativePointer) KNativePointer impl_ClassDeclarationDefinition(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); @@ -528,6 +398,16 @@ KBoolean impl_FunctionDeclarationIsAnonymousConst(KNativePointer contextPtr, KNa } KOALA_INTEROP_2(FunctionDeclarationIsAnonymousConst, KBoolean, KNativePointer, KNativePointer) +KNativePointer impl_ScriptFunctionAddFlag(KNativePointer contextPtr, KNativePointer nodePtr, KInt flagsT) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + auto flags = static_cast(flagsT); + + GetImpl()->ScriptFunctionAddFlag(context, node, flags); + return node; +} +KOALA_INTEROP_3(ScriptFunctionAddFlag, KNativePointer, KNativePointer, KNativePointer, KInt) + KNativePointer impl_ScriptFunctionParams(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -567,29 +447,39 @@ KBoolean impl_ScriptFunctionDeclareConst(KNativePointer contextPtr, KNativePoint } KOALA_INTEROP_2(ScriptFunctionDeclareConst, KBoolean, KNativePointer, KNativePointer) -KNativePointer impl_CreateFunctionDeclaration(KNativePointer contextPtr, KNativePointer funcPtr, KBoolean isAnonK) { +KNativePointer impl_CreateFunctionDeclaration( + KNativePointer contextPtr, + KNativePointer funcPtr, + KNativePointerArray annotationsPtr, + KInt annotationsLen, + KBoolean isAnonK +) { auto context = reinterpret_cast(contextPtr); auto func = reinterpret_cast(funcPtr); + auto annotations = reinterpret_cast(annotationsPtr); auto isAnon = static_cast(isAnonK); - return GetImpl()->CreateFunctionDeclaration(context, func, isAnon); + return GetImpl()->CreateFunctionDeclaration(context, func, annotations, annotationsLen, isAnon); } -KOALA_INTEROP_3(CreateFunctionDeclaration, KNativePointer, KNativePointer, KNativePointer, KBoolean) +KOALA_INTEROP_5(CreateFunctionDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KBoolean) KNativePointer impl_UpdateFunctionDeclaration( KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer funcPtr, + KNativePointerArray annotationsPtr, + KInt annotationsLen, KBoolean isAnonK ) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); auto func = reinterpret_cast(funcPtr); + auto annotations = reinterpret_cast(annotationsPtr); auto isAnon = static_cast(isAnonK); - return GetImpl()->UpdateFunctionDeclaration(context, node, func, isAnon); + return GetImpl()->UpdateFunctionDeclaration(context, node, func, annotations, annotationsLen, isAnon); } -KOALA_INTEROP_4(UpdateFunctionDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean) +KOALA_INTEROP_6(UpdateFunctionDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KBoolean) // TODO: add param initializer KNativePointer impl_CreateETSParameterExpression(KNativePointer contextPtr, KNativePointer identifierPtr, KNativePointer initializerPtr) { @@ -865,6 +755,17 @@ KNativePointer impl_MemberExpressionProperty( } KOALA_INTEROP_2(MemberExpressionProperty, KNativePointer, KNativePointer, KNativePointer) +KInt impl_MemberExpressionKindConst( + KNativePointer contextPtr, + KNativePointer nodePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->MemberExpressionKindConst(context, node); +} +KOALA_INTEROP_2(MemberExpressionKindConst, KInt, KNativePointer, KNativePointer) + KNativePointer impl_CreateCallExpression( KNativePointer contextPtr, KNativePointer calleePtr, @@ -1059,92 +960,6 @@ KNativePointer impl_CreateBlockStatement( } KOALA_INTEROP_3(CreateBlockStatement, KNativePointer, KNativePointer, KNativePointerArray, KInt) -// TODO: rewrite everything here -/* ------------------------------------------------------------------------------------------------------------------------------ -*/ - -es2panda_AstNode * __parentNode; -es2panda_Context * __context; - -static void changeParent(es2panda_AstNode *child) -{ - GetImpl()->AstNodeSetParent(__context, child, __parentNode); -} - -static void SetRightParent(es2panda_AstNode *node, void *arg) -{ - es2panda_Context *ctx = static_cast(arg); - __context = ctx; - __parentNode = node; - GetImpl()->AstNodeIterateConst(ctx, node, changeParent); -} - -KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer programPtr) { - auto context = reinterpret_cast(contextPtr); - auto program = reinterpret_cast(programPtr); - - GetImpl()->AstNodeForEach(program, SetRightParent, context); - - return program; -} -KOALA_INTEROP_2(AstNodeUpdateAll, KNativePointer, KNativePointer, KNativePointer) - -KNativePointer impl_AstNodeUpdateChildren(KNativePointer contextPtr, KNativePointer nodePtr) { - auto context = reinterpret_cast(contextPtr); - auto node = reinterpret_cast(nodePtr); - - // auto lambda = [node, impl, context](es2panda_AstNode *child){ impl->AstNodeSetParent(context, child, node); }; - // void(decltype(lambda)::*ptr)(es2panda_AstNode*)const = &decltype(lambda)::operator(); - - // impl->AstNodeIterateConst(context, node, [node, impl, context](es2panda_AstNode *child){ impl->AstNodeSetParent(context, child, node); }); - // GetImpl()->AstNodeIterateConst(context, node, &decltype(lambda)::operator()); - - __parentNode = node; - GetImpl()->AstNodeIterateConst(context, node, changeParent); - - return node; -} -KOALA_INTEROP_2(AstNodeUpdateChildren, KNativePointer, KNativePointer, KNativePointer) - - -std::string __result; -std::size_t __depth; - -static void appendModifiers(es2panda_AstNode *node) { - __depth += 2; - std::size_t kind = GetKind(__context, node); - __result += std::string(__depth, '_'); - __result += "kind: " + std::to_string(kind); - __result += ", mod: " + std::to_string(static_cast(GetImpl()->AstNodeModifiers(__context, node))); - // if (kind == 22) { - // __result += ", script_function_flags: " + std::to_string(GetImpl()->ScriptFunctionFlagsConst(__context, node)); - // } - __result += "\n"; - GetImpl()->AstNodeIterateConst(__context, node, appendModifiers); - __depth -= 2; -} - -KNativePointer impl_AstNodeDumpModifiers( - KNativePointer contextPtr, - KNativePointer nodePtr -) { - auto context = reinterpret_cast(contextPtr); - auto node = reinterpret_cast(nodePtr); - - __context = context; - __result = ""; - __depth = 0; - GetImpl()->AstNodeIterateConst(context, node, appendModifiers); - - return new std::string(__result); -} -KOALA_INTEROP_2(AstNodeDumpModifiers, KNativePointer, KNativePointer, KNativePointer) -/* ------------------------------------------------------------------------------------------------------------------------------ -*/ - - KNativePointer impl_CreateAstDumper( KNativePointer contextPtr, KNativePointer nodePtr, @@ -1273,20 +1088,6 @@ KNativePointer impl_ScriptFunctionSetSignature( } KOALA_INTEROP_3(ScriptFunctionSetSignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_ScriptFunctionSetIrSignature( - KNativePointer contextPtr, - KNativePointer astPtr, - KNativePointer signaturePtr -) { - auto context = reinterpret_cast(contextPtr); - auto ast = reinterpret_cast(astPtr); - auto signature = reinterpret_cast(signaturePtr); - - GetImpl()->ScriptFunctionSetIrSignature(context, ast, signature); - return ast; -} -KOALA_INTEROP_3(ScriptFunctionSetIrSignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer) - KNativePointer impl_ScriptFunctionSetBody( KNativePointer contextPtr, KNativePointer astPtr, @@ -1417,24 +1218,16 @@ KBoolean impl_IdentifierIsPrivateIdentConst(KNativePointer contextPtr, KNativePo } KOALA_INTEROP_2(IdentifierIsPrivateIdentConst, KBoolean, KNativePointer, KNativePointer) -KNativePointer impl_IdentifierSetReference(KNativePointer contextPtr, KNativePointer nodePtr, KBoolean isReferenceK) { - auto context = reinterpret_cast(contextPtr); - auto node = reinterpret_cast(nodePtr); - auto isReference = static_cast(isReferenceK); - - GetImpl()->IdentifierSetReference(context, node, isReference); - return node; -} -KOALA_INTEROP_3(IdentifierSetReference, KNativePointer, KNativePointer, KNativePointer, KBoolean) - -KNativePointer impl_ScriptFunctionUpdateIrSignature(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer signaturePtr) { +KInt impl_IdentifierIdentifierFlags(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); - auto signature = reinterpret_cast(signaturePtr); - return GetImpl()->ScriptFunctionUpdateIrSignature(context, node, signature); + return + (GetImpl()->IdentifierIsOptionalConst(context, node) ? (1 << 0) : 0) | + (GetImpl()->IdentifierIsReferenceConst(context, node, Es2pandaScriptExtension::SCRIPT_EXTENSION_TS) ? (1 << 1) : 0) | + (GetImpl()->IdentifierIsTdzConst(context, node) ? (1 << 2) : 0); } -KOALA_INTEROP_3(ScriptFunctionUpdateIrSignature, KNativePointer, KNativePointer, KNativePointer, KNativePointer) +KOALA_INTEROP_2(IdentifierIdentifierFlags, KInt, KNativePointer, KNativePointer) KNativePointer impl_CreateFunctionExpression(KNativePointer contextPtr, KNativePointer funcPtr) { auto context = reinterpret_cast(contextPtr); @@ -1524,6 +1317,14 @@ KNativePointer impl_AstNodeVariableConst(KNativePointer contextPtr, KNativePoint } KOALA_INTEROP_2(AstNodeVariableConst, KNativePointer, KNativePointer, KNativePointer) +KInt impl_AstNodeTypeConst(KNativePointer contextPtr, KNativePointer nodePtr) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->AstNodeTypeConst(context, node); +} +KOALA_INTEROP_2(AstNodeTypeConst, KInt, KNativePointer, KNativePointer) + KNativePointer impl_VariableDeclaration(KNativePointer contextPtr, KNativePointer variablePtr) { auto context = reinterpret_cast(contextPtr); auto variable = reinterpret_cast(variablePtr); @@ -1587,6 +1388,15 @@ KNativePointer impl_VarBinderSetContext(KNativePointer contextPtr) { } KOALA_INTEROP_1(VarBinderSetContext, KNativePointer, KNativePointer) +KNativePointer impl_VarBinderSetGenStdLib(KNativePointer contextPtr, KBoolean genStdLibT) { + auto context = reinterpret_cast(contextPtr); + auto genStdLib = static_cast(genStdLibT); + + GetImpl()->VarBinderSetGenStdLib(context, genStdLib); + return nullptr; +} +KOALA_INTEROP_2(VarBinderSetGenStdLib, KNativePointer, KNativePointer, KBoolean) + KNativePointer impl_CreateClassDeclaration(KNativePointer contextPtr, KNativePointer defPtr) { auto context = reinterpret_cast(contextPtr); auto def = reinterpret_cast(defPtr); @@ -1618,16 +1428,19 @@ KNativePointer impl_ClassDefinitionSetTypeParams( } KOALA_INTEROP_3(ClassDefinitionSetTypeParams, KNativePointer, KNativePointer, KNativePointer, KNativePointer) -KNativePointer impl_ClassDefinitionLanguageConst( +KNativePointer impl_ClassDefinitionSetSuper( KNativePointer contextPtr, - KNativePointer nodePtr + KNativePointer astPtr, + KNativePointer superClassPtr ) { auto context = reinterpret_cast(contextPtr); - auto node = reinterpret_cast(nodePtr); + auto ast = reinterpret_cast(astPtr); + auto superClass = reinterpret_cast(superClassPtr); - return GetImpl()->ClassDefinitionLanguageConst(context, node); + GetImpl()->ClassDefinitionSetSuper(context, ast, superClass); + return ast; } -KOALA_INTEROP_2(ClassDefinitionLanguageConst, KNativePointer, KNativePointer, KNativePointer) +KOALA_INTEROP_3(ClassDefinitionSetSuper, KNativePointer, KNativePointer, KNativePointer, KNativePointer) KNativePointer impl_ClassDefinitionIdent( KNativePointer contextPtr, @@ -1646,8 +1459,7 @@ KNativePointer impl_CreateClassDefinition1( KNativePointerArray bodyPtr, KInt bodyLenT, KInt modifiersT, - KInt flagsT, - KNativePointer langT + KInt flagsT ) { auto context = reinterpret_cast(contextPtr); auto ident = reinterpret_cast(identPtr); @@ -1655,11 +1467,10 @@ KNativePointer impl_CreateClassDefinition1( auto bodyLen = static_cast(bodyLenT); auto modifiers = Es2pandaClassDefinitionModifiers(modifiersT); auto flags = Es2pandaModifierFlags(flagsT); - auto lang = reinterpret_cast(langT); - return GetImpl()->CreateClassDefinition1(context, ident, body, bodyLen, modifiers, flags, lang); + return GetImpl()->CreateClassDefinition1(context, ident, body, bodyLen, modifiers, flags); } -KOALA_INTEROP_7(CreateClassDefinition1, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KInt, KInt, KNativePointer) +KOALA_INTEROP_6(CreateClassDefinition1, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KInt, KInt) KNativePointer impl_UpdateClassDefinition1( KNativePointer contextPtr, @@ -1668,8 +1479,7 @@ KNativePointer impl_UpdateClassDefinition1( KNativePointerArray bodyPtr, KInt bodyLenT, KInt modifiersT, - KInt flagsT, - KNativePointer langT + KInt flagsT ) { auto context = reinterpret_cast(contextPtr); auto original = reinterpret_cast(originalPtr); @@ -1678,8 +1488,165 @@ KNativePointer impl_UpdateClassDefinition1( auto bodyLen = static_cast(bodyLenT); auto modifiers = Es2pandaClassDefinitionModifiers(modifiersT); auto flags = Es2pandaModifierFlags(flagsT); - auto lang = reinterpret_cast(langT); - return GetImpl()->UpdateClassDefinition1(context, original, ident, body, bodyLen, modifiers, flags, lang); + return GetImpl()->UpdateClassDefinition1(context, original, ident, body, bodyLen, modifiers, flags); +} +KOALA_INTEROP_7(UpdateClassDefinition1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KInt, KInt) + +KNativePointer impl_CreateSuperExpression(KNativePointer contextPtr) { + auto context = reinterpret_cast(contextPtr); + + return GetImpl()->CreateSuperExpression(context); +} +KOALA_INTEROP_1(CreateSuperExpression, KNativePointer, KNativePointer) + +KNativePointer impl_UpdateSuperExpression(KNativePointer contextPtr, KNativePointer originalPtr) { + auto context = reinterpret_cast(contextPtr); + auto original = reinterpret_cast(originalPtr); + + return GetImpl()->UpdateSuperExpression(context, original); +} +KOALA_INTEROP_2(UpdateSuperExpression, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_CreateETSImportDeclaration( + KNativePointer contextPtr, + KNativePointer sourcePtr, + KNativePointerArray specifiersPtr, + KInt specifiersLen, + KInt importKindT +) { + auto context = reinterpret_cast(contextPtr); + auto source = reinterpret_cast(sourcePtr); + auto specifiers = reinterpret_cast(specifiersPtr); + auto importKind = static_cast(importKindT); + + return GetImpl()->CreateETSImportDeclaration(context, source, specifiers, specifiersLen, importKind); +} +KOALA_INTEROP_5(CreateETSImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KInt) + +KNativePointer impl_ETSImportDeclarationSourceConst( + KNativePointer contextPtr, + KNativePointer nodePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->ETSImportDeclarationSourceConst(context, node); +} +KOALA_INTEROP_2(ETSImportDeclarationSourceConst, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_ETSImportDeclarationResolvedSource( + KNativePointer contextPtr, + KNativePointer nodePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->ETSImportDeclarationResolvedSource(context, node); +} +KOALA_INTEROP_2(ETSImportDeclarationResolvedSource, KNativePointer, KNativePointer, KNativePointer) + +KBoolean impl_ETSImportDeclarationHasDeclConst( + KNativePointer contextPtr, + KNativePointer nodePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->ETSImportDeclarationHasDeclConst(context, node); } -KOALA_INTEROP_8(UpdateClassDefinition1, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KInt, KInt, KInt, KNativePointer) +KOALA_INTEROP_2(ETSImportDeclarationHasDeclConst, KBoolean, KNativePointer, KNativePointer) + +KNativePointer impl_CreateImportSource( + KNativePointer contextPtr, + KNativePointer sourcePtr, + KNativePointer resolvedSourcePtr, + KBoolean hasDeclT +) { + auto context = reinterpret_cast(contextPtr); + auto source = reinterpret_cast(sourcePtr); + auto resolvedSource = reinterpret_cast(resolvedSourcePtr); + auto hasDecl = static_cast(hasDeclT); + + return GetImpl()->CreateImportSource(context, source, resolvedSource, hasDecl); +} +KOALA_INTEROP_4(CreateImportSource, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KBoolean) + +KNativePointer impl_CreateImportSpecifier( + KNativePointer contextPtr, + KNativePointer importedPtr, + KNativePointer localPtr +) { + auto context = reinterpret_cast(contextPtr); + auto imported = reinterpret_cast(importedPtr); + auto local = reinterpret_cast(localPtr); + + return GetImpl()->CreateImportSpecifier(context, imported, local); +} +KOALA_INTEROP_3(CreateImportSpecifier, KNativePointer, KNativePointer, KNativePointer, KNativePointer) + + +/* +TODO: NOT FROM API (shouldn't be there) +----------------------------------------------------------------------------------------------------------------------------- +*/ + +es2panda_AstNode * __parentNode; +es2panda_Context * __context; + +static void changeParent(es2panda_AstNode *child) +{ + GetImpl()->AstNodeSetParent(__context, child, __parentNode); +} + +static void SetRightParent(es2panda_AstNode *node, void *arg) +{ + es2panda_Context *ctx = static_cast(arg); + __context = ctx; + __parentNode = node; + + GetImpl()->AstNodeIterateConst(ctx, node, changeParent); +} + +KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer programPtr) { + auto context = reinterpret_cast(contextPtr); + auto program = reinterpret_cast(programPtr); + + GetImpl()->AstNodeForEach(program, SetRightParent, context); + return program; +} +KOALA_INTEROP_2(AstNodeUpdateAll, KNativePointer, KNativePointer, KNativePointer) + +KNativePointer impl_AstNodeUpdateChildren(KNativePointer contextPtr, KNativePointer nodePtr) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + __parentNode = node; + + GetImpl()->AstNodeIterateConst(context, node, changeParent); + return node; +} +KOALA_INTEROP_2(AstNodeUpdateChildren, KNativePointer, KNativePointer, KNativePointer) + +std::vector __children; + +static void visitChild(es2panda_AstNode *node) { + __children.emplace_back(node); +} + +KNativePointer impl_AstNodeChildren( + KNativePointer contextPtr, + KNativePointer nodePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + __context = context; + __children.clear(); + + GetImpl()->AstNodeIterateConst(context, node, visitChild); + return new std::vector(__children); +} +KOALA_INTEROP_2(AstNodeChildren, KNativePointer, KNativePointer, KNativePointer) + +/* +----------------------------------------------------------------------------------------------------------------------------- +*/ diff --git a/arkoala-arkts/libarkts/native/src/node.h b/arkoala-arkts/libarkts/native/src/node.h deleted file mode 100644 index 660aef5ff..000000000 --- a/arkoala-arkts/libarkts/native/src/node.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include -#include - -#ifndef _ARK_TS_NODE_H_ -#define _ARK_TS_NODE_H_ - -class Node { - public: - virtual ~Node() {} - - virtual int kind() { - return 0; - } -}; - -class Identifier : public Node { - public: - std::string name; - - Identifier(std::string&& name) : name(std::move(name)) {} - virtual int kind() { - return 2; - } -}; - -class Block : public Node { - public: - std::vector statements = {}; - - Block(std::vector&& statements) : statements(std::move(statements)) {} - virtual int kind() { - return 3; - } - - Block() {} -}; - -class FunctionDeclaration : public Node { - public: - Identifier* identifier; - Block* block; - - FunctionDeclaration(Identifier* identifier, Block* block) : identifier(identifier), block(block) {} - virtual int kind() { - return 4; - } -}; - -class PropertyAccessExpression: public Node { - public: - Identifier* expression; - Identifier* name; - - PropertyAccessExpression(Identifier* expression, Identifier* name) : expression(expression), name(name) {} - virtual int kind() { - return 5; - } -}; - -class StringLiteral : public Node { - public: - std::string text; - - StringLiteral(std::string&& text) : text(std::move(text)) {} - - virtual int kind() { - return 6; - } -}; - -class CallExpression : public Node { - public: - PropertyAccessExpression* propertyAccessExpression; - std::vector arguments; - - CallExpression(PropertyAccessExpression* propertyAccessExpression, std::vector&& arguments) - : propertyAccessExpression(propertyAccessExpression), arguments(std::move(arguments)) {} - - virtual int kind() { - return 7; - } -}; - -class ExpressionStatement : public Node { - public: - CallExpression* call; - - ExpressionStatement(CallExpression* call) : call(call) {} - - virtual int kind() { - return 8; - } -}; - -class SourceFile : public Node { - public: - std::vector children; - - SourceFile(std::vector&& children) : children(std::move(children)) {} - - virtual int kind() { - return 9; - } -}; - -#endif // _ARK_TS_NODE_H_ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/native/subprojects/node/meson.build b/arkoala-arkts/libarkts/native/subprojects/node/meson.build deleted file mode 100644 index a3b3401b1..000000000 --- a/arkoala-arkts/libarkts/native/subprojects/node/meson.build +++ /dev/null @@ -1,30 +0,0 @@ -project('node', 'cpp', - version: '18.1.0-28-b02', - default_options: ['cpp_std=c++17']) - -oses = { 'emscripten': 'wasm', 'darwin': 'macos' } # rename meson default names to covienient ones -archs = { 'x86_64': 'x64', 'aarch64': 'arm64', 'wasm32': 'wasm' } - -os = target_machine.system() -os = oses.get(os, os) - -arch = target_machine.cpu() -arch = archs.get(arch, arch) - -buildtype = '@0@-@1@-@2@'.format(get_option('build_type'), os, arch) - -fs = import('fs') - -node_addon_api = run_command('node', '-p', 'require.resolve("node-addon-api/package.json").slice(0, -12)', check: true).stdout().strip() -node_api_headers = run_command('node', '-p', 'require.resolve("node-api-headers/package.json").slice(0, -12)', check: true).stdout().strip() - -node_include_dirs = [ - node_api_headers / 'include', - node_addon_api, -] - -summary({ - 'Node addon API': node_addon_api, - 'Node API headers': node_api_headers, - 'Build type': buildtype, -}) diff --git a/arkoala-arkts/libarkts/native/subprojects/node/meson_options.txt b/arkoala-arkts/libarkts/native/subprojects/node/meson_options.txt deleted file mode 100644 index c9c2de160..000000000 --- a/arkoala-arkts/libarkts/native/subprojects/node/meson_options.txt +++ /dev/null @@ -1,6 +0,0 @@ -option('node_dir', type : 'string', value : '', - description : 'Path to NodeJS headers/libs prebuilt') -option('version', type: 'string', value: '', - description: 'NodeJS prebuilt package version to link with') -option('build_type', type : 'combo', choices : ['debug', 'release'], value: 'release', - description: 'NodeJS prebuilt package build variant to link with') \ No newline at end of file diff --git a/arkoala-arkts/libarkts/package.json b/arkoala-arkts/libarkts/package.json index c910549a1..bd7e99366 100644 --- a/arkoala-arkts/libarkts/package.json +++ b/arkoala-arkts/libarkts/package.json @@ -1,36 +1,35 @@ { - "name": "libarkts", + "name": "@koalaui/libarkts", + "private": true, + "main": "./build/es2panda.js", + "types": "./build/src/ts-api/index.d.ts", "dependencies": { - "node-api-headers": "0.0.5", - "node-addon-api": "8.0.0", - "commander": "^11.1.0" - }, - "devDependencies": { - "@koalaui/plugin-api-panda-sdk": "1.0.5", "@types/chai": "^4.3.1", "@types/mocha": "^9.1.0", - "chai": "^4.3.6", + "commander": "10.0.1", "mocha": "^9.2.2", + "node-addon-api": "8.0.0", + "node-api-headers": "0.0.5", + "node-loader": "^2.1.0", + "ts-loader": "^9.2.8", "tsconfig-paths-webpack-plugin": "^4.1.0", - "typescript": "4.9.5", - "webpack-cli": "^5.1.4", - "ts-loader": "^9.2.8" + "typescript": "4.9.5" }, "scripts": { - "clean": "rimraf build node_modules && npm run clean:native && npm run clean:compatible", - "clean:native": "rimraf native/build_es2panda", - "clean:compatible": "rimraf compatible/build compatible/build_typescript compatible/build_arkts", + "clean": "rimraf ./build && npm run clean:native && npm run clean:compatible", + "clean:native": "rimraf ./native/build", + "clean:compatible": "rimraf ./compatible/build", + "clean:generated": "rimraf ./generated/*", + "compile:playground": "cd playground && meson setup build && cd build && meson compile", + "run:playground": "npm run compile:playground && cd playground && ./build/playground.out", "compile:koala:interop": "cd ../../interop && npm run compile", - "compile:native": "cd native && meson setup build_es2panda && cd build_es2panda && meson compile", - "compile": "npm run compile:koala:interop && npm run compile:native", - "test": "npm run compile && backend=es2panda TS_NODE_PROJECT=./test/tsconfig.json mocha -r tsconfig-paths/register --config .mocha.json --reporter-option maxDiffSize=0", - "test:all": "STATE_CHECKED=1 TEST_BIN=1 npm run test", - "compatible": "cd compatible && npx webpack --config arkts.webpack.config.js", - "webpack": "npm run compile && npm run compatible && npx webpack --config es2panda.webpack.config.js", - "run:dev": "npm run run && backend=es2panda node build/api/es2panda.js", - "run": "npm run webpack && node build/api/es2panda.js --file ./input/main.sts --arktsconfig ./arktsconfig.json", - "run:typescript": "npm run compatible && cd input && memo-tsc -p ./tsconfig.json", - "run:debug": "npm run compile:native && cd native && ./build_es2panda/playground_exec", - "run:abc": "./node_modules/@koalaui/plugin-api-panda-sdk/@panda/sdk/linux_host_tools/bin/ark --load-runtimes=ets --boot-panda-files=./node_modules/@koalaui/plugin-api-panda-sdk/@panda/sdk/ets/etsstdlib.abc ./native/main.abc ETSGLOBAL::main" + "compile:native": "npm run compile:koala:interop && cd native && meson setup build && cd build && meson compile", + "run": "npm run pack:es2panda && node build/api/es2panda.js --file ./input/main.sts --arktsconfig ./arktsconfig.json", + "run:abc": "node_modules/@panda/sdk/linux_host_tools/bin/ark --load-runtimes=ets --boot-panda-files=node_modules/@panda/sdk/ets/etsstdlib.abc ./generated/main.abc ETSGLOBAL::main", + "run:dev": "npm run run && node build/api/es2panda.js", + "pack:compatible": "npx memo-tsc -p ./compatible/arkts-tsconfig.json", + "pack:es2panda": "npm run compile:native && npm run pack:compatible && npx webpack --config webpack.config.js", + "test": "npm run compile:native && TS_NODE_PROJECT=./test/tsconfig.json mocha -r tsconfig-paths/register --config .mocha.json --reporter-option maxDiffSize=0", + "test:all": "STATE_CHECKED=1 TEST_BIN=1 npm run test" } } diff --git a/arkoala-arkts/libarkts/playground/meson.build b/arkoala-arkts/libarkts/playground/meson.build new file mode 100644 index 000000000..e70cb0ad8 --- /dev/null +++ b/arkoala-arkts/libarkts/playground/meson.build @@ -0,0 +1,31 @@ +project('playground', 'cpp', + version: '1.0', + default_options: [ + 'cpp_std=c++17', + 'buildtype=debug', + ], +) + +cflags = [ + '-DKOALA_USE_NODE_VM', + '-DKOALA_NAPI' +] + +if target_machine.system() == 'windows' + cflags += ['-DKOALA_WINDOWS'] +else + cflags += ['-DKOALA_LINUX'] +endif + +executable( + 'playground.out', + [ + './src/playground.cc', + ], + include_directories: [ + get_option('panda_sdk_dir') / 'ohos_arm64/include/tools/es2panda/public', + get_option('panda_sdk_dir') / 'ohos_arm64/include/tools/es2panda', + get_option('interop_src_dir'), + ], + cpp_args: cflags +) diff --git a/arkoala-arkts/libarkts/playground/meson_options.txt b/arkoala-arkts/libarkts/playground/meson_options.txt new file mode 100644 index 000000000..98f27a075 --- /dev/null +++ b/arkoala-arkts/libarkts/playground/meson_options.txt @@ -0,0 +1,4 @@ +option('panda_sdk_dir', type : 'string', value : '../node_modules/@panda/sdk/', + description : 'path to panda sdk') +option('interop_src_dir', type : 'string', value : '../../../interop/src/cpp/', + description : 'path to interop_src') diff --git a/arkoala-arkts/libarkts/native/src/playground.cc b/arkoala-arkts/libarkts/playground/src/playground.cc similarity index 90% rename from arkoala-arkts/libarkts/native/src/playground.cc rename to arkoala-arkts/libarkts/playground/src/playground.cc index 49e0785e3..2b05c0e94 100644 --- a/arkoala-arkts/libarkts/native/src/playground.cc +++ b/arkoala-arkts/libarkts/playground/src/playground.cc @@ -3,7 +3,13 @@ #include "dynamic-loader.h" #include "es2panda_lib.h" -const char* libpath = "../node_modules/@koalaui/plugin-api-panda-sdk/@panda/sdk/linux_host_tools/lib/libes2panda-public.so"; +#ifdef __x86_64__ + #define PLUGIN_DIR "linux_host_tools" +#else + #define PLUGIN_DIR "linux_arm64_host_tools" +#endif + +const char* libpath = "../node_modules/@panda/sdk/" PLUGIN_DIR "/lib/libes2panda-public.so"; static es2panda_Impl *impl = nullptr; @@ -23,7 +29,12 @@ es2panda_Impl *GetImpl() { return impl; } -static const char* source = ""; +static const char* source = +"" +; + +void test(es2panda_Context* context) { +} int main() { const char* args[] = { @@ -39,8 +50,6 @@ int main() { auto config = GetImpl()->CreateConfig(4, args); auto context = GetImpl()->CreateContextFromString(config, source, args[3]); - // playground - GetImpl()->ProceedToState(context, ES2PANDA_STATE_PARSED); if(GetImpl()->ContextState(context) == ES2PANDA_STATE_ERROR) { @@ -51,6 +60,8 @@ int main() { std::cout << "PROCEED TO PARSE SUCCESS" << std::endl; } + test(context); + GetImpl()->ProceedToState(context, ES2PANDA_STATE_SCOPE_INITED); if(GetImpl()->ContextState(context) == ES2PANDA_STATE_ERROR) { diff --git a/arkoala-arkts/libarkts/src/NativeModule.ts b/arkoala-arkts/libarkts/src/NativeModule.ts deleted file mode 100644 index 174909f1c..000000000 --- a/arkoala-arkts/libarkts/src/NativeModule.ts +++ /dev/null @@ -1,197 +0,0 @@ -/* - * 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 { KBoolean, KInt, KNativePointer } from "@koalaui/interop" -import * as path from "path" - -export type KNativePointerArray = BigUint64Array - -export interface NativeModule { - _ContextState(context: KNativePointer): KInt - _ContextErrorMessage(context: KNativePointer): KNativePointer - _ETSParserCreateExpression(context: KNativePointer, sourceCode: String, flags: KInt): KNativePointer - _AstNodeDumpModifiers(context: KNativePointer, node: KNativePointer): KNativePointer - _CreateAstDumper(context: KNativePointer, node: KNativePointer, source: String): KNativePointer - _AstDumperModifierToString(context: KNativePointer, dumper: KNativePointer, flags: KInt): KNativePointer - - _CreateConfig(argc: number, argv: string[]): KNativePointer - _DestroyConfig(config: KNativePointer): void - _CreateContextFromString(config: KNativePointer, source: String, filename: String): KNativePointer - _DestroyContext(context: KNativePointer): void - _ProceedToState(context: KNativePointer, state: number): void - _ContextProgram(context: KNativePointer): KNativePointer - _ProgramAst(program: KNativePointer): KNativePointer - _CheckerStartChecker(context: KNativePointer): KBoolean - _VarBinderIdentifierAnalysis(context: KNativePointer): void - _VarBinderInitTopScope(context: KNativePointer): void - - _StringLength(ptr: KNativePointer): KInt - _StringData(ptr: KNativePointer, buffer: KNativePointer, length: KInt): void - _GetStringFinalizer(): KNativePointer - _InvokeFinalizer(ptr: KNativePointer, finalizer: KNativePointer): void - _GetPtrVectorSize(ptr: KNativePointer): KInt - _GetPtrVectorElement(ptr: KNativePointer, index: KInt): KNativePointer - - _SourceFileGetChildren(node: KNativePointer): KNativePointer - _BlockGetStatements(node: KNativePointer): KNativePointer - _FunctionDeclarationIsAnonymousConst(context: KNativePointer, node: KNativePointer): KBoolean - _ExpressionStatementGetExpression(context: KNativePointer, node: KNativePointer): KNativePointer - _CallExpressionArguments(context: KNativePointer, node: KNativePointer, returnLen: KNativePointer): KNativePointer - _CallExpressionCallee(context: KNativePointer, node: KNativePointer): KNativePointer - _IdentifierGetText(node: KNativePointer): KNativePointer - _IdentifierIsPrivateIdentConst(context: KNativePointer, node: KNativePointer): KBoolean - _PropertyAccessExpressionGetExpression(node: KNativePointer): KNativePointer - _PropertyAccessExpressionGetName(node: KNativePointer): KNativePointer - - _FunctionDeclarationFunction(context: KNativePointer, node: KNativePointer): KNativePointer - _ScriptFunctionSignature(context: KNativePointer, node: KNativePointer): KNativePointer - _ScriptFunctionParams(context: KNativePointer, node: KNativePointer): KNativePointer - _ScriptFunctionId(context: KNativePointer, node: KNativePointer): KNativePointer - _ScriptFunctionBody(context: KNativePointer, node: KNativePointer): KNativePointer - _ScriptFunctionSetIdent(context: KNativePointer, ast: KNativePointer, id: KNativePointer): KNativePointer - _ScriptFunctionIrSignature(context: KNativePointer, ast: KNativePointer): KNativePointer - _ScriptFunctionUpdateIrSignature(context: KNativePointer, ast: KNativePointer, signature: KNativePointer): KNativePointer - _ScriptFunctionSetSignature(context: KNativePointer, ast: KNativePointer, signature: KNativePointer): KNativePointer - _ScriptFunctionSetIrSignature(context: KNativePointer, ast: KNativePointer, signature: KNativePointer): KNativePointer - _ScriptFunctionSetBody(context: KNativePointer, ast: KNativePointer, body: KNativePointer): KNativePointer - _ScriptFunctionSetScope(context: KNativePointer, ast: KNativePointer, scope: KNativePointer): KNativePointer - _ScriptFunctionDeclareConst(context: KNativePointer, node: KNativePointer): KBoolean - _ScriptFunctionFlagsConst(context: KNativePointer, node: KNativePointer): KInt - _ScriptFunctionTypeParams(context: KNativePointer, node: KNativePointer): KNativePointer - _ScriptFunctionReturnTypeAnnotation(context: KNativePointer, node: KNativePointer): KNativePointer - _UpdateBlockStatement(context: KNativePointer, original: KNativePointer, statementList: KNativePointerArray, statementListLen: KInt): KNativePointer - _BlockStatementSetScope(context: KNativePointer, node: KNativePointer, scope: KNativePointerArray): void - _CreateIdentifier1(context: KNativePointer, name: String): KNativePointer - _CreateIdentifier2(context: KNativePointer, name: String, type_annotation: KNativePointer): KNativePointer - _IdentifierSetReference(context: KNativePointer, node: KNativePointer, isRef: KBoolean): void - _IdentifierSetName(context: KNativePointer, node: KNativePointer, name: String): void - _CreateFunctionDeclaration(context: KNativePointer, func: KNativePointer, isAnon: KBoolean): KNativePointer - _UpdateFunctionDeclaration(context: KNativePointer, node: KNativePointer, func: KNativePointer, isAnon: KBoolean): KNativePointer - _CreateReturnStatement1(context: KNativePointer, argument: KNativePointer): KNativePointer - _ReturnStatementArgument(context: KNativePointer, node: KNativePointer): KNativePointer - _CreateIfStatement(context: KNativePointer, test: KNativePointer, consequent: KNativePointer, alternate: KNativePointer): KNativePointer - _CreateBinaryExpression(context: KNativePointer, left: KNativePointer, right: KNativePointer, operatorType: KInt): KNativePointer - _CreateAssignmentExpression(context: KNativePointer, left: KNativePointer, right: KNativePointer, assignmentOperator: KInt): KNativePointer - _CreateMethodDefinition(context: KNativePointer, kind: KInt, key: KNativePointer, value: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer - _CreateClassProperty(context: KNativePointer, key: KNativePointer, value: KNativePointer, typeAnnotation: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer - - _CreateFunctionSignature(context: KNativePointer, typeParams: KNativePointer, params: KNativePointerArray, paramsLen: KInt, returnTypeAnnotation: KNativePointer): KNativePointer - _CreateScriptFunction(context: KNativePointer, databody: KNativePointer, datasignature: KNativePointer, datafuncFlags: KInt, dataflags: KInt, datadeclare: KBoolean): KNativePointer - _UpdateScriptFunction(context: KNativePointer, original: KNativePointer, databody: KNativePointer, datasignature: KNativePointer, datafuncFlags: KInt, dataflags: KInt, datadeclare: KBoolean): KNativePointer - _CreateBlockStatement(context: KNativePointer, statementList: KNativePointerArray, statementListLen: KInt): KNativePointer - _AstNodeScopeConst(context: KNativePointer, ast: KNativePointer): KNativePointer - _AstNodeParent(context: KNativePointer, ast: KNativePointer): KNativePointer - _AstNodeSetParent(context: KNativePointer, ast: KNativePointer, parent: KNativePointer): KNativePointer - _AstNodeClone(context: KNativePointer, ast: KNativePointer, parent: KNativePointer): KNativePointer - _AstNodeModifiers(context: KNativePointer, ast: KNativePointer): KInt - _AstNodeAddModifier(context: KNativePointer, ast: KNativePointer, flags: KInt): void - _AstNodeClearModifier(context: KNativePointer, ast: KNativePointer, flags: KInt): void - _AstNodeVariableConst(context: KNativePointer, ast: KNativePointer): KNativePointer - _FunctionSignatureTypeParams(context: KNativePointer, ast: KNativePointer): KNativePointer - _FunctionSignatureReturnType(context: KNativePointer, ast: KNativePointer): KNativePointer - _FunctionSignatureParamsConst(context: KNativePointer, ast: KNativePointer, returnTypeLen: KNativePointer): KNativePointer - _UpdateIdentifier1(context: KNativePointer, ast: KNativePointer, name: string): KNativePointer - _UpdateIdentifier2(context: KNativePointer, ast: KNativePointer, name: string, typeAnnotation: KNativePointer): KNativePointer - _UpdateMethodDefinition(context: KNativePointer, node: KNativePointer, kind: KInt, key: KNativePointer, value: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer - _MethodDefinitionFunction(context: KNativePointer, node: KNativePointer): KNativePointer - _MethodDefinitionKindConst(context: KNativePointer, node: KNativePointer): KInt - - _CreateMemberExpression(context: KNativePointer, object: KNativePointer, property: KNativePointer, kind: KInt, computed: KBoolean, optional: KBoolean): KNativePointer - _UpdateMemberExpression(context: KNativePointer, node: KNativePointer, object: KNativePointer, property: KNativePointer, kind: KInt, computed: KBoolean, optional: KBoolean): KNativePointer - _MemberExpressionObject(context: KNativePointer, node: KNativePointer): KNativePointer - _MemberExpressionProperty(context: KNativePointer, node: KNativePointer): KNativePointer - _CreateCallExpression(context: KNativePointer, callee: KNativePointer, args: KNativePointerArray, argsLen: KInt, typeParams: KNativePointer, optional: KBoolean, trailingComma: KBoolean): KNativePointer - _UpdateCallExpression(node: KNativePointer, context: KNativePointer, callee: KNativePointer, args: KNativePointerArray, argsLen: KInt, typeParams: KNativePointer, optional: KBoolean, trailingComma: KBoolean): KNativePointer - _CreateArrowFunctionExpression(context: KNativePointer, node: KNativePointer): KNativePointer - _FunctionExpressionFunction(context: KNativePointer, node: KNativePointer): KNativePointer - _ArrowFunctionExpressionFunction(context: KNativePointer, node: KNativePointer): KNativePointer - _ArrowFunctionExpressionCreateTypeAnnotation(context: KNativePointer, node: KNativePointer): KNativePointer - _CreateFunctionExpression(context: KNativePointer, node: KNativePointer): KNativePointer - _UpdateFunctionExpression(context: KNativePointer, original: KNativePointer, node: KNativePointer): KNativePointer - - _CreateExpressionStatement(context: KNativePointer, expr: KNativePointer): KNativePointer - _UpdateExpressionStatement(context: KNativePointer, node: KNativePointer, expr: KNativePointer): KNativePointer - _CreateETSParameterExpression(context: KNativePointer, identifier: KNativePointer, initializer: KNativePointer): KNativePointer - _CreateETSPrimitiveType(context: KNativePointer, type: KInt): KNativePointer - _CreateETSTypeReference(context: KNativePointer, part: KNativePointer): KNativePointer - _CreateETSTypeReferencePart(context: KNativePointer, name: KNativePointer, typeParams: KNativePointer, prev: KNativePointer): KNativePointer - _CreateETSTypeReferencePart1(context: KNativePointer, name: KNativePointer): KNativePointer - _IsIdentifier(node: KNativePointer): KBoolean - _IdentifierName(context: KNativePointer, node: KNativePointer): KNativePointer - _ETSParameterExpressionIdent(context: KNativePointer, node: KNativePointer): KNativePointer - _CreateTSTypeParameterDeclaration(context: KNativePointer, params: KNativePointerArray, paramsLen: KInt, requiredParams: KInt): KNativePointer - _TSTypeParameterDeclarationParamsConst(context: KNativePointer, node: KNativePointer, returnTypeLen: KNativePointer): KNativePointer - _CreateTSTypeParameter(context: KNativePointer, name: KNativePointer, constraint: KNativePointer, defaultType: KNativePointer): KNativePointer - _TSTypeParameterName(context: KNativePointer, node: KNativePointer): KNativePointer - - _CreateTSUnionType(context: KNativePointer, types: KNativePointerArray, typesLen: KInt): KNativePointer - _TSUnionTypeTypesConst(context: KNativePointer, node: KNativePointer, returnTypeLen: KNativePointer): KNativePointer - _CreateETSUnionTypeIr(context: KNativePointer, types: KNativePointerArray, typesLen: KInt): KNativePointer - _ETSUnionTypeIrTypesConst(context: KNativePointer, node: KNativePointer, returnTypeLen: KNativePointer): KNativePointer - - _CreateVariableDeclaration(context: KNativePointer, kind: KInt, declarators: KNativePointerArray, declaratorsLen: KInt, declare: KBoolean): KNativePointer - _UpdateVariableDeclaration(context: KNativePointer, original: KNativePointer, kind: KInt, declarators: KNativePointerArray, declaratorsLen: KInt, declare: KBoolean): KNativePointer - _CreateVariableDeclarator(context: KNativePointer, flag: KInt, ident: KNativePointer): KNativePointer - _VariableDeclarationDeclaratorsConst(context: KNativePointer, node: KNativePointer): KNativePointer - _VariableDeclaratorId(context: KNativePointer, node: KNativePointer): KNativePointer - _VariableDeclaratorSetInit(context: KNativePointer, node: KNativePointer, init: KNativePointer): void - - _CreateStringLiteral(context: KNativePointer, string: string): KNativePointer - _CreateNumberLiteral(context: KNativePointer, string: string): KNativePointer - _NumberLiteralStrConst(context: KNativePointer, node: KNativePointer): KNativePointer - _StringLiteralStrConst(context: KNativePointer, node: KNativePointer): KNativePointer - - _GetKind(context: KNativePointer, node: KNativePointer): KInt - - _BlockStatementStatements(context: KNativePointer, node: KNativePointer): KNativePointer - _BlockStatementSetStatements(context: KNativePointer, node: KNativePointer, statements: KNativePointerArray, statementsLen: KInt): void - _BlockStatementUpdateStatements(context: KNativePointer, original: KNativePointer, statementList: KNativePointerArray, statementListLen: KInt, returnType: KNativePointer): KNativePointer - _ClassDeclarationDefinition(context: KNativePointer, node: KNativePointer): KNativePointer - _ClassDefinitionBody(context: KNativePointer, node: KNativePointer): KNativePointer - _ClassDefinitionLanguageConst(context: KNativePointer, node: KNativePointer): KNativePointer - _ClassDefinitionIdent(context: KNativePointer, node: KNativePointer): KNativePointer - _ClassDefinitionTypeParamsConst(context: KNativePointer, node: KNativePointer): KNativePointer - _CreateClassDeclaration(context: KNativePointer, def: KNativePointer): KNativePointer - _UpdateClassDeclaration(context: KNativePointer, original: KNativePointer, def: KNativePointer): KNativePointer - _CreateClassDefinition1(context: KNativePointer, ident: KNativePointer, body: KNativePointerArray, bodyLen: KInt, modifiers: KInt, flags: KInt, lang: KNativePointer): KNativePointer - _ClassDefinitionSetTypeParams(context: KNativePointer, ast: KNativePointer, typeParams: KNativePointer): void - _UpdateClassDefinition1(context: KNativePointer, original: KNativePointer, ident: KNativePointer, body: KNativePointerArray, bodyLen: KInt, modifiers: KInt, flags: KInt, lang: KNativePointer): KNativePointer - _CreateETSFunctionTypeIr(context: KNativePointer, signature: KNativePointer, funcFlags: KInt): KNativePointer - - _IsProgram(context: KNativePointer, node: KNativePointer): KBoolean - _AstNodeDumpJsonConst(context: KNativePointer, node: KNativePointer): KNativePointer - _AstNodeDumpEtsSrcConst(context: KNativePointer, node: KNativePointer): KNativePointer - _AstNodeUpdateChildren(context: KNativePointer, node: KNativePointer): void - _AstNodeUpdateAll(context: KNativePointer, node: KNativePointer): void - _AstNodeSetOriginalNode(context: KNativePointer, ast: KNativePointer, originalNode: KNativePointer): void - _AstNodeOriginalNodeConst(context: KNativePointer, ast: KNativePointer): KNativePointer - - _VarBinderSetProgram(context: KNativePointer): void - _VarBinderSetContext(context: KNativePointer): void - - _VariableDeclaration(context: KNativePointer, variable: KNativePointer): KNativePointer - _DeclNode(context: KNativePointer, decl: KNativePointer): KNativePointer - - _ScopeSetParent(context: KNativePointer, ast: KNativePointer, scope: KNativePointer): void -} - -const backend = process.env.backend ?? 'es2panda' - -const libarkts = 'libarkts' -const filename = __filename -const occurrence = filename.indexOf(libarkts) -const root = filename.slice(0, occurrence + libarkts.length) -const importPath = path.join(root, 'native', `build_${backend}`, 'Es2panda.node') -export const nativeModule: NativeModule = require(/* webpackIgnore: true */ importPath) diff --git a/arkoala-arkts/libarkts/src/api/factory/utilities.ts b/arkoala-arkts/libarkts/src/api/factory/utilities.ts deleted file mode 100644 index 8d62af9c0..000000000 --- a/arkoala-arkts/libarkts/src/api/factory/utilities.ts +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 "../static/global" -import * as ts from "../layers/ts/types" -import * as arkts from "../layers/arkts/types" - -import { nativeModule } from "../../NativeModule" -import { KNativePointer, KInt, KBoolean } from "@koalaui/interop" -import { - TokenSyntaxKind, - Es2pandaModifierFlags, - Es2pandaScriptFunctionFlags, -} from "../static/enums" -import { - passNodeArray, -} from "../layers/ts/utilities" - -// export function updateAllChildren(peer: KNativePointer) { -// nativeModule._AstNodeUpdateAll(global.context, peer) -// } - -// TODO: support unrequired params (with ?) -export function passTypeParams(params: readonly ts.TypeParameterDeclaration[] | undefined): arkts.TSTypeParameterDeclaration | undefined { - if (params === undefined) { - return undefined - } - return arkts.TSTypeParameterDeclaration.create( - passNodeArray(params) - ) -} - -// export function identifierUpdateTypeAnnotation(node: arkts.Identifier, type: arkts.TypeNode | undefined): arkts.Identifier { -// const peer = withString(node.text, (_text: string) => { -// return nativeModule._UpdateIdentifier2(global.context, node.peer, _text, type?.peer ?? arkts.NULLPTR) -// }) -// return new arkts.Identifier(node.text, type?.node) -// } diff --git a/arkoala-arkts/libarkts/src/api/layers/arkts/utilities.ts b/arkoala-arkts/libarkts/src/api/layers/arkts/utilities.ts deleted file mode 100644 index 52ab99579..000000000 --- a/arkoala-arkts/libarkts/src/api/layers/arkts/utilities.ts +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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 arkts from "./types" -import global from "../../static/global" - -import { KNativePointer, withString, fromPtrArray, withStringResult, withStringArray } from "@koalaui/interop" -import { nativeModule } from "../../../NativeModule" -import { NativePtrDecoder } from "../../../node/Platform" -import { - es2pandaKind, - Es2pandaScriptFunctionFlags, -} from "../../static/enums" - -export function classByPeer(peer: KNativePointer): { new (peer: KNativePointer): arkts.Node } { - const kinds = - new Map([ - // [es2pandaKind.UnsupportedNode, ets.UnsupportedNode], - - [es2pandaKind.Program, arkts.Program], - [es2pandaKind.Identifier, arkts.Identifier], - [es2pandaKind.StringLiteral, arkts.StringLiteral], - [es2pandaKind.NumberLiteral, arkts.NumberLiteral], - [es2pandaKind.ExpressionStatement, arkts.ExpressionStatement], - [es2pandaKind.FunctionDeclaration, arkts.FunctionDeclaration], - [es2pandaKind.ScriptFunction, arkts.ScriptFunction], - [es2pandaKind.Block, arkts.Block], - [es2pandaKind.ReturnStatement, arkts.ReturnStatement], - [es2pandaKind.ETSParameterExpression, arkts.ETSParameterExpression], - [es2pandaKind.ETSTypeReference, arkts.ETSTypeReference], - [es2pandaKind.TSTypeParameterDeclaration, arkts.TSTypeParameterDeclaration], - [es2pandaKind.ETSPrimitiveType, arkts.ETSPrimitiveType], - [es2pandaKind.CallExpression, arkts.CallExpression], - [es2pandaKind.MemberExpression, arkts.MemberExpression], - [es2pandaKind.TSTypeParameter, arkts.TSTypeParameter], - [es2pandaKind.IfStatement, arkts.IfStatement], - [es2pandaKind.BinaryExpression, arkts.BinaryExpression], - [es2pandaKind.ETSUnionType, arkts.ETSUnionType], - [es2pandaKind.ArrowFunctionExpression, arkts.ArrowFunctionExpression], - [es2pandaKind.ClassDeclaration, arkts.ClassDeclaration], - [es2pandaKind.ClassDefinition, arkts.ClassDefinition], - [es2pandaKind.MethodDefinition, arkts.MethodDefinition], - [es2pandaKind.ClassProperty, arkts.ClassProperty], - [es2pandaKind.AssignmentExpression, arkts.AssignmentExpression], - ]) - - const kind = nativeModule._GetKind(global.context, peer) - return kinds.get(kind) ?? global.throwError(`UNSUPPORTED NODE (arkts): ${es2pandaKind[kind]}`) -} - -export function unpackNonNullableNode(peer: KNativePointer): T { - if (peer === arkts.NULLPTR) { - global.throwError('peer is NULLPTR (maybe you should use unpackNode)') - } - return (new (classByPeer(peer))(peer)) as T -} - -export function unpackNode(peer: KNativePointer): T | undefined { - if (peer === arkts.NULLPTR) { - return undefined - } - return (new (classByPeer(peer))(peer)) as T -} - -export function passNode(node: arkts.Node | undefined): KNativePointer { - return node?.peer ?? arkts.NULLPTR -} - -// meaning unpackNonNullableNodeArray -export function unpackNodeArray(nodesPtr: KNativePointer): readonly T[] { - if (nodesPtr === arkts.NULLPTR) { - global.throwError('nodesPtr is NULLPTR (maybe you should use unpackNodeArray)') - } - const array = (new NativePtrDecoder).decode(nodesPtr) - - return fromPtrArray(array, (peer: KNativePointer) => { - return unpackNonNullableNode(peer) - }) -} - -export function passNodeArray(nodes: readonly arkts.Node[] | undefined): BigUint64Array { - return new BigUint64Array((nodes === undefined) ? [] : nodes.map(node => BigInt(node.peer))) -} - -export function unpackObject(type: { new (peer: KNativePointer): T }, peer: KNativePointer): T | undefined { - if (peer === arkts.NULLPTR) { - return undefined - } - return new type(peer) -} - -export function unpackString(peer: KNativePointer): string { - return withStringResult(peer) ?? global.throwError(`failed to unpack (peer shouldn't be NULLPTR)`) -} - -export function passString(str: string | undefined): string { - if (str === undefined) { - return "" - } - return withString(str, (_str: string) => _str) -} - -export function passStringArray(strs: string[]): string[] { - return withStringArray(strs, (_strs: string[]) => _strs) -} - -export function scriptFunctionHasBody(peer: KNativePointer): boolean { - const flags = nativeModule._ScriptFunctionFlagsConst(global.context, peer) - return true - && ((flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL) === 0) - && ((flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL_OVERLOAD) === 0) -} - -// TODO: update scopes and other data -export function updateNode(node: T, original: T): T { - if (node.peer === arkts.NULLPTR) { - global.throwError('updateNode called on NULLPTR') - } - nativeModule._AstNodeSetOriginalNode(global.context, node.peer, original.peer) - nativeModule._AstNodeSetParent(global.context, node.peer, nativeModule._AstNodeParent(global.context, original.peer)) - nativeModule._AstNodeUpdateChildren(global.context, node.peer) - node.modifiers = original.modifiers - // new flags may change children - node.updateChildren() - // switch (classByPeer(peer)) { - // case arkts.ClassDeclaration: { - // // TODO: update Language - // break - // } - // } - return node -} - -// export function updateNodeModifiers(node: T, modifiers: ReadonlyArray | undefined): T { -// // node.modifiers = modifiers -// return node -// } - -// export function updateModifiers(peer: KNativePointer, modifiers: ReadonlyArray | undefined): KNativePointer { -// if (modifiers === undefined) { -// return peer -// } -// setModifierFlags(peer, packModifiers(modifiers)) -// return peer -// } diff --git a/arkoala-arkts/libarkts/src/api/static/global.ts b/arkoala-arkts/libarkts/src/api/static/global.ts deleted file mode 100644 index f5d4a0b11..000000000 --- a/arkoala-arkts/libarkts/src/api/static/global.ts +++ /dev/null @@ -1,148 +0,0 @@ -/* - * 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 { KNativePointer } from "@koalaui/interop" -import { - SyntaxKind, - TokenSyntaxKind, - Es2pandaScriptFunctionFlags, - Es2pandaTokenType, - Es2pandaModifierFlags, -} from "./enums" -import * as arkts from "../layers/ts/types" - -// TODO: -// type ModifierKinds = arkts.ModifierSyntaxKind | SyntaxKind.UnknownKeyword | SyntaxKind.ConstructorKeyword - -export default class global { - static throwError(error: string): never { - throw new Error(error) - } - - private static _config?: KNativePointer - public static set config(config: KNativePointer) { - if (global._config !== undefined) { - throw new Error('Global.config already initialized') - } - global._config = config - } - public static get config(): KNativePointer { - return global._config ?? global.throwError('Global.config not initialized') - } - - public static isInitializedConfig(): boolean { - return (global._config !== undefined) - } - - private static _context?: KNativePointer - public static set context(context: KNativePointer) { - global._context = context - } - public static get context(): KNativePointer { - return global._context ?? global.throwError('Global.context not initialized') - } - - public static isInitializedContext(): boolean { - return (global._context !== undefined) - } - - private static _tokenKinds?: Map - - public static get tokenKinds(): Map { - if (this._tokenKinds === undefined) { - this._tokenKinds = - new Map([ - [SyntaxKind.PlusToken, Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS], - ]) - } - return this._tokenKinds - } - - private static _scriptFunctionFlags?: Map - - public static get scriptFunctionFlags(): Map { - if (this._scriptFunctionFlags === undefined) { - this._scriptFunctionFlags = - new Map([ - [SyntaxKind.StaticKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_STATIC_BLOCK], - [SyntaxKind.AsyncKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC], - [SyntaxKind.PublicKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE], - ]) - } - return this._scriptFunctionFlags - } - - private static _modifierFlags?: Map - - public static get modifierFlags(): Map { - if (this._modifierFlags === undefined) { - this._modifierFlags = - new Map([ - // [SyntaxKind.UnknownKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_NONE], - // [SyntaxKind.ConstructorKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR], - - [SyntaxKind.AbstractKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT], - // TODO: unsupported - // [SyntaxKind.AccessorKeyword, Es2pandaModifierFlags.], - [SyntaxKind.AsyncKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_ASYNC], - [SyntaxKind.ConstKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_CONST], - [SyntaxKind.DeclareKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE], - [SyntaxKind.DefaultKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_DEFAULT_EXPORT], - [SyntaxKind.ExportKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT], - [SyntaxKind.InKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_IN], - [SyntaxKind.PrivateKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE], - [SyntaxKind.ProtectedKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_PROTECTED], - [SyntaxKind.PublicKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC], - [SyntaxKind.OutKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_OUT], - [SyntaxKind.OverrideKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE], - [SyntaxKind.ReadonlyKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_READONLY], - [SyntaxKind.StaticKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC], - ]) - } - return this._modifierFlags - } - - private static _translateModifiers?: Map - - public static get translateModifiers(): Map { - if (this._translateModifiers === undefined) { - this._translateModifiers = - new Map([ - // [Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, SyntaxKind.UnknownKeyword], - // [Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, SyntaxKind.ConstructorKeyword], - - [Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT, SyntaxKind.AbstractKeyword], - // TODO: unsupported - // [Es2pandaModifierFlags. , SyntaxKind.AccessorKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_ASYNC, SyntaxKind.AsyncKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_CONST, SyntaxKind.ConstKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE, SyntaxKind.DeclareKeyword], - // TODO: choose one - // [Es2pandaModifierFlags.MODIFIER_FLAGS_DEFAULT_EXPORT, SyntaxKind.DefaultClause], - // [Es2pandaModifierFlags.MODIFIER_FLAGS_DEFAULT_EXPORT, SyntaxKind.DefaultKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT, SyntaxKind.ExportKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_IN, SyntaxKind.InKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, SyntaxKind.PrivateKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_PROTECTED, SyntaxKind.ProtectedKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, SyntaxKind.PublicKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_OUT, SyntaxKind.OutKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE, SyntaxKind.OverrideKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_READONLY, SyntaxKind.ReadonlyKeyword], - [Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, SyntaxKind.StaticKeyword], - ]) - } - return this._translateModifiers - } -} diff --git a/arkoala-arkts/libarkts/src/arkts-api/factory/nodeFactory.ts b/arkoala-arkts/libarkts/src/arkts-api/factory/nodeFactory.ts new file mode 100644 index 000000000..b06af611c --- /dev/null +++ b/arkoala-arkts/libarkts/src/arkts-api/factory/nodeFactory.ts @@ -0,0 +1,54 @@ +/* + * 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 arkts from "../types" +import { updateNodeByNode } from "../utilities/private" + +function compose( + create: (...args: ARGS) => T, + update: (node: T, original: T) => T = updateNodeByNode +): (node: T, ...args: ARGS) => T { + return (node: T, ...args: ARGS) => update(node, create(...args)); +} + +export const factory = { + /** + * @see TS_INTERFACE + * @arg text: string + */ + createIdentifier: arkts.Identifier.create, + updateIdentifier: compose(arkts.Identifier.create), + + /** + * @see TS_INTERFACE + * @arg expression: Expression, + * @arg typeArguments: readonly TypeNode[] | undefined, + * @arg argumentsArray: readonly Expression[] | undefined, + */ + createCallExpression: arkts.CallExpression.create, + updateCallExpression: compose(arkts.CallExpression.create), + + /** + * TODO: + */ + createExpressionStatement: arkts.ExpressionStatement.create, + updateExpressionStatement: compose(arkts.ExpressionStatement.create), + + /** + * TODO: + */ + createMemberExpression: arkts.MemberExpression.create, + updateMemberExpression: compose(arkts.MemberExpression.create), +} diff --git a/arkoala-arkts/libarkts/src/api/layers/ts/index.ts b/arkoala-arkts/libarkts/src/arkts-api/index.ts similarity index 78% rename from arkoala-arkts/libarkts/src/api/layers/ts/index.ts rename to arkoala-arkts/libarkts/src/arkts-api/index.ts index f7237d2d9..e6cdcc914 100644 --- a/arkoala-arkts/libarkts/src/api/layers/ts/index.ts +++ b/arkoala-arkts/libarkts/src/arkts-api/index.ts @@ -14,4 +14,8 @@ */ export * from "./types" -export * from "./utilities" +// TODO: remove private export +export * from "./utilities/private" +export * from "./utilities/public" +export * from "./static/enums" +export * from "./factory/nodeFactory" diff --git a/arkoala-arkts/libarkts/src/api/static/enums.ts b/arkoala-arkts/libarkts/src/arkts-api/static/enums.ts similarity index 65% rename from arkoala-arkts/libarkts/src/api/static/enums.ts rename to arkoala-arkts/libarkts/src/arkts-api/static/enums.ts index a43d1f347..9fd82dcb0 100644 --- a/arkoala-arkts/libarkts/src/api/static/enums.ts +++ b/arkoala-arkts/libarkts/src/arkts-api/static/enums.ts @@ -13,11 +13,44 @@ * limitations under the License. */ -export { SyntaxKind } from "@koalaui/ets-tsc" - -export { TokenSyntaxKind } from "@koalaui/ets-tsc" +export enum Es2pandaModifierFlags { + MODIFIER_FLAGS_NONE = 0, + MODIFIER_FLAGS_STATIC = 1 << 0, + MODIFIER_FLAGS_ASYNC = 1 << 1, + MODIFIER_FLAGS_PUBLIC = 1 << 2, + MODIFIER_FLAGS_PROTECTED = 1 << 3, + MODIFIER_FLAGS_PRIVATE = 1 << 4, + MODIFIER_FLAGS_DECLARE = 1 << 5, + MODIFIER_FLAGS_READONLY = 1 << 6, + MODIFIER_FLAGS_OPTIONAL = 1 << 7, + MODIFIER_FLAGS_DEFINITE = 1 << 8, + MODIFIER_FLAGS_ABSTRACT = 1 << 9, + MODIFIER_FLAGS_CONST = 1 << 10, + MODIFIER_FLAGS_FINAL = 1 << 11, + MODIFIER_FLAGS_NATIVE = 1 << 12, + MODIFIER_FLAGS_OVERRIDE = 1 << 13, + MODIFIER_FLAGS_CONSTRUCTOR = 1 << 14, + MODIFIER_FLAGS_SYNCHRONIZED = 1 << 15, + MODIFIER_FLAGS_FUNCTIONAL = 1 << 16, + MODIFIER_FLAGS_IN = 1 << 17, + MODIFIER_FLAGS_OUT = 1 << 18, + MODIFIER_FLAGS_INTERNAL = 1 << 19, + MODIFIER_FLAGS_EXPORT = 1 << 20, + MODIFIER_FLAGS_GETTER = 1 << 21, + MODIFIER_FLAGS_SETTER = 1 << 22, + MODIFIER_FLAGS_DEFAULT_EXPORT = 1 << 23, + MODIFIER_FLAGS_EXPORT_TYPE = 1 << 24, + MODIFIER_FLAGS_SUPER_OWNER = 1 << 25, + MODIFIER_FLAGS_ACCESS = MODIFIER_FLAGS_PUBLIC | MODIFIER_FLAGS_PROTECTED | MODIFIER_FLAGS_PRIVATE | MODIFIER_FLAGS_INTERNAL, + MODIFIER_FLAGS_ALL = MODIFIER_FLAGS_STATIC | MODIFIER_FLAGS_ASYNC | MODIFIER_FLAGS_ACCESS | MODIFIER_FLAGS_DECLARE | MODIFIER_FLAGS_READONLY | MODIFIER_FLAGS_ABSTRACT, + MODIFIER_FLAGS_ALLOWED_IN_CTOR_PARAMETER = MODIFIER_FLAGS_ACCESS | MODIFIER_FLAGS_READONLY, + MODIFIER_FLAGS_INTERNAL_PROTECTED = MODIFIER_FLAGS_INTERNAL | MODIFIER_FLAGS_PROTECTED, + MODIFIER_FLAGS_ACCESSOR_MODIFIERS = MODIFIER_FLAGS_ABSTRACT | MODIFIER_FLAGS_FINAL, + MODIFIER_FLAGS_GETTER_SETTER = MODIFIER_FLAGS_GETTER | MODIFIER_FLAGS_SETTER, + MODIFIER_FLAGS_EXPORTED = MODIFIER_FLAGS_EXPORT | MODIFIER_FLAGS_DEFAULT_EXPORT | MODIFIER_FLAGS_EXPORT_TYPE, +}; -export enum ContextState { +export enum Es2pandaContextState { ES2PANDA_STATE_NEW = 0, ES2PANDA_STATE_PARSED = 1, ES2PANDA_STATE_SCOPE_INITED = 2, @@ -29,41 +62,172 @@ export enum ContextState { ES2PANDA_STATE_ERROR = 7, }; -export enum es2pandaKind { - UnsupportedNode = 0, - - Identifier = 1, - StringLiteral = 2, - Block = 3, - MethodDefinition = 4, - ClassDeclaration = 5, - FunctionDeclaration = 6, - ClassProperty = 7, - TSTypeParameterDeclaration = 8, - ETSFunctionType = 9, - CallExpression = 10, - ExpressionStatement = 11, - MemberExpression = 12, - ArrowFunctionExpression = 13, - ReturnStatement = 14, - ETSParameterExpression = 15, - NumberLiteral = 16, - VariableDeclaration = 17, - ClassStaticBlock = 18, - Program = 19, - BinaryExpression = 20, - FunctionExpression = 21, - ScriptFunction = 22, - VariableDeclarator = 23, - TSTypeParameter = 24, - ETSPrimitiveType = 25, - AssignmentExpression = 26, - ETSTypeReference = 27, - TSUnionType = 28, - ETSUnionType = 29, - ClassDefinition = 30, - ETSTypeReferencePart = 31, - IfStatement = 32, +export enum Es2pandaAstNodeType { + AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, + AST_NODE_TYPE_ANNOTATION_DECLARATION, + AST_NODE_TYPE_ANNOTATION_USAGE, + AST_NODE_TYPE_ASSERT_STATEMENT, + AST_NODE_TYPE_AWAIT_EXPRESSION, + AST_NODE_TYPE_BIGINT_LITERAL, + AST_NODE_TYPE_BINARY_EXPRESSION, + AST_NODE_TYPE_BLOCK_STATEMENT, + AST_NODE_TYPE_BOOLEAN_LITERAL, + AST_NODE_TYPE_BREAK_STATEMENT, + AST_NODE_TYPE_CALL_EXPRESSION, + AST_NODE_TYPE_CATCH_CLAUSE, + AST_NODE_TYPE_CHAIN_EXPRESSION, + AST_NODE_TYPE_CHAR_LITERAL, + AST_NODE_TYPE_CLASS_DEFINITION, + AST_NODE_TYPE_CLASS_DECLARATION, + AST_NODE_TYPE_CLASS_EXPRESSION, + AST_NODE_TYPE_CLASS_PROPERTY, + AST_NODE_TYPE_CLASS_STATIC_BLOCK, + AST_NODE_TYPE_CONDITIONAL_EXPRESSION, + AST_NODE_TYPE_CONTINUE_STATEMENT, + AST_NODE_TYPE_DEBUGGER_STATEMENT, + AST_NODE_TYPE_DECORATOR, + AST_NODE_TYPE_DIRECT_EVAL, + AST_NODE_TYPE_DO_WHILE_STATEMENT, + AST_NODE_TYPE_EMPTY_STATEMENT, + AST_NODE_TYPE_EXPORT_ALL_DECLARATION, + AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION, + AST_NODE_TYPE_EXPORT_NAMED_DECLARATION, + AST_NODE_TYPE_EXPORT_SPECIFIER, + AST_NODE_TYPE_EXPRESSION_STATEMENT, + AST_NODE_TYPE_FOR_IN_STATEMENT, + AST_NODE_TYPE_FOR_OF_STATEMENT, + AST_NODE_TYPE_FOR_UPDATE_STATEMENT, + AST_NODE_TYPE_FUNCTION_DECLARATION, + AST_NODE_TYPE_FUNCTION_EXPRESSION, + AST_NODE_TYPE_IDENTIFIER, + AST_NODE_TYPE_DUMMYNODE, + AST_NODE_TYPE_IF_STATEMENT, + AST_NODE_TYPE_IMPORT_DECLARATION, + AST_NODE_TYPE_IMPORT_EXPRESSION, + AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER, + AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER, + AST_NODE_TYPE_IMPORT_SPECIFIER, + AST_NODE_TYPE_LABELLED_STATEMENT, + AST_NODE_TYPE_MEMBER_EXPRESSION, + AST_NODE_TYPE_META_PROPERTY_EXPRESSION, + AST_NODE_TYPE_METHOD_DEFINITION, + AST_NODE_TYPE_NAMED_TYPE, + AST_NODE_TYPE_NAMESPACE_DECLARATION, + AST_NODE_TYPE_NAMESPACE_DEFINITION, + AST_NODE_TYPE_NEW_EXPRESSION, + AST_NODE_TYPE_NULL_LITERAL, + AST_NODE_TYPE_UNDEFINED_LITERAL, + AST_NODE_TYPE_NUMBER_LITERAL, + AST_NODE_TYPE_OMITTED_EXPRESSION, + AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION, + AST_NODE_TYPE_PROPERTY, + AST_NODE_TYPE_REGEXP_LITERAL, + AST_NODE_TYPE_REEXPORT_STATEMENT, + AST_NODE_TYPE_RETURN_STATEMENT, + AST_NODE_TYPE_SCRIPT_FUNCTION, + AST_NODE_TYPE_SEQUENCE_EXPRESSION, + AST_NODE_TYPE_STRING_LITERAL, + AST_NODE_TYPE_ETS_NULL_TYPE, + AST_NODE_TYPE_ETS_UNDEFINED_TYPE, + AST_NODE_TYPE_ETS_NEVER_TYPE, + AST_NODE_TYPE_ETS_STRING_LITERAL_TYPE, + AST_NODE_TYPE_ETS_FUNCTION_TYPE, + AST_NODE_TYPE_ETS_WILDCARD_TYPE, + AST_NODE_TYPE_ETS_PRIMITIVE_TYPE, + AST_NODE_TYPE_ETS_PACKAGE_DECLARATION, + AST_NODE_TYPE_ETS_CLASS_LITERAL, + AST_NODE_TYPE_ETS_TYPE_REFERENCE, + AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, + AST_NODE_TYPE_ETS_UNION_TYPE, + AST_NODE_TYPE_ETS_LAUNCH_EXPRESSION, + AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION, + AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION, + AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION, + AST_NODE_TYPE_ETS_IMPORT_DECLARATION, + AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, + AST_NODE_TYPE_ETS_TUPLE, + AST_NODE_TYPE_ETS_SCRIPT, + AST_NODE_TYPE_SUPER_EXPRESSION, + AST_NODE_TYPE_STRUCT_DECLARATION, + AST_NODE_TYPE_SWITCH_CASE_STATEMENT, + AST_NODE_TYPE_SWITCH_STATEMENT, + AST_NODE_TYPE_TS_ENUM_DECLARATION, + AST_NODE_TYPE_TS_ENUM_MEMBER, + AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE, + AST_NODE_TYPE_TS_NUMBER_KEYWORD, + AST_NODE_TYPE_TS_ANY_KEYWORD, + AST_NODE_TYPE_TS_STRING_KEYWORD, + AST_NODE_TYPE_TS_BOOLEAN_KEYWORD, + AST_NODE_TYPE_TS_VOID_KEYWORD, + AST_NODE_TYPE_TS_UNDEFINED_KEYWORD, + AST_NODE_TYPE_TS_UNKNOWN_KEYWORD, + AST_NODE_TYPE_TS_OBJECT_KEYWORD, + AST_NODE_TYPE_TS_BIGINT_KEYWORD, + AST_NODE_TYPE_TS_NEVER_KEYWORD, + AST_NODE_TYPE_TS_NON_NULL_EXPRESSION, + AST_NODE_TYPE_TS_NULL_KEYWORD, + AST_NODE_TYPE_TS_ARRAY_TYPE, + AST_NODE_TYPE_TS_UNION_TYPE, + AST_NODE_TYPE_TS_TYPE_LITERAL, + AST_NODE_TYPE_TS_PROPERTY_SIGNATURE, + AST_NODE_TYPE_TS_METHOD_SIGNATURE, + AST_NODE_TYPE_TS_SIGNATURE_DECLARATION, + AST_NODE_TYPE_TS_PARENT_TYPE, + AST_NODE_TYPE_TS_LITERAL_TYPE, + AST_NODE_TYPE_TS_INFER_TYPE, + AST_NODE_TYPE_TS_CONDITIONAL_TYPE, + AST_NODE_TYPE_TS_IMPORT_TYPE, + AST_NODE_TYPE_TS_INTERSECTION_TYPE, + AST_NODE_TYPE_TS_MAPPED_TYPE, + AST_NODE_TYPE_TS_MODULE_BLOCK, + AST_NODE_TYPE_TS_THIS_TYPE, + AST_NODE_TYPE_TS_TYPE_OPERATOR, + AST_NODE_TYPE_TS_TYPE_PARAMETER, + AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION, + AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION, + AST_NODE_TYPE_TS_TYPE_PREDICATE, + AST_NODE_TYPE_TS_PARAMETER_PROPERTY, + AST_NODE_TYPE_TS_MODULE_DECLARATION, + AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION, + AST_NODE_TYPE_TS_FUNCTION_TYPE, + AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE, + AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION, + AST_NODE_TYPE_TS_TYPE_REFERENCE, + AST_NODE_TYPE_TS_QUALIFIED_NAME, + AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE, + AST_NODE_TYPE_TS_INTERFACE_DECLARATION, + AST_NODE_TYPE_TS_INTERFACE_BODY, + AST_NODE_TYPE_TS_INTERFACE_HERITAGE, + AST_NODE_TYPE_TS_TUPLE_TYPE, + AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER, + AST_NODE_TYPE_TS_INDEX_SIGNATURE, + AST_NODE_TYPE_TS_TYPE_QUERY, + AST_NODE_TYPE_TS_AS_EXPRESSION, + AST_NODE_TYPE_TS_CLASS_IMPLEMENTS, + AST_NODE_TYPE_TS_TYPE_ASSERTION, + AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION, + AST_NODE_TYPE_TEMPLATE_ELEMENT, + AST_NODE_TYPE_TEMPLATE_LITERAL, + AST_NODE_TYPE_THIS_EXPRESSION, + AST_NODE_TYPE_TYPEOF_EXPRESSION, + AST_NODE_TYPE_THROW_STATEMENT, + AST_NODE_TYPE_TRY_STATEMENT, + AST_NODE_TYPE_UNARY_EXPRESSION, + AST_NODE_TYPE_UPDATE_EXPRESSION, + AST_NODE_TYPE_VARIABLE_DECLARATION, + AST_NODE_TYPE_VARIABLE_DECLARATOR, + AST_NODE_TYPE_WHILE_STATEMENT, + AST_NODE_TYPE_YIELD_EXPRESSION, + AST_NODE_TYPE_OPAQUE_TYPE_NODE, + AST_NODE_TYPE_BLOCK_EXPRESSION, + AST_NODE_TYPE_ARRAY_EXPRESSION, + AST_NODE_TYPE_ARRAY_PATTERN, + AST_NODE_TYPE_ASSIGNMENT_EXPRESSION, + AST_NODE_TYPE_ASSIGNMENT_PATTERN, + AST_NODE_TYPE_OBJECT_EXPRESSION, + AST_NODE_TYPE_OBJECT_PATTERN, + AST_NODE_TYPE_SPREAD_ELEMENT, + AST_NODE_TYPE_REST_ELEMENT, }; export enum Es2pandaTokenType { @@ -265,52 +429,15 @@ export enum Es2pandaMethodDefinitionKind { }; export enum Es2pandaPrimitiveType { - PRIMITIVE_TYPE_BYTE = 1, - PRIMITIVE_TYPE_INT = 2, - PRIMITIVE_TYPE_LONG = 3, - PRIMITIVE_TYPE_SHORT = 4, - PRIMITIVE_TYPE_FLOAT = 5, - PRIMITIVE_TYPE_DOUBLE = 6, - PRIMITIVE_TYPE_BOOLEAN = 7, - PRIMITIVE_TYPE_CHAR = 8, - PRIMITIVE_TYPE_VOID = 9, -}; - -export enum Es2pandaModifierFlags { - MODIFIER_FLAGS_NONE = 0, - MODIFIER_FLAGS_STATIC = 1 << 0, - MODIFIER_FLAGS_ASYNC = 1 << 1, - MODIFIER_FLAGS_PUBLIC = 1 << 2, - MODIFIER_FLAGS_PROTECTED = 1 << 3, - MODIFIER_FLAGS_PRIVATE = 1 << 4, - MODIFIER_FLAGS_DECLARE = 1 << 5, - MODIFIER_FLAGS_READONLY = 1 << 6, - MODIFIER_FLAGS_OPTIONAL = 1 << 7, - MODIFIER_FLAGS_DEFINITE = 1 << 8, - MODIFIER_FLAGS_ABSTRACT = 1 << 9, - MODIFIER_FLAGS_CONST = 1 << 10, - MODIFIER_FLAGS_FINAL = 1 << 11, - MODIFIER_FLAGS_NATIVE = 1 << 12, - MODIFIER_FLAGS_OVERRIDE = 1 << 13, - MODIFIER_FLAGS_CONSTRUCTOR = 1 << 14, - MODIFIER_FLAGS_SYNCHRONIZED = 1 << 15, - MODIFIER_FLAGS_FUNCTIONAL = 1 << 16, - MODIFIER_FLAGS_IN = 1 << 17, - MODIFIER_FLAGS_OUT = 1 << 18, - MODIFIER_FLAGS_INTERNAL = 1 << 19, - MODIFIER_FLAGS_EXPORT = 1 << 20, - MODIFIER_FLAGS_GETTER = 1 << 21, - MODIFIER_FLAGS_SETTER = 1 << 22, - MODIFIER_FLAGS_DEFAULT_EXPORT = 1 << 23, - MODIFIER_FLAGS_EXPORT_TYPE = 1 << 24, - MODIFIER_FLAGS_SUPER_OWNER = 1 << 25, - MODIFIER_FLAGS_ACCESS = MODIFIER_FLAGS_PUBLIC | MODIFIER_FLAGS_PROTECTED | MODIFIER_FLAGS_PRIVATE | MODIFIER_FLAGS_INTERNAL, - MODIFIER_FLAGS_ALL = MODIFIER_FLAGS_STATIC | MODIFIER_FLAGS_ASYNC | MODIFIER_FLAGS_ACCESS | MODIFIER_FLAGS_DECLARE | MODIFIER_FLAGS_READONLY | MODIFIER_FLAGS_ABSTRACT, - MODIFIER_FLAGS_ALLOWED_IN_CTOR_PARAMETER = MODIFIER_FLAGS_ACCESS | MODIFIER_FLAGS_READONLY, - MODIFIER_FLAGS_INTERNAL_PROTECTED = MODIFIER_FLAGS_INTERNAL | MODIFIER_FLAGS_PROTECTED, - MODIFIER_FLAGS_ACCESSOR_MODIFIERS = MODIFIER_FLAGS_ABSTRACT | MODIFIER_FLAGS_FINAL, - MODIFIER_FLAGS_GETTER_SETTER = MODIFIER_FLAGS_GETTER | MODIFIER_FLAGS_SETTER, - MODIFIER_FLAGS_EXPORTED = MODIFIER_FLAGS_EXPORT | MODIFIER_FLAGS_DEFAULT_EXPORT | MODIFIER_FLAGS_EXPORT_TYPE, + PRIMITIVE_TYPE_BYTE = 0, + PRIMITIVE_TYPE_INT = 1, + PRIMITIVE_TYPE_LONG = 2, + PRIMITIVE_TYPE_SHORT = 3, + PRIMITIVE_TYPE_FLOAT = 4, + PRIMITIVE_TYPE_DOUBLE = 5, + PRIMITIVE_TYPE_BOOLEAN = 6, + PRIMITIVE_TYPE_CHAR = 7, + PRIMITIVE_TYPE_VOID = 8, }; export enum Es2pandaScriptFunctionFlags { @@ -365,7 +492,7 @@ export enum Es2pandaClassDefinitionModifiers { CLASS_DEFINITION_MODIFIERS_DECLARATION_ID_REQUIRED = CLASS_DEFINITION_MODIFIERS_DECLARATION | CLASS_DEFINITION_MODIFIERS_ID_REQUIRED, }; -export const enum TokenFlags { +export const enum Es2pandaTokenFlags { None = 0, /** @internal */ PrecedingLineBreak = 1 << 0, @@ -416,9 +543,29 @@ export const enum Es2pandaVariableDeclarationKind { VAR } -export const enum VariableDeclaratorFlag { +export const enum Es2pandaVariableDeclaratorFlag { LET, CONST, VAR, UNKNOWN, } + +export const enum Es2pandaImportKinds { + VALUE, + TYPE +} + +export const enum Es2pandaIdentifierFlags { + NONE = 0, + OPTIONAL = 1 << 0, + REFERENCE = 1 << 1, + TDZ = 1 << 2, +} + +export const enum Es2pandaScriptExtension { + SCRIPT_EXTENSION_JS, + SCRIPT_EXTENSION_TS, + SCRIPT_EXTENSION_AS, + SCRIPT_EXTENSION_ETS, + SCRIPT_EXTENSION_INVALID, +} diff --git a/arkoala-arkts/libarkts/src/arkts-api/static/global.ts b/arkoala-arkts/libarkts/src/arkts-api/static/global.ts new file mode 100644 index 000000000..18f16585d --- /dev/null +++ b/arkoala-arkts/libarkts/src/arkts-api/static/global.ts @@ -0,0 +1,46 @@ +/* + * 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 { throwError } from "../../utils" +import { KNativePointer } from "@koalaui/interop" + +export default class global { + private static _config?: KNativePointer + public static set config(config: KNativePointer) { + if (global._config !== undefined) { + throwError('Global.config already initialized') + } + global._config = config + } + public static get config(): KNativePointer { + return global._config ?? throwError('Global.config not initialized') + } + + public static isInitializedConfig(): boolean { + return global._config !== undefined + } + + private static _context?: KNativePointer + public static set context(context: KNativePointer) { + global._context = context + } + public static get context(): KNativePointer { + return global._context ?? throwError('Global.context not initialized') + } + + public static isInitializedContext(): boolean { + return global._context !== undefined + } +} diff --git a/arkoala-arkts/libarkts/src/api/layers/arkts/types.ts b/arkoala-arkts/libarkts/src/arkts-api/types.ts similarity index 41% rename from arkoala-arkts/libarkts/src/api/layers/arkts/types.ts rename to arkoala-arkts/libarkts/src/arkts-api/types.ts index 630cbb379..cc9fcff2d 100644 --- a/arkoala-arkts/libarkts/src/api/layers/arkts/types.ts +++ b/arkoala-arkts/libarkts/src/arkts-api/types.ts @@ -13,175 +13,172 @@ * limitations under the License. */ -import global from "../../static/global" +import global from "./static/global" +import { throwError } from "../utils" -import { nativeModule } from "../../../NativeModule" +import { nativeModule } from "../nativeModule" import { KInt, KNativePointer as KPtr } from "@koalaui/interop" import { Es2pandaPrimitiveType, Es2pandaModifierFlags, Es2pandaScriptFunctionFlags, - es2pandaKind, - ContextState, + Es2pandaAstNodeType, + Es2pandaContextState, Es2pandaTokenType, Es2pandaMethodDefinitionKind, -} from "../../static/enums" + Es2pandaVariableDeclarationKind, + Es2pandaVariableDeclaratorFlag, + Es2pandaImportKinds, + Es2pandaMemberExpressionKind, + Es2pandaIdentifierFlags, +} from "./static/enums" import { unpackNonNullableNode, unpackNode, passNode, - unpackNodeArray, passNodeArray, - - unpackObject, - passString, unpackString, - passStringArray, -} from "./utilities" + updatePeerByNode, + resolveSource, +} from "./utilities/private" import { proceedToState, -} from "../../utilities/utilitiesPublic" +} from "./utilities/public" export const NULLPTR: KPtr = BigInt(0) export const NULLPTR_ARRAY = new BigUint64Array([NULLPTR]) -export const ALL_FLAGS: KInt = Object.values(Es2pandaModifierFlags).filter( - (value: any) => { return (typeof value) === 'number' } - ).reduce( - (prev: KInt, next: KInt): KInt => (prev | next), - 0 as KInt - ) +export const ALL_FLAGS: KInt = + Object.values(Es2pandaModifierFlags).filter( + (value: any) => { return (typeof value) === 'number' } + ).reduce( + (prev: KInt, next: KInt): KInt => (prev | next), + 0 as KInt + ) -function assertValidPeer(peer: KPtr, expectedKind: es2pandaKind): void { +function assertValidPeer(peer: KPtr, expectedKind: Es2pandaAstNodeType): void { if (peer === NULLPTR) { - global.throwError(`invalid peer: NULLPTR`) + throwError(`invalid peer: NULLPTR`) } - const peerKind = nativeModule._GetKind(global.context, peer) - if (peerKind !== expectedKind) { - global.throwError(`invalid kind of peer: ${peerKind} expected: ${expectedKind}`) + const peerType = nativeModule._AstNodeTypeConst(global.context, peer) + if (peerType !== expectedKind) { + throwError(`actual type of peer: ${peerType} expected: ${expectedKind}`) } } export abstract class ArktsObject { - constructor(peer: KPtr) { + protected constructor(peer: KPtr) { this.peer = peer } - // pointer associated with native object readonly peer: KPtr } export abstract class Node extends ArktsObject { - constructor(peer: KPtr) { + protected constructor(peer: KPtr) { if (peer === NULLPTR) { throw new Error('trying to create new Node on NULLPTR') } super(peer) - this.kind = nativeModule._GetKind(global.context, this.peer) + this.type = nativeModule._AstNodeTypeConst(global.context, this.peer) this.updateChildren() } - readonly kind: es2pandaKind + readonly type: Es2pandaAstNodeType - // TODO: update scopes and other data - updateNode(original: this): this { - if (typeof this !== typeof original) { - throw new Error('updateNode called on different type') - } - nativeModule._AstNodeSetOriginalNode(global.context, this.peer, original.peer) - nativeModule._AstNodeSetParent(global.context, this.peer, nativeModule._AstNodeParent(global.context, original.peer)) - nativeModule._AstNodeUpdateChildren(global.context, this.peer) - this.modifiers = original.modifiers - // new flags may change children - this.updateChildren() - // switch (classByPeer(peer)) { - // case arkts.ClassDeclaration: { - // // TODO: update Language - // break - // } - // } - - // TODO: rewrite - return this + public get originalPeer(): KPtr { + return nativeModule._AstNodeOriginalNodeConst(global.context, this.peer) + } + + public set originalPeer(peer: KPtr) { + nativeModule._AstNodeSetOriginalNode(global.context, this.peer, peer) } - updateChildren(): void { + public getChildren(): readonly Node[] { + return unpackNodeArray(nativeModule._AstNodeChildren(global.context, this.peer)) + } + + public getSubtree(): readonly Node[] { + return this.getChildren().reduce( + (prev: readonly Node[], curr: Node): readonly Node[] => { + return prev.concat(curr.getSubtree()) + }, + [this] + ) + } + + public updateChildren(): void { if (this.peer === NULLPTR) { - global.throwError('updateChildren called on NULLPTR') + throwError('updateChildren called on NULLPTR') } nativeModule._AstNodeUpdateChildren(global.context, this.peer) } - updateModifiers(modifierFlags: KInt | undefined): this { + public updateModifiers(modifierFlags: KInt | undefined): this { nativeModule._AstNodeClearModifier(global.context, this.peer, ALL_FLAGS) nativeModule._AstNodeAddModifier(global.context, this.peer, modifierFlags ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE) return this } - dumpJson(): string { + public dump(indentation: number = 0): string { + const children = this.getChildren().map( + (child: Node): string => child.dump(indentation + 1) + ) + const msg: string = + `${indentation}_` + + Es2pandaAstNodeType[this.type] + + ` ` + + this.dumpMessage() + return "> " + " ".repeat(4 * indentation) + msg + "\n" + children.join("") + } + + protected dumpMessage(): string { + return `` + } + + public dumpJson(): string { return unpackString(nativeModule._AstNodeDumpJsonConst(global.context, this.peer)) } - dumpSrc(): string { + public dumpSrc(): string { return unpackString(nativeModule._AstNodeDumpEtsSrcConst(global.context, this.peer)) } - dumpModifiers(): string { + public dumpModifiers(): string { return unpackString(nativeModule._AstNodeDumpModifiers(global.context, this.peer)) } - get parent(): Node { + public get parent(): Node { const _parent = nativeModule._AstNodeParent(global.context, this.peer) if (_parent === NULLPTR) { - global.throwError('BAD ACCESS: PARENT IS NULLPTR') + throwError('BAD ACCESS: PARENT IS NULLPTR') } return unpackNonNullableNode(_parent) } - set parent(node: Node) { + public set parent(node: Node) { nativeModule._AstNodeSetParent(global.context, this.peer, node.peer) } - get modifiers(): KInt { + public get modifiers(): KInt { return nativeModule._AstNodeModifiers(global.context, this.peer) } - set modifiers(flags: KInt | undefined) { + public set modifiers(flags: KInt | undefined) { nativeModule._AstNodeClearModifier(global.context, this.peer, ALL_FLAGS) nativeModule._AstNodeAddModifier(global.context, this.peer, flags ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE) } } -// export abstract class Node extends EtsNode { -// constructor(peer: KPtr) { -// super(peer) -// this.kind = nativeModule._GetKind(global.context, this.peer) -// updateChildren(this.peer) -// } - -// readonly kind: es2pandaKind -// } - -// export abstract class CompatibleNode extends EtsNode { -// constructor(peer: KPtr, related: arkts.Node) { -// super(peer) -// this.kind = nativeModule._GetKind(global.context, this.peer) -// updateChildren(this.peer) -// this.related = related -// } - -// readonly kind: es2pandaKind -// readonly related: arkts.Node -// } - -export abstract class UnsupportedNode extends Node { +export class UnsupportedNode extends Node { constructor(peer: KPtr) { super(peer) - throw new Error('trying to create UnsupportedNode') + console.log(`WARNING: UNSUPPORTED NODE (arkts): ${Es2pandaAstNodeType[this.type]}`) + // throwError(`UNSUPPORTED NODE (arkts): ${es2panda_Kind[this.kind]}`) } } @@ -197,24 +194,35 @@ export class Context extends ArktsObject { } } -export class Program extends Node { +export class EtsScript extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.Program) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_SCRIPT) + if (!nativeModule._IsProgram(global.context, peer)) { + throwError('peer expected to be Program') + } super(peer) } + // TODO: rewrite this maybe static create( - source: string - ): Program { + source: string, + state: Es2pandaContextState = Es2pandaContextState.ES2PANDA_STATE_PARSED, + ): EtsScript { if (!global.isInitializedConfig()) { global.config = nativeModule._CreateConfig(4, passStringArray(["", "--arktsconfig", "./arktsconfig.json", "./input/main.sts"])) } global.context = nativeModule._CreateContextFromString(global.config, passString(source), passString("./input/main.sts")) + proceedToState(state) + return new EtsScript(nativeModule._ProgramAst(nativeModule._ContextProgram(global.context))) + } - // TODO: rewrite this maybe - proceedToState(ContextState.ES2PANDA_STATE_PARSED) - - return new Program(nativeModule._ProgramAst(nativeModule._ContextProgram(global.context))) + // TODO: should create new node + static update( + node: EtsScript, + statements: Node[], + ): EtsScript { + nativeModule._BlockStatementSetStatements(global.context, node.peer, passNodeArray(statements), statements.length) + return node } get statements(): readonly Node[] { @@ -228,13 +236,20 @@ export class Program extends Node { export class ExpressionStatement extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ExpressionStatement) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT) super(peer) this.expression = unpackNonNullableNode(nativeModule._ExpressionStatementGetExpression(global.context, this.peer)) } - static create(expression: Node): ExpressionStatement { - return new ExpressionStatement(nativeModule._CreateExpressionStatement(global.context, expression.peer)) + static create( + expression: Node, + ): ExpressionStatement { + return new ExpressionStatement( + nativeModule._CreateExpressionStatement( + global.context, + expression.peer + ) + ) } readonly expression: Node @@ -242,7 +257,7 @@ export class ExpressionStatement extends Node { export class CallExpression extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.CallExpression) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION) super(peer) this.expression = unpackNonNullableNode(nativeModule._CallExpressionCallee(global.context, this.peer)) this.arguments = unpackNodeArray(nativeModule._CallExpressionArguments(global.context, this.peer, NULLPTR)) @@ -272,21 +287,25 @@ export class CallExpression extends Node { export class AssignmentExpression extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.AssignmentExpression) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ASSIGNMENT_EXPRESSION) super(peer) } static create( + node: undefined | AssignmentExpression, left: Node, assignmentOperator: Es2pandaTokenType, right: Node ): AssignmentExpression { return new AssignmentExpression( - nativeModule._CreateAssignmentExpression( - global.context, - passNode(left), - passNode(right), - assignmentOperator + updatePeerByNode( + nativeModule._CreateAssignmentExpression( + global.context, + passNode(left), + passNode(right), + assignmentOperator + ), + node ) ) } @@ -294,16 +313,17 @@ export class AssignmentExpression extends Node { export class MemberExpression extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.MemberExpression) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION) super(peer) this.object = unpackNonNullableNode(nativeModule._MemberExpressionObject(global.context, this.peer)) this.property = unpackNonNullableNode(nativeModule._MemberExpressionProperty(global.context, this.peer)) + this.kind = nativeModule._MemberExpressionKindConst(global.context, this.peer) } static create( object: Node, property: Node, - kind: KInt, + kind: Es2pandaMemberExpressionKind, computed: boolean, optional: boolean ): MemberExpression { @@ -319,27 +339,36 @@ export class MemberExpression extends Node { ) } + protected override dumpMessage(): string { + return ` ` + } + readonly object: Node readonly property: Node + readonly kind: Es2pandaMemberExpressionKind } export class BinaryExpression extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.BinaryExpression) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION) super(peer) } static create( + node: undefined | BinaryExpression, left: Node, operatorType: Es2pandaTokenType, right: Node ): BinaryExpression { return new BinaryExpression( - nativeModule._CreateBinaryExpression( - global.context, - passNode(left), - passNode(right), - operatorType + updatePeerByNode( + nativeModule._CreateBinaryExpression( + global.context, + passNode(left), + passNode(right), + operatorType + ), + node ) ) } @@ -347,34 +376,50 @@ export class BinaryExpression extends Node { export class ETSPrimitiveType extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ETSPrimitiveType) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE) super(peer) + this.primitiveType = nativeModule._ETSPrimitiveTypeGetPrimitiveTypeConst(global.context, this.peer) } static create( - type: Es2pandaPrimitiveType + node: undefined | ETSPrimitiveType, + type: Es2pandaPrimitiveType, ): ETSPrimitiveType { return new ETSPrimitiveType( - nativeModule._CreateETSPrimitiveType(global.context, type) + updatePeerByNode( + nativeModule._CreateETSPrimitiveType( + global.context, + type + ), + node + ) ) } - // readonly type: Es2pandaPrimitiveType + protected override dumpMessage(): string { + return ` ` + } + + readonly primitiveType: Es2pandaPrimitiveType } export class ETSTypeReference extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ETSTypeReference) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE) super(peer) } static create( - typeName: Identifier + node: undefined | ETSTypeReference, + typeName: Identifier, ): ETSTypeReference { return new ETSTypeReference( - nativeModule._CreateETSTypeReference( - global.context, - ETSTypeReferencePart.create(typeName).peer + updatePeerByNode( + nativeModule._CreateETSTypeReference( + global.context, + ETSTypeReferencePart.create(undefined, typeName).peer + ), + node ) ) } @@ -385,20 +430,26 @@ export class ETSTypeReference extends Node { export class ETSTypeReferencePart extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ETSTypeReferencePart) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART) super(peer) } // TODO: support type params and prev - static create(typeName: Identifier) { - typeName.setReference(true) + static create( + node: undefined | ETSTypeReferencePart, + typeName: Identifier, + ) { + // typeName.setReference(true) // TODO: support type params and prev return new ETSTypeReferencePart( - nativeModule._CreateETSTypeReferencePart( - global.context, - typeName.peer, - NULLPTR, - NULLPTR + updatePeerByNode( + nativeModule._CreateETSTypeReferencePart( + global.context, + typeName.peer, + NULLPTR, + NULLPTR + ), + node ) ) } @@ -408,19 +459,23 @@ export class ETSTypeReferencePart extends Node { export class TSUnionType extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.TSUnionType) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE) super(peer) this.types = unpackNodeArray(nativeModule._TSUnionTypeTypesConst(global.context, this.peer, NULLPTR)) } static create( - types: Node[] + node: undefined | TSUnionType, + types: Node[], ): TSUnionType { return new TSUnionType( - nativeModule._CreateTSUnionType( - global.context, - passNodeArray(types), - types.length + updatePeerByNode( + nativeModule._CreateTSUnionType( + global.context, + passNodeArray(types), + types.length + ), + node ) ) } @@ -430,19 +485,23 @@ export class TSUnionType extends Node { export class ETSUnionType extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ETSUnionType) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE) super(peer) this.types = unpackNodeArray(nativeModule._ETSUnionTypeIrTypesConst(global.context, this.peer, NULLPTR)) } static create( - types: Node[] + node: undefined | ETSUnionType, + types: Node[], ): ETSUnionType { return new ETSUnionType( - nativeModule._CreateETSUnionTypeIr( - global.context, - passNodeArray(types), - types.length + updatePeerByNode( + nativeModule._CreateETSUnionTypeIr( + global.context, + passNodeArray(types), + types.length + ), + node ) ) } @@ -450,21 +509,25 @@ export class ETSUnionType extends Node { readonly types: readonly Node[] } -export class FunctionTypeNode extends Node { +export class ETSFunctionType extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ETSFunctionType) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE) super(peer) } static create( + node: undefined | ETSFunctionType, signature: FunctionSignature, scriptFunctionFlags: Es2pandaScriptFunctionFlags - ): FunctionTypeNode { - return new FunctionTypeNode( - nativeModule._CreateETSFunctionTypeIr( - global.context, - signature.peer, - scriptFunctionFlags + ): ETSFunctionType { + return new ETSFunctionType( + updatePeerByNode( + nativeModule._CreateETSFunctionTypeIr( + global.context, + signature.peer, + scriptFunctionFlags + ), + node ) ) } @@ -472,20 +535,29 @@ export class FunctionTypeNode extends Node { export class Identifier extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.Identifier) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER) super(peer) - this.isPrivate = nativeModule._IdentifierIsPrivateIdentConst(global.context, this.peer) } - static create(name: string, typeAnnotation?: Node): Identifier { + static create( + name: string, + typeAnnotation?: Node + ): Identifier { if (typeAnnotation === undefined) { - return new Identifier(nativeModule._CreateIdentifier1(global.context, passString(name))) + return new Identifier( + nativeModule._CreateIdentifier1(global.context, passString(name)) + ) } else { - return new Identifier(nativeModule._CreateIdentifier2(global.context, passString(name), typeAnnotation.peer)) + return new Identifier( + nativeModule._CreateIdentifier2(global.context, passString(name), typeAnnotation.peer) + ) } } - // TODO: return (string | undefined) maybe + protected override dumpMessage(): string { + return ` ` + } + get name(): string { return unpackString(nativeModule._IdentifierName(global.context, this.peer)) } @@ -494,28 +566,36 @@ export class Identifier extends Node { nativeModule._IdentifierSetName(global.context, this.peer, passString(name)) } - readonly isPrivate: boolean - - setReference(isRef: boolean): void { - nativeModule._IdentifierSetReference(global.context, this.peer, isRef) + get isPrivate(): boolean { + return nativeModule._IdentifierIsPrivateIdentConst(global.context, this.peer) } - // TODO: - // typeAnnotation() - // isOptional() - // setOptional() - // setTsVariables() + get identifierFlags(): Es2pandaIdentifierFlags { + return nativeModule._IdentifierIdentifierFlags(global.context, this.peer) + } } export class StringLiteral extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.StringLiteral) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL) super(peer) this.str = unpackString(nativeModule._StringLiteralStrConst(global.context, this.peer)) } - static create(str: string): StringLiteral { - return new StringLiteral(nativeModule._CreateStringLiteral(global.context, passString(str))) + static create( + node: undefined | StringLiteral, + str: string, + ): StringLiteral { + return new StringLiteral( + updatePeerByNode( + nativeModule._CreateStringLiteral(global.context, passString(str)), + node + ) + ) + } + + protected override dumpMessage(): string { + return ` ` } readonly str: string @@ -523,13 +603,25 @@ export class StringLiteral extends Node { export class NumberLiteral extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.NumberLiteral) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL) super(peer) this.str = unpackString(nativeModule._NumberLiteralStrConst(global.context, this.peer)) } - static create(str: string): NumberLiteral { - return new NumberLiteral(nativeModule._CreateNumberLiteral(global.context, passString(str))) + static create( + node: undefined | NumberLiteral, + str: string, + ): NumberLiteral { + return new NumberLiteral( + updatePeerByNode( + nativeModule._CreateNumberLiteral(global.context, passString(str)), + node + ) + ) + } + + protected override dumpMessage(): string { + return ` ` } readonly str: string @@ -538,9 +630,13 @@ export class NumberLiteral extends Node { export class FunctionSignature extends ArktsObject { constructor(peer: KPtr) { super(peer) - this.typeParamsDecl = unpackNode(nativeModule._FunctionSignatureTypeParams(global.context, this.peer)) - this.parameters = unpackNodeArray(nativeModule._FunctionSignatureParamsConst(global.context, this.peer, NULLPTR)) - this.returnTypeAnnotation = unpackNode(nativeModule._FunctionSignatureReturnType(global.context, this.peer)) + // TODO: + // there is some weird behavior with FunctionSignature, so properties unavailable now + // in class constructor (typeParamsDecl maybe NULLPTR in ScriptFunction, but not NULLPTR in its signature) + + // this.typeParamsDecl = unpackNode(nativeModule._FunctionSignatureTypeParams(global.context, this.peer)) + // this.parameters = unpackNodeArray(nativeModule._FunctionSignatureParamsConst(global.context, this.peer, NULLPTR)) + // this.returnTypeAnnotation = unpackNode(nativeModule._FunctionSignatureReturnType(global.context, this.peer)) } static create( @@ -559,23 +655,27 @@ export class FunctionSignature extends ArktsObject { ) } - readonly typeParamsDecl?: TSTypeParameterDeclaration - readonly parameters: readonly Node[] - readonly returnTypeAnnotation?: Node + // readonly typeParamsDecl?: TSTypeParameterDeclaration + // readonly parameters: readonly Node[] + // readonly returnTypeAnnotation?: Node } export class ScriptFunction extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ScriptFunction) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION) super(peer) this.parameters = unpackNodeArray(nativeModule._ScriptFunctionParams(global.context, this.peer)) + this.typeParamsDecl = unpackNode(nativeModule._ScriptFunctionTypeParams(global.context, this.peer)) this.body = unpackNode(nativeModule._ScriptFunctionBody(global.context, this.peer)) - this.signature = unpackObject(FunctionSignature, nativeModule._ScriptFunctionSignature(global.context, this.peer)) + // this.signature = unpackNonNullableObject(FunctionSignature, nativeModule._ScriptFunctionSignature(global.context, this.peer)) this.declare = nativeModule._ScriptFunctionDeclareConst(global.context, this.peer) this.ident = unpackNode(nativeModule._ScriptFunctionId(global.context, this.peer)) + + this.scriptFunctionFlags = this._correctScriptFunctionFlags() } static create( + node: undefined | ScriptFunction, body: Node | undefined, signature: FunctionSignature, functionFlags: Es2pandaScriptFunctionFlags, @@ -583,13 +683,16 @@ export class ScriptFunction extends Node { declare: boolean, ident: Identifier | undefined ): ScriptFunction { - const peer = nativeModule._CreateScriptFunction( - global.context, - passNode(body), - signature.peer, - functionFlags, - modifierFlags, - declare + const peer = updatePeerByNode( + nativeModule._CreateScriptFunction( + global.context, + passNode(body), + signature.peer, + functionFlags, + modifierFlags, + declare + ), + node ) if (ident !== undefined) { nativeModule._ScriptFunctionSetIdent(global.context, peer, ident.peer) @@ -597,27 +700,69 @@ export class ScriptFunction extends Node { return new ScriptFunction(peer) } + protected override dumpMessage(): string { + const scriptFunctionFlags = nativeModule._ScriptFunctionFlagsConst(global.context, this.peer) + return ` ` + } + + private _correctScriptFunctionFlags(): KInt { + let flags: KInt = nativeModule._ScriptFunctionFlagsConst(global.context, this.peer) + if (this._hasReturn()) { + flags |= Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_HAS_RETURN + nativeModule._ScriptFunctionAddFlag(global.context, this.peer, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_HAS_RETURN) + } + if (this._isAsync()) { + flags |= Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC + nativeModule._ScriptFunctionAddFlag(global.context, this.peer, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC) + } + return flags + } + + private _hasReturn(): boolean { + if (this.body === undefined) { + return false + } + let hasReturn: boolean = false + // TODO: goes through whole subtree, optimizable (unnecessary now) + this.body.getSubtree().forEach( + (node: Node) => { + hasReturn = hasReturn || (node.type === Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT) + } + ) + return hasReturn + } + + private _isAsync(): boolean { + return (this.modifiers & Es2pandaModifierFlags.MODIFIER_FLAGS_ASYNC) !== 0 + } + readonly parameters: readonly ETSParameterExpression[] - readonly body?: Node - readonly signature?: FunctionSignature + readonly typeParamsDecl?: TSTypeParameterDeclaration + readonly body?: BlockStatement + // readonly signature: FunctionSignature + readonly scriptFunctionFlags: KInt readonly declare: boolean readonly ident?: Identifier } export class ArrowFunctionExpression extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ArrowFunctionExpression) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION) super(peer) this.scriptFunction = unpackNonNullableNode(nativeModule._ArrowFunctionExpressionFunction(global.context, this.peer)) } static create( - func: ScriptFunction + node: undefined | ArrowFunctionExpression, + func: ScriptFunction, ): ArrowFunctionExpression { return new ArrowFunctionExpression( - nativeModule._CreateArrowFunctionExpression( - global.context, - passNode(func) + updatePeerByNode( + nativeModule._CreateArrowFunctionExpression( + global.context, + passNode(func) + ), + node ) ) } @@ -627,56 +772,67 @@ export class ArrowFunctionExpression extends Node { export class FunctionDeclaration extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.FunctionDeclaration) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION) super(peer) this.scriptFunction = unpackNonNullableNode(nativeModule._FunctionDeclarationFunction(global.context, this.peer)) this.parameters = unpackNodeArray(nativeModule._ScriptFunctionParams(global.context, this.scriptFunction.peer)) this.name = unpackNode(nativeModule._ScriptFunctionId(global.context, this.scriptFunction.peer)) this.body = unpackNode(nativeModule._ScriptFunctionBody(global.context, this.scriptFunction.peer)) this.typeParamsDecl = unpackNode(nativeModule._ScriptFunctionTypeParams(global.context, this.scriptFunction.peer)) - this.type = unpackNode(nativeModule._ScriptFunctionReturnTypeAnnotation(global.context, this.scriptFunction.peer)) + this.returnType = unpackNode(nativeModule._ScriptFunctionReturnTypeAnnotation(global.context, this.scriptFunction.peer)) this.isAnon = nativeModule._FunctionDeclarationIsAnonymousConst(global.context, this.peer) } static create( + node: undefined | FunctionDeclaration, scriptFunction: ScriptFunction, isAnon: boolean ): FunctionDeclaration { - const node = new FunctionDeclaration( - nativeModule._CreateFunctionDeclaration( - global.context, - scriptFunction.peer, - isAnon + const res = new FunctionDeclaration( + updatePeerByNode( + nativeModule._CreateFunctionDeclaration( + global.context, + scriptFunction.peer, + // TODO: support annotations + NULLPTR_ARRAY, + 0, + isAnon + ), + node ) ) // TODO: maybe wrong - node.modifiers = scriptFunction.modifiers - return node + res.modifiers = scriptFunction.modifiers + return res } readonly scriptFunction: ScriptFunction readonly parameters: readonly Node[] readonly name?: Identifier - readonly body?: Block + readonly body?: BlockStatement readonly typeParamsDecl?: TSTypeParameterDeclaration - readonly type?: Node + readonly returnType?: Node readonly isAnon: boolean } export class FunctionExpression extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.FunctionExpression) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION) super(peer) this.scriptFunction = unpackNonNullableNode(nativeModule._FunctionExpressionFunction(global.context, this.peer)) } static create( - expression: ScriptFunction + node: undefined | FunctionExpression, + expression: ScriptFunction, ): FunctionExpression { return new FunctionExpression( - nativeModule._CreateFunctionExpression( - global.context, - passNode(expression) + updatePeerByNode( + nativeModule._CreateFunctionExpression( + global.context, + passNode(expression) + ), + node ) ) } @@ -684,21 +840,25 @@ export class FunctionExpression extends Node { readonly scriptFunction: ScriptFunction } -export class Block extends Node { +export class BlockStatement extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.Block) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT) super(peer) this.statements = unpackNodeArray(nativeModule._BlockStatementStatements(global.context, this.peer)) } static create( - statements: Node[] - ): Block { - return new Block( - nativeModule._CreateBlockStatement( - global.context, - passNodeArray(statements), - statements.length + node: undefined | BlockStatement, + statements: Node[], + ): BlockStatement { + return new BlockStatement( + updatePeerByNode( + nativeModule._CreateBlockStatement( + global.context, + passNodeArray(statements), + statements.length + ), + node ) ) } @@ -708,19 +868,23 @@ export class Block extends Node { export class ETSParameterExpression extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ETSParameterExpression) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION) super(peer) } static create( + node: undefined | ETSParameterExpression, identifier: Identifier, initializer: Node | undefined ): ETSParameterExpression { return new ETSParameterExpression( - nativeModule._CreateETSParameterExpression( - global.context, - passNode(identifier), - passNode(initializer) + updatePeerByNode( + nativeModule._CreateETSParameterExpression( + global.context, + passNode(identifier), + passNode(initializer) + ), + node ) ) } @@ -728,22 +892,26 @@ export class ETSParameterExpression extends Node { export class TSTypeParameterDeclaration extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.TSTypeParameterDeclaration) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION) super(peer) this.parameters = unpackNodeArray(nativeModule._TSTypeParameterDeclarationParamsConst(global.context, this.peer, NULLPTR)) } // TODO: think about valid type of parameters static create( + node: undefined | TSTypeParameterDeclaration, parameters: Node[], ): TSTypeParameterDeclaration { return new TSTypeParameterDeclaration( - nativeModule._CreateTSTypeParameterDeclaration( - global.context, - passNodeArray(parameters), - parameters.length, - // TODO: fix - parameters.length + updatePeerByNode( + nativeModule._CreateTSTypeParameterDeclaration( + global.context, + passNodeArray(parameters), + parameters.length, + // TODO: fix + parameters.length + ), + node ) ) } @@ -753,12 +921,13 @@ export class TSTypeParameterDeclaration extends Node { export class TSTypeParameter extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.TSTypeParameter) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER) super(peer) this.name = unpackNonNullableNode(nativeModule._TSTypeParameterName(global.context, this.peer)) } static create( + node: undefined | TSTypeParameter, name: Identifier, constraint: Node | undefined, defaultType: Node | undefined, @@ -772,7 +941,9 @@ export class TSTypeParameter extends Node { ) nativeModule._AstNodeClearModifier(global.context, peer, ALL_FLAGS) nativeModule._AstNodeAddModifier(global.context, peer, modifierFlags) - return new TSTypeParameter(peer) + return new TSTypeParameter( + updatePeerByNode(peer, node) + ) } readonly name: Identifier @@ -780,7 +951,7 @@ export class TSTypeParameter extends Node { export class ReturnStatement extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ReturnStatement) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT) super(peer) this.argument = unpackNode( nativeModule._ReturnStatementArgument(global.context, this.peer) @@ -788,12 +959,16 @@ export class ReturnStatement extends Node { } static create( - argument: Node + node: undefined | ReturnStatement, + argument: Node, ): ReturnStatement { return new ReturnStatement( - nativeModule._CreateReturnStatement1( - global.context, - passNode(argument) + updatePeerByNode( + nativeModule._CreateReturnStatement1( + global.context, + passNode(argument) + ), + node ) ) } @@ -803,21 +978,25 @@ export class ReturnStatement extends Node { export class IfStatement extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.IfStatement) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT) super(peer) } static create( + node: undefined | IfStatement, test: Node, consequent: Node, alternate?: Node ): IfStatement { return new IfStatement( - nativeModule._CreateIfStatement( - global.context, - passNode(test), - passNode(consequent), - passNode(alternate) + updatePeerByNode( + nativeModule._CreateIfStatement( + global.context, + passNode(test), + passNode(consequent), + passNode(alternate) + ), + node ) ) } @@ -825,18 +1004,22 @@ export class IfStatement extends Node { export class ClassDeclaration extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ClassDeclaration) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION) super(peer) this.definition = unpackNonNullableNode(nativeModule._ClassDeclarationDefinition(global.context, this.peer)) } static create( - definition: ClassDefinition + node: undefined | ClassDeclaration, + definition: ClassDefinition, ): ClassDeclaration { return new ClassDeclaration( - nativeModule._CreateClassDeclaration( - global.context, - passNode(definition) + updatePeerByNode( + nativeModule._CreateClassDeclaration( + global.context, + passNode(definition) + ), + node ) ) } @@ -846,7 +1029,7 @@ export class ClassDeclaration extends Node { export class ClassDefinition extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ClassDefinition) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION) super(peer) this.name = unpackNonNullableNode(nativeModule._ClassDefinitionIdent(global.context, this.peer)) this.members = unpackNodeArray(nativeModule._ClassDefinitionBody(global.context, this.peer)) @@ -854,23 +1037,26 @@ export class ClassDefinition extends Node { } static create( + node: undefined | ClassDefinition, name: Identifier | undefined, members: Node[], modifiers: KInt, classFlags: KInt, - lang: undefined + typeParamsDecl: TSTypeParameterDeclaration | undefined, + superClass?: Node, ): ClassDefinition { + const peer = nativeModule._CreateClassDefinition1( + global.context, + passNode(name), + passNodeArray(members), + members.length, + classFlags, + modifiers + ) + nativeModule._ClassDefinitionSetTypeParams(global.context, peer, passNode(typeParamsDecl)) + nativeModule._ClassDefinitionSetSuper(global.context, peer, passNode(superClass)) return new ClassDefinition( - nativeModule._CreateClassDefinition1( - global.context, - passNode(name), - passNodeArray(members), - members.length, - classFlags, - modifiers, - // TODO: fix lang - NULLPTR - ) + updatePeerByNode(peer, node) ) } @@ -879,15 +1065,35 @@ export class ClassDefinition extends Node { readonly typeParamsDecl?: TSTypeParameterDeclaration } +export class ClassStaticBlock extends Node { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK) + super(peer) + } + + // TODO: + // static create( + // value: Node + // ): ClassStaticBlock { + // return new ClassStaticBlock( + // nativeModule._CreateClassStaticBlock( + // global.context, + // passNode(value) + // ) + // ) + // } +} + export class MethodDefinition extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.MethodDefinition) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION) super(peer) this.scriptFunction = unpackNonNullableNode(nativeModule._MethodDefinitionFunction(global.context, this.peer)) this.name = unpackNonNullableNode(nativeModule._ScriptFunctionId(global.context, this.scriptFunction.peer)) } static create( + node: undefined | MethodDefinition, kind: Es2pandaMethodDefinitionKind, key: Node, value: Node, @@ -895,13 +1101,16 @@ export class MethodDefinition extends Node { isComputed: boolean ): MethodDefinition { return new MethodDefinition( - nativeModule._CreateMethodDefinition( - global.context, - kind, - passNode(key), - passNode(value), - modifiers, - isComputed + updatePeerByNode( + nativeModule._CreateMethodDefinition( + global.context, + kind, + passNode(key), + passNode(value), + modifiers, + isComputed + ), + node ) ) } @@ -912,11 +1121,12 @@ export class MethodDefinition extends Node { export class ClassProperty extends Node { constructor(peer: KPtr) { - assertValidPeer(peer, es2pandaKind.ClassProperty) + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY) super(peer) } static create( + node: undefined | ClassProperty, key: Node, value: Node, typeAnnotation: Node, @@ -924,14 +1134,197 @@ export class ClassProperty extends Node { isComputed: boolean ): ClassProperty { return new ClassProperty( - nativeModule._CreateClassProperty( + updatePeerByNode( + nativeModule._CreateClassProperty( + global.context, + passNode(key), + passNode(value), + passNode(typeAnnotation), + modifiers, + isComputed + ), + node + ) + ) + } +} + +export class VariableDeclaration extends Node { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION) + super(peer) + this.declarationKind = nativeModule._VariableDeclarationKindConst(global.context, this.peer) + this.declarators = unpackNodeArray(nativeModule._VariableDeclarationDeclaratorsConst(global.context, this.peer)) + } + + static create( + node: undefined | VariableDeclaration, + modifiers: KInt, + kind: Es2pandaVariableDeclarationKind, + declarators: readonly VariableDeclarator[], + declare: boolean, + ): VariableDeclaration { + const peer = updatePeerByNode( + nativeModule._CreateVariableDeclaration( + global.context, + kind, + passNodeArray(declarators), + declarators.length, + declare + ), + node + ) + nativeModule._AstNodeClearModifier(global.context, peer, ALL_FLAGS) + nativeModule._AstNodeAddModifier(global.context, peer, modifiers) + return new VariableDeclaration(peer) + } + + readonly declarationKind: Es2pandaVariableDeclarationKind + readonly declarators: readonly VariableDeclarator[] +} + +export class VariableDeclarator extends Node { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR) + super(peer) + this.name = unpackNonNullableNode(nativeModule._VariableDeclaratorId(global.context, this.peer)) + } + + static create( + node: undefined | VariableDeclarator, + flag: Es2pandaVariableDeclaratorFlag, + name: Identifier, + initializer: Node | undefined + ): VariableDeclarator { + const peer = updatePeerByNode( + nativeModule._CreateVariableDeclarator( global.context, - passNode(key), - passNode(value), - passNode(typeAnnotation), - modifiers, - isComputed + flag, + passNode(name) + ), + node + ) + if (initializer !== undefined) { + nativeModule._VariableDeclaratorSetInit(global.context, peer, initializer.peer) + } + return new VariableDeclarator(peer) + } + + readonly name: Identifier +} + +export class ETSUndefinedType extends Node { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE) + super(peer) + } +} + +export class SuperExpression extends Node { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION) + super(peer) + } + + static create( + node: undefined | SuperExpression, + ): SuperExpression { + return new SuperExpression( + updatePeerByNode( + nativeModule._CreateSuperExpression( + global.context, + ), + node + ) + ) + } +} + +export class ImportSource extends ArktsObject { + constructor(peer: KPtr) { + super(peer) + } + + static create( + source: StringLiteral, + hasDecl: boolean, + ): ImportSource { + return new ImportSource( + nativeModule._CreateImportSource( + global.context, + source.peer, + resolveSource(source).peer, + hasDecl ) ) } } + +export class EtsImportDeclaration extends Node { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION) + super(peer) + this.importSource = unpackNonNullableNode(nativeModule._ETSImportDeclarationSourceConst(global.context, this.peer)) + this.resolvedSource = unpackNonNullableNode(nativeModule._ETSImportDeclarationResolvedSource(global.context, this.peer)) + this.hasDecl = nativeModule._ETSImportDeclarationHasDeclConst(global.context, this.peer) + } + + static create( + node: undefined | EtsImportDeclaration, + source: StringLiteral, + specifiers: readonly ImportSpecifier[], + importKind: Es2pandaImportKinds, + hasDecl: boolean, + ): EtsImportDeclaration { + return new EtsImportDeclaration( + updatePeerByNode( + nativeModule._CreateETSImportDeclaration( + global.context, + ImportSource.create( + source, + hasDecl, + ).peer, + passNodeArray(specifiers), + specifiers.length, + importKind + ), + node + ) + ) + } + + readonly importSource: StringLiteral + readonly resolvedSource: StringLiteral + readonly hasDecl: boolean +} + +export class ImportSpecifier extends Node { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER) + super(peer) + } + + static create( + node: undefined | ImportSpecifier, + imported: Identifier, + local: Identifier, + ): ImportSpecifier { + return new ImportSpecifier( + updatePeerByNode( + nativeModule._CreateImportSpecifier( + global.context, + passNode(imported), + passNode(local), + ), + node + ) + ) + } +} + +export class UndefinedLiteral extends Node { + constructor(peer: KPtr) { + assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL) + super(peer) + } +} diff --git a/arkoala-arkts/libarkts/src/node/Platform.ts b/arkoala-arkts/libarkts/src/arkts-api/utilities/nativePtrDecoder.ts similarity index 95% rename from arkoala-arkts/libarkts/src/node/Platform.ts rename to arkoala-arkts/libarkts/src/arkts-api/utilities/nativePtrDecoder.ts index 5cef4ade1..e03bccc31 100644 --- a/arkoala-arkts/libarkts/src/node/Platform.ts +++ b/arkoala-arkts/libarkts/src/arkts-api/utilities/nativePtrDecoder.ts @@ -15,7 +15,7 @@ import { int32 } from "@koalaui/common" import { Access, NativeStringBase, nullptr, pointer as NativePtr, withByteArray, providePlatformDefinedData, ArrayDecoder, CallbackRegistry, Wrapper, pointer } from "@koalaui/interop" -import { nativeModule } from "../NativeModule" +import { nativeModule } from "../../nativeModule" class NativeString extends NativeStringBase { constructor(ptr: NativePtr) { diff --git a/arkoala-arkts/libarkts/src/arkts-api/utilities/private.ts b/arkoala-arkts/libarkts/src/arkts-api/utilities/private.ts new file mode 100644 index 000000000..e851fa595 --- /dev/null +++ b/arkoala-arkts/libarkts/src/arkts-api/utilities/private.ts @@ -0,0 +1,186 @@ +/* + * 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 arkts from ".." +import * as fs from "fs" +import global from "../static/global" +import { throwError } from "../../utils" + +import { KNativePointer, withString, withStringResult, withStringArray, KInt } from "@koalaui/interop" +import { nativeModule } from "../../nativeModule" +import { NativePtrDecoder } from "./nativePtrDecoder" +import { + Es2pandaAstNodeType, + Es2pandaScriptFunctionFlags, +} from "../static/enums" + +export function classByPeer(peer: KNativePointer): { new (peer: KNativePointer): arkts.Node } { + const types = new Map([ + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_SCRIPT, arkts.EtsScript], + [Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER, arkts.Identifier], + [Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL, arkts.StringLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL, arkts.NumberLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT, arkts.ExpressionStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION, arkts.FunctionDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION, arkts.ScriptFunction], + [Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, arkts.BlockStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT, arkts.ReturnStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, arkts.ETSParameterExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, arkts.ETSTypeReference], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, arkts.ETSTypeReferencePart], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION, arkts.TSTypeParameterDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE, arkts.ETSPrimitiveType], + [Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION, arkts.CallExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION, arkts.MemberExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER, arkts.TSTypeParameter], + [Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT, arkts.IfStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION, arkts.BinaryExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE, arkts.ETSUnionType], + [Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, arkts.ArrowFunctionExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION, arkts.ClassDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION, arkts.ClassDefinition], + [Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION, arkts.MethodDefinition], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY, arkts.ClassProperty], + [Es2pandaAstNodeType.AST_NODE_TYPE_ASSIGNMENT_EXPRESSION, arkts.AssignmentExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION, arkts.VariableDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR, arkts.VariableDeclarator], + [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION, arkts.FunctionExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE, arkts.ETSFunctionType], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK, arkts.ClassStaticBlock], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE, arkts.ETSUndefinedType], + [Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL, arkts.UndefinedLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION, arkts.SuperExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION, arkts.EtsImportDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER, arkts.ImportSpecifier], + ]) + + if (peer === arkts.NULLPTR) { + throwError('classByPeer: peer is NULLPTR') + } + const type = nativeModule._AstNodeTypeConst(global.context, peer) + return types.get(type) ?? arkts.UnsupportedNode +} + +export function unpackNonNullableNode(peer: KNativePointer): T { + if (peer === arkts.NULLPTR) { + throwError('peer is NULLPTR (maybe you should use unpackNode)') + } + return (new (classByPeer(peer))(peer)) as T +} + +export function unpackNode(peer: KNativePointer): T | undefined { + if (peer === arkts.NULLPTR) { + return undefined + } + return (new (classByPeer(peer))(peer)) as T +} + +export function passNode(node: arkts.Node | undefined): KNativePointer { + return node?.peer ?? arkts.NULLPTR +} + +// meaning unpackNonNullableNodeArray +export function unpackNodeArray(nodesPtr: KNativePointer): readonly T[] { + if (nodesPtr === arkts.NULLPTR) { + throwError('nodesPtr is NULLPTR (maybe you should use unpackNodeArray)') + } + return (new NativePtrDecoder).decode(nodesPtr).map((peer: KNativePointer) => unpackNonNullableNode(peer)) +} + +export function passNodeArray(nodes: readonly arkts.Node[] | undefined): BigUint64Array { + return new BigUint64Array( + nodes === undefined + ? [] + : nodes.map(node => BigInt(node.peer)) + ) +} + +export function unpackNonNullableObject(type: { new (peer: KNativePointer): T }, peer: KNativePointer): T { + if (peer === arkts.NULLPTR) { + throwError('peer is NULLPTR (maybe you should use unpackObject)') + } + return new type(peer) +} + +export function unpackObject(type: { new (peer: KNativePointer): T }, peer: KNativePointer): T | undefined { + if (peer === arkts.NULLPTR) { + return undefined + } + return new type(peer) +} + +export function unpackString(peer: KNativePointer): string { + return withStringResult(peer) ?? throwError(`failed to unpack (peer shouldn't be NULLPTR)`) +} + +export function passString(str: string | undefined): string { + if (str === undefined) { + return "" + } + return withString(str, (it: string) => it) +} + +export function passStringArray(strings: string[]): string[] { + return withStringArray(strings, (it: string[]) => it) +} + +export function passNodeWithNewModifiers(node: T, modifiers: KInt): T { + return (unpackNonNullableNode(node.peer) as T).updateModifiers(modifiers) +} + +export function scriptFunctionHasBody(peer: KNativePointer): boolean { + const flags = nativeModule._ScriptFunctionFlagsConst(global.context, peer) + return (flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL) === 0 + && (flags & Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_EXTERNAL_OVERLOAD) === 0 +} + +// TODO: remove this +// TODO: update scopes and other data +export function updatePeerByNode(peer: KNativePointer, original: T | undefined): KNativePointer { + if (peer === arkts.NULLPTR) { + throwError('updatePeerByNode called on NULLPTR') + } + if (original === undefined) { + return peer + } + nativeModule._AstNodeSetOriginalNode(global.context, peer, original.peer) + nativeModule._AstNodeSetParent(global.context, peer, nativeModule._AstNodeParent(global.context, original.peer)) + nativeModule._AstNodeUpdateChildren(global.context, peer) + nativeModule._AstNodeClearModifier(global.context, peer, arkts.ALL_FLAGS) + nativeModule._AstNodeAddModifier(global.context, peer, original.modifiers) + nativeModule._AstNodeUpdateChildren(global.context, peer) + return peer +} + +// TODO: update scopes and other data +export function updateNodeByNode(node: T, original: arkts.Node): T { + if (original.peer === arkts.NULLPTR) { + throwError('update called on NULLPTR') + } + nativeModule._AstNodeSetOriginalNode(global.context, node.peer, original.peer) + nativeModule._AstNodeSetParent(global.context, node.peer, nativeModule._AstNodeParent(global.context, original.peer)) + nativeModule._AstNodeUpdateChildren(global.context, node.peer) + nativeModule._AstNodeClearModifier(global.context, node.peer, arkts.ALL_FLAGS) + nativeModule._AstNodeAddModifier(global.context, node.peer, original.modifiers) + nativeModule._AstNodeUpdateChildren(global.context, node.peer) + return node +} + +export function resolveSource(source: arkts.StringLiteral): arkts.StringLiteral { + return arkts.StringLiteral.create( + undefined, + fs.readFileSync(`../../../input/${source.str}.sts`).toString() + ) +} diff --git a/arkoala-arkts/libarkts/src/api/utilities/utilitiesPublic.ts b/arkoala-arkts/libarkts/src/arkts-api/utilities/public.ts similarity index 42% rename from arkoala-arkts/libarkts/src/api/utilities/utilitiesPublic.ts rename to arkoala-arkts/libarkts/src/arkts-api/utilities/public.ts index 745a8d9cc..4c670db6c 100644 --- a/arkoala-arkts/libarkts/src/api/utilities/utilitiesPublic.ts +++ b/arkoala-arkts/libarkts/src/arkts-api/utilities/public.ts @@ -14,12 +14,24 @@ */ import global from "../static/global" -import { nativeModule } from "../../NativeModule" +import { throwError } from "../../utils" +import * as arkts from "../../arkts-api" +import { nativeModule } from "../../nativeModule" import { KNativePointer, withString, withStringArray, withStringResult } from "@koalaui/interop" import { - ContextState, + Es2pandaContextState, } from "../static/enums" +export function getAstFromContext(): KNativePointer { + return nativeModule._ProgramAst(nativeModule._ContextProgram(global.context)) +} + +export function createAstDumper(peer: KNativePointer, source: string): KNativePointer { + return withString(source, (_source: string) => { + return nativeModule._CreateAstDumper(global.context, peer, _source) + }) +} + export function createConfig(input: string[]): KNativePointer { return withStringArray(input, (stringArray: string[]) => { return nativeModule._CreateConfig(input.length, stringArray) @@ -34,19 +46,22 @@ export function createContextFromString(config: KNativePointer, source: string, }) } -export function proceedToState(state: ContextState): void { +export function proceedToState(state: Es2pandaContextState): void { if (state <= nativeModule._ContextState(global.context)) { return } - nativeModule._ProceedToState(global.context, state) - if (nativeModule._ContextState(global.context) === ContextState.ES2PANDA_STATE_ERROR) { - // TODO: maybe shoudn't do it here - nativeModule._DestroyContext(global.context) - const errorMessage = withStringResult(nativeModule._ContextErrorMessage(global.context)) - if (errorMessage === undefined) { - global.throwError(`COULDN'T GET: _ContextErrorMessage`) + try { + nativeModule._ProceedToState(global.context, state) + if (nativeModule._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR) { + const errorMessage = withStringResult(nativeModule._ContextErrorMessage(global.context)) + if (errorMessage === undefined) { + throwError(`COULDN'T GET ContextErrorMessage`) + } + throwError("FAILED PROCEED TO: " + Es2pandaContextState[state] + "\n" + errorMessage) } - global.throwError("FAILED PROCEED TO: " + ContextState[state] + "\n" + errorMessage) + } catch (e) { + nativeModule._DestroyContext(global.context) + throw e } } @@ -54,27 +69,33 @@ export function startChecker(): boolean { return nativeModule._CheckerStartChecker(global.context) } -// export function getDecl(node: arkts.Node): arkts.Node | undefined { -// let decl = node.peer -// decl = nativeModule._AstNodeVariableConst(global.context, decl) -// if (decl === arkts.NULLPTR) { -// return undefined -// } -// decl = nativeModule._VariableDeclaration(global.context, decl) -// if (decl === arkts.NULLPTR) { -// return undefined -// } -// decl = nativeModule._DeclNode(global.context, decl) -// if (decl === arkts.NULLPTR) { -// return undefined -// } -// return nodeByPeer(decl) -// } +export function getDecl(node: arkts.Node): arkts.Node | undefined { + if (node === undefined) { + throwError('there is no arkts pair of ts node (unable to getDecl)') + } + let decl: KNativePointer = node.peer + decl = nativeModule._AstNodeVariableConst(global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + decl = nativeModule._VariableDeclaration(global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + decl = nativeModule._DeclNode(global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + return arkts.unpackNonNullableNode(decl) +} -// export function getOriginalNode(node: arkts.Node): arkts.Node { -// const peer = nativeModule._AstNodeOriginalNodeConst(global.context, node.peer) -// if (peer === arkts.NULLPTR) { -// return node -// } -// return nodeByPeer(peer) -// } +export function getOriginalNode(node: arkts.Node): arkts.Node { + if (node === undefined) { + // TODO: fix this + throwError('there is no arkts pair of ts node (unable to getOriginalNode)') + } + if (node.originalPeer === arkts.NULLPTR) { + return node + } + return arkts.unpackNonNullableNode(node.originalPeer) +} diff --git a/arkoala-arkts/libarkts/src/es2panda.ts b/arkoala-arkts/libarkts/src/es2panda.ts index 7c46fb7da..b5aac6a84 100644 --- a/arkoala-arkts/libarkts/src/es2panda.ts +++ b/arkoala-arkts/libarkts/src/es2panda.ts @@ -1,16 +1,18 @@ import { Command } from "commander" import * as fs from "fs" import * as path from "path" -import * as arkts from "./api" -import global from "./api/global" -import { - generateBin, - runAbc, -} from "../test/test-util" +import * as arkts from "./arkts-api" +import * as ts from "./ts-api" +import global from "./arkts-api/static/global" +import { webpackUnoptimizableImport } from "./utils" +// import { +// contextToAbc, +// runAbc, +// } from "../test/test-util" function parseCommandLineArgs() { const commander = new Command() - .option('--file, ', 'Path to file to be compiled', './input/main.ets') + .option('--file, ', 'Path to file to be compiled', './input/main.sts') .option('--arktsconfig, ', 'Path to arkts configuration file', './arktsconfig.json') .parse(process.argv) .opts() @@ -27,7 +29,7 @@ function parseCommandLineArgs() { return { filePath, configPath } } -function es2panda(configPath: string, filePath: string, transform: (ast: arkts.Node) => arkts.Node) { +function es2panda(configPath: string, filePath: string, transform: (ast: ts.Node) => ts.Node) { const source = fs.readFileSync(filePath).toString() global.config = arkts.createConfig([ '_', @@ -36,42 +38,40 @@ function es2panda(configPath: string, filePath: string, transform: (ast: arkts.N filePath ]) global.context = arkts.createContextFromString(global.config, source, filePath) - arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_PARSED) - const program = arkts.contextProgram() - const ast = arkts.programAst(program) + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) + const ast = ts.unpackNode(arkts.unpackNode(arkts.getAstFromContext())) as ts.SourceFile transform(ast) // TODO: this should be called after executing all plugins - generateBin() - runAbc() + // contextToAbc() + // runAbc(`./generated/main.abc`) } -function plugins(configPath: string): Promise<((ast: arkts.Node) => arkts.Node)[]> { +function plugins(configPath: string): Promise<((ast: ts.Node) => ts.Node)[]> { const config = JSON.parse(fs.readFileSync(configPath).toString()) const plugins = config['compilerOptions']['plugins'] return Promise.all(plugins.map(async (jsonPlugin: any) => { - const pluginPath = jsonPlugin['transform'] + const pluginPath = path.resolve(jsonPlugin['transform']) // TODO: read and pass plugin options const options = {} - - function webpackUnoptimizableImport(path: string): { default: any } { - return require(/* webpackIgnore: true */ path) - } // TODO: fix this require - const module = require('../compatible/src/example-transformer.ts') + // const module = require(/* webpackIgnore: true */ '../compatible/src/example-transformer.ts') // const module = require(pluginPath) - // const module = webpackUnoptimizableImport(pluginPath) + const module = webpackUnoptimizableImport(pluginPath) return module.default()() })) } const { filePath, configPath } = parseCommandLineArgs() -plugins(configPath).then(plugins => { - es2panda(configPath, filePath, (ast: arkts.Node) => { - return plugins.reduce((ast, plugin) => plugin(ast), ast) - }) -}) +plugins(configPath).then(plugins => + es2panda(configPath, filePath, (ast: ts.Node) => + plugins.reduce( + (ast, plugin) => plugin(ast), + ast + ) + ) +) diff --git a/arkoala-arkts/libarkts/src/nativeModule.ts b/arkoala-arkts/libarkts/src/nativeModule.ts new file mode 100644 index 000000000..0ba0c3051 --- /dev/null +++ b/arkoala-arkts/libarkts/src/nativeModule.ts @@ -0,0 +1,202 @@ +/* + * 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 { KNativePointer as KPtr, KInt, KBoolean, KNativePointer } from "@koalaui/interop" + +// TODO: this type should be in interop +export type KPtrArray = BigUint64Array + +export interface NativeModule { + _ContextState(context: KPtr): KInt + _ContextErrorMessage(context: KPtr): KPtr + _AstNodeChildren(context: KPtr, node: KPtr): KPtr + _ETSParserCreateExpression(context: KPtr, sourceCode: String, flags: KInt): KPtr + _AstNodeDumpModifiers(context: KPtr, node: KPtr): KPtr + _CreateAstDumper(context: KPtr, node: KPtr, source: String): KPtr + _AstDumperModifierToString(context: KPtr, dumper: KPtr, flags: KInt): KPtr + + _CreateConfig(argc: number, argv: string[]): KPtr + _DestroyConfig(config: KPtr): void + _CreateContextFromString(config: KPtr, source: String, filename: String): KPtr + _CreateContextFromFile(config: KPtr, filename: String): KPtr + _DestroyContext(context: KPtr): void + _ProceedToState(context: KPtr, state: number): void + _ContextProgram(context: KPtr): KPtr + _ProgramAst(program: KPtr): KPtr + _CheckerStartChecker(context: KPtr): KBoolean + _VarBinderIdentifierAnalysis(context: KPtr): void + _VarBinderInitTopScope(context: KPtr): void + _VarBinderSetGenStdLib(context: KPtr, genStdLibT: KBoolean): void + + _StringLength(ptr: KPtr): KInt + _StringData(ptr: KPtr, buffer: KPtr, length: KInt): void + _GetStringFinalizer(): KPtr + _InvokeFinalizer(ptr: KPtr, finalizer: KPtr): void + _GetPtrVectorSize(ptr: KPtr): KInt + _GetPtrVectorElement(ptr: KPtr, index: KInt): KPtr + + _SourceFileGetChildren(node: KPtr): KPtr + _BlockGetStatements(node: KPtr): KPtr + _FunctionDeclarationIsAnonymousConst(context: KPtr, node: KPtr): KBoolean + _ExpressionStatementGetExpression(context: KPtr, node: KPtr): KPtr + _CallExpressionArguments(context: KPtr, node: KPtr, returnLen: KPtr): KPtr + _CallExpressionCallee(context: KPtr, node: KPtr): KPtr + _IdentifierGetText(node: KPtr): KPtr + _IdentifierIsPrivateIdentConst(context: KPtr, node: KPtr): KBoolean + _PropertyAccessExpressionGetExpression(node: KPtr): KPtr + _PropertyAccessExpressionGetName(node: KPtr): KPtr + + _FunctionDeclarationFunction(context: KPtr, node: KPtr): KPtr + _ScriptFunctionSignature(context: KPtr, node: KPtr): KPtr + _ScriptFunctionParams(context: KPtr, node: KPtr): KPtr + _ScriptFunctionId(context: KPtr, node: KPtr): KPtr + _ScriptFunctionBody(context: KPtr, node: KPtr): KPtr + _ScriptFunctionSetIdent(context: KPtr, ast: KPtr, id: KPtr): KPtr + _ScriptFunctionIrSignature(context: KPtr, ast: KPtr): KPtr + _ScriptFunctionSetSignature(context: KPtr, ast: KPtr, signature: KPtr): KPtr + _ScriptFunctionSetBody(context: KPtr, ast: KPtr, body: KPtr): KPtr + _ScriptFunctionSetScope(context: KPtr, ast: KPtr, scope: KPtr): KPtr + _ScriptFunctionDeclareConst(context: KPtr, node: KPtr): KBoolean + _ScriptFunctionFlagsConst(context: KPtr, node: KPtr): KInt + _ScriptFunctionTypeParams(context: KPtr, node: KPtr): KPtr + _ScriptFunctionReturnTypeAnnotation(context: KPtr, node: KPtr): KPtr + _ScriptFunctionAddFlag(context: KPtr, node: KPtr, flags: KInt): void + _UpdateBlockStatement(context: KPtr, original: KPtr, statementList: KPtrArray, statementListLen: KInt): KPtr + _BlockStatementSetScope(context: KPtr, node: KPtr, scope: KPtrArray): void + _CreateIdentifier1(context: KPtr, name: String): KPtr + _CreateIdentifier2(context: KPtr, name: String, type_annotation: KPtr): KPtr + _IdentifierSetName(context: KPtr, node: KPtr, name: String): void + _IdentifierIdentifierFlags(context: KPtr, node: KPtr): KInt + _CreateFunctionDeclaration(context: KPtr, func: KPtr, annotations: KPtrArray, annotationsLen: KInt, isAnon: KBoolean): KPtr + _UpdateFunctionDeclaration(context: KPtr, node: KPtr, annotations: KPtrArray, annotationsLen: KInt, func: KPtr, isAnon: KBoolean): KPtr + _CreateReturnStatement1(context: KPtr, argument: KPtr): KPtr + _ReturnStatementArgument(context: KPtr, node: KPtr): KPtr + _CreateIfStatement(context: KPtr, test: KPtr, consequent: KPtr, alternate: KPtr): KPtr + _CreateBinaryExpression(context: KPtr, left: KPtr, right: KPtr, operatorType: KInt): KPtr + _CreateAssignmentExpression(context: KPtr, left: KPtr, right: KPtr, assignmentOperator: KInt): KPtr + _CreateMethodDefinition(context: KPtr, kind: KInt, key: KPtr, value: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr + _CreateClassProperty(context: KPtr, key: KPtr, value: KPtr, typeAnnotation: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr + _CreateETSImportDeclaration(context: KPtr, source: KPtr, specifiers: KPtrArray, specifiersLen: KInt, importKind: KInt): KNativePointer + _ETSImportDeclarationSourceConst(context: KPtr, node: KPtr): KPtr + _ETSImportDeclarationResolvedSource(context: KPtr, node: KPtr): KPtr + _ETSImportDeclarationHasDeclConst(context: KPtr, node: KPtr): KBoolean + _CreateImportSource(context: KPtr, source: KPtr, resolvedSource: KPtr, hasDecl: KBoolean): KNativePointer + _CreateImportSpecifier(context: KPtr, imported: KPtr, local: KPtr): KNativePointer + + _CreateFunctionSignature(context: KPtr, typeParams: KPtr, params: KPtrArray, paramsLen: KInt, returnTypeAnnotation: KPtr): KPtr + _CreateScriptFunction(context: KPtr, databody: KPtr, datasignature: KPtr, datafuncFlags: KInt, dataflags: KInt, datadeclare: KBoolean): KPtr + _UpdateScriptFunction(context: KPtr, original: KPtr, databody: KPtr, datasignature: KPtr, datafuncFlags: KInt, dataflags: KInt, datadeclare: KBoolean): KPtr + _CreateBlockStatement(context: KPtr, statementList: KPtrArray, statementListLen: KInt): KPtr + _AstNodeScopeConst(context: KPtr, ast: KPtr): KPtr + _AstNodeParent(context: KPtr, ast: KPtr): KPtr + _AstNodeSetParent(context: KPtr, ast: KPtr, parent: KPtr): KPtr + _AstNodeClone(context: KPtr, ast: KPtr, parent: KPtr): KPtr + _AstNodeModifiers(context: KPtr, ast: KPtr): KInt + _AstNodeAddModifier(context: KPtr, ast: KPtr, flags: KInt): void + _AstNodeClearModifier(context: KPtr, ast: KPtr, flags: KInt): void + _AstNodeVariableConst(context: KPtr, ast: KPtr): KPtr + _AstNodeTypeConst(context: KPtr, ast: KPtr): KInt + _FunctionSignatureTypeParams(context: KPtr, ast: KPtr): KPtr + _FunctionSignatureReturnType(context: KPtr, ast: KPtr): KPtr + _FunctionSignatureParamsConst(context: KPtr, ast: KPtr, returnTypeLen: KPtr): KPtr + _UpdateIdentifier1(context: KPtr, ast: KPtr, name: string): KPtr + _UpdateIdentifier2(context: KPtr, ast: KPtr, name: string, typeAnnotation: KPtr): KPtr + _UpdateMethodDefinition(context: KPtr, node: KPtr, kind: KInt, key: KPtr, value: KPtr, modifiers: KInt, isComputed: KBoolean): KPtr + _MethodDefinitionFunction(context: KPtr, node: KPtr): KPtr + _MethodDefinitionKindConst(context: KPtr, node: KPtr): KInt + + _CreateMemberExpression(context: KPtr, object: KPtr, property: KPtr, kind: KInt, computed: KBoolean, optional: KBoolean): KPtr + _UpdateMemberExpression(context: KPtr, node: KPtr, object: KPtr, property: KPtr, kind: KInt, computed: KBoolean, optional: KBoolean): KPtr + _MemberExpressionObject(context: KPtr, node: KPtr): KPtr + _MemberExpressionProperty(context: KPtr, node: KPtr): KPtr + _MemberExpressionKindConst(context: KPtr, node: KPtr): KInt + _CreateCallExpression(context: KPtr, callee: KPtr, args: KPtrArray, argsLen: KInt, typeParams: KPtr, optional: KBoolean, trailingComma: KBoolean): KPtr + _UpdateCallExpression(node: KPtr, context: KPtr, callee: KPtr, args: KPtrArray, argsLen: KInt, typeParams: KPtr, optional: KBoolean, trailingComma: KBoolean): KPtr + _CreateArrowFunctionExpression(context: KPtr, node: KPtr): KPtr + _FunctionExpressionFunction(context: KPtr, node: KPtr): KPtr + _ArrowFunctionExpressionFunction(context: KPtr, node: KPtr): KPtr + _ArrowFunctionExpressionCreateTypeAnnotation(context: KPtr, node: KPtr): KPtr + _CreateFunctionExpression(context: KPtr, node: KPtr): KPtr + _UpdateFunctionExpression(context: KPtr, original: KPtr, node: KPtr): KPtr + + _CreateExpressionStatement(context: KPtr, expr: KPtr): KPtr + _UpdateExpressionStatement(context: KPtr, node: KPtr, expr: KPtr): KPtr + _CreateETSParameterExpression(context: KPtr, identifier: KPtr, initializer: KPtr): KPtr + _CreateETSPrimitiveType(context: KPtr, type: KInt): KPtr + _ETSPrimitiveTypeGetPrimitiveTypeConst(context: KPtr, node: KNativePointer): KInt + _CreateETSTypeReference(context: KPtr, part: KPtr): KPtr + _CreateETSTypeReferencePart(context: KPtr, name: KPtr, typeParams: KPtr, prev: KPtr): KPtr + _CreateETSTypeReferencePart1(context: KPtr, name: KPtr): KPtr + _IsIdentifier(node: KPtr): KBoolean + _IdentifierName(context: KPtr, node: KPtr): KPtr + _ETSParameterExpressionIdent(context: KPtr, node: KPtr): KPtr + _CreateTSTypeParameterDeclaration(context: KPtr, params: KPtrArray, paramsLen: KInt, requiredParams: KInt): KPtr + _TSTypeParameterDeclarationParamsConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr + _CreateTSTypeParameter(context: KPtr, name: KPtr, constraint: KPtr, defaultType: KPtr): KPtr + _TSTypeParameterName(context: KPtr, node: KPtr): KPtr + + _CreateTSUnionType(context: KPtr, types: KPtrArray, typesLen: KInt): KPtr + _TSUnionTypeTypesConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr + _CreateETSUnionTypeIr(context: KPtr, types: KPtrArray, typesLen: KInt): KPtr + _ETSUnionTypeIrTypesConst(context: KPtr, node: KPtr, returnTypeLen: KPtr): KPtr + + _CreateVariableDeclaration(context: KPtr, kind: KInt, declarators: KPtrArray, declaratorsLen: KInt, declare: KBoolean): KPtr + _UpdateVariableDeclaration(context: KPtr, original: KPtr, kind: KInt, declarators: KPtrArray, declaratorsLen: KInt, declare: KBoolean): KPtr + _CreateVariableDeclarator(context: KPtr, flag: KInt, ident: KPtr): KPtr + _VariableDeclarationDeclaratorsConst(context: KPtr, node: KPtr): KPtr + _VariableDeclarationKindConst(context: KPtr, node: KPtr): KInt + _VariableDeclaratorId(context: KPtr, node: KPtr): KPtr + _VariableDeclaratorSetInit(context: KPtr, node: KPtr, init: KPtr): void + + _CreateStringLiteral(context: KPtr, string: string): KPtr + _CreateNumberLiteral(context: KPtr, string: string): KPtr + _NumberLiteralStrConst(context: KPtr, node: KPtr): KPtr + _StringLiteralStrConst(context: KPtr, node: KPtr): KPtr + + _BlockStatementStatements(context: KPtr, node: KPtr): KPtr + _BlockStatementSetStatements(context: KPtr, node: KPtr, statements: KPtrArray, statementsLen: KInt): void + _ClassDeclarationDefinition(context: KPtr, node: KPtr): KPtr + _ClassDefinitionBody(context: KPtr, node: KPtr): KPtr + _ClassDefinitionIdent(context: KPtr, node: KPtr): KPtr + _ClassDefinitionTypeParamsConst(context: KPtr, node: KPtr): KPtr + _CreateClassDeclaration(context: KPtr, def: KPtr): KPtr + _UpdateClassDeclaration(context: KPtr, original: KPtr, def: KPtr): KPtr + _CreateClassDefinition1(context: KPtr, ident: KPtr, body: KPtrArray, bodyLen: KInt, modifiers: KInt, flags: KInt): KPtr + _ClassDefinitionSetTypeParams(context: KPtr, ast: KPtr, typeParams: KPtr): void + _ClassDefinitionSetSuper(context: KPtr, ast: KPtr, superClass: KPtr): void + _UpdateClassDefinition1(context: KPtr, original: KPtr, ident: KPtr, body: KPtrArray, bodyLen: KInt, modifiers: KInt, flags: KInt): KPtr + _CreateETSFunctionTypeIr(context: KPtr, signature: KPtr, funcFlags: KInt): KPtr + _CreateSuperExpression(context: KPtr): KPtr + _UpdateSuperExpression(context: KPtr, original: KPtr): KPtr + + _IsProgram(context: KPtr, node: KPtr): KBoolean + _AstNodeDumpJsonConst(context: KPtr, node: KPtr): KPtr + _AstNodeDumpEtsSrcConst(context: KPtr, node: KPtr): KPtr + _AstNodeUpdateChildren(context: KPtr, node: KPtr): void + _AstNodeUpdateAll(context: KPtr, node: KPtr): void + _AstNodeSetOriginalNode(context: KPtr, ast: KPtr, originalNode: KPtr): void + _AstNodeOriginalNodeConst(context: KPtr, ast: KPtr): KPtr + + _VarBinderSetProgram(context: KPtr): void + _VarBinderSetContext(context: KPtr): void + + _VariableDeclaration(context: KPtr, variable: KPtr): KPtr + _DeclNode(context: KPtr, decl: KPtr): KPtr + + _ScopeSetParent(context: KPtr, ast: KPtr, scope: KPtr): void +} + +console.log(process.cwd()) +export const nativeModule: NativeModule = require("../native/build/es2panda.node") diff --git a/arkoala-arkts/libarkts/src/api/factory/nodeFactory.ts b/arkoala-arkts/libarkts/src/ts-api/factory/nodeFactory.ts similarity index 65% rename from arkoala-arkts/libarkts/src/api/factory/nodeFactory.ts rename to arkoala-arkts/libarkts/src/ts-api/factory/nodeFactory.ts index 0a4a2041a..77b325828 100644 --- a/arkoala-arkts/libarkts/src/api/factory/nodeFactory.ts +++ b/arkoala-arkts/libarkts/src/ts-api/factory/nodeFactory.ts @@ -1,7 +1,6 @@ -import global from "../static/global" +import { throwError } from "../../utils" import * as ts from "@koalaui/ets-tsc" -import * as arkts from "../layers/arkts" -import { nativeModule } from "src/NativeModule" +import * as arkts from "../../arkts-api" import { passNode, @@ -10,18 +9,15 @@ import { passModifiersToScriptFunction, passModifiers, passIdentifier, -} from "../layers/ts/utilities" -import { - passString, - updateNode, - // updateModifiers, - // passTypeParams, -} from "../layers/arkts/utilities" -import { passTypeParams, -} from "./utilities" + passVariableDeclarationKind, +} from "../utilities/private" import { SyntaxKind, + NodeFlags, +} from "../static/enums" +import { + Es2pandaContextState, Es2pandaPrimitiveType, Es2pandaMethodDefinitionKind, Es2pandaModifierFlags, @@ -29,8 +25,8 @@ import { Es2pandaMemberExpressionKind, Es2pandaClassDefinitionModifiers, Es2pandaVariableDeclarationKind, - VariableDeclaratorFlag, -} from "../static/enums" + Es2pandaVariableDeclaratorFlag, +} from "../../arkts-api/static/enums" import { // ts types: Modifier, @@ -63,11 +59,16 @@ import { TypeParameterDeclaration, NumericLiteral, ClassDeclaration, - // VariableDeclaration, - // VariableDeclarationList, - // VariableStatement, + VariableDeclaration, + VariableDeclarationList, + VariableStatement, UnionTypeNode, -} from "../layers/ts/types" + SuperExpression, + ParenthesizedExpression, + ImportDeclaration, + ImportClause, + ImportSpecifier, +} from "../types" // TODO: add flags and base export function createNodeFactory() { @@ -111,14 +112,20 @@ export function createNodeFactory() { updateTypeParameterDeclaration, createClassDeclaration, updateClassDeclaration, - // createVariableDeclarationList, - // updateVariableDeclarationList, - // createVariableStatement, - // updateVariableStatement, - // createVariableDeclaration, - // updateVariableDeclaration, + createVariableDeclarationList, + updateVariableDeclarationList, + createVariableStatement, + updateVariableStatement, + createVariableDeclaration, + updateVariableDeclaration, createUnionTypeNode, updateUnionTypeNode, + createSuper, + updateSuper, + createParenthesizedExpression, + updateParenthesizedExpression, + // createImportDeclaration, + createImportSpecifier, } // @api @@ -127,8 +134,8 @@ export function createNodeFactory() { // endOfFileToken: EndOfFileToken, // flags: NodeFlags, // ): SourceFile; - function createSourceFile(source: string): SourceFile { - const node = arkts.Program.create(source) + function createSourceFile(source: string, state: Es2pandaContextState = Es2pandaContextState.ES2PANDA_STATE_PARSED): SourceFile { + const node = arkts.EtsScript.create(source, state) return new SourceFile(node) } @@ -147,8 +154,12 @@ export function createNodeFactory() { node: SourceFile, statements: readonly Statement[] ): SourceFile { - node.node.statements = passNodeArray(statements) - return new SourceFile(node.node) + return new SourceFile( + arkts.EtsScript.update( + node.node, + passNodeArray(statements) + ) + ) } // @api @@ -160,7 +171,7 @@ export function createNodeFactory() { typeAnnotation?: TypeNode | undefined ): Identifier { return new Identifier( - arkts.Identifier.create( + arkts.factory.createIdentifier( text, passNode(typeAnnotation) ) @@ -175,8 +186,12 @@ export function createNodeFactory() { function createStringLiteral( str: string ): StringLiteral { - const node = arkts.StringLiteral.create(str) - return new StringLiteral(node) + return new StringLiteral( + arkts.StringLiteral.create( + undefined, + str + ) + ) } // @api @@ -187,10 +202,14 @@ export function createNodeFactory() { function createNumericLiteral( str: string ): NumericLiteral { - const node = arkts.NumberLiteral.create(str) - return new NumericLiteral(node) + return new NumericLiteral( + arkts.NumberLiteral.create( + undefined, + str + ) + ) } -/* + // @api // createVariableDeclarationList( // declarations: readonly VariableDeclaration[], @@ -198,12 +217,17 @@ export function createNodeFactory() { // ): VariableDeclarationList function createVariableDeclarationList( declarations: readonly VariableDeclaration[], - flags = Es2pandaVariableDeclarationKind.CONST + flags: NodeFlags = NodeFlags.None ): VariableDeclarationList { - const peer = withNodeArray(declarations, _declarators => { - return nativeModule._CreateVariableDeclaration(global.context, flags, _declarators, _declarators.length, false) - }) - return new VariableDeclarationList(updateChildren(peer)) + return new VariableDeclarationList( + arkts.VariableDeclaration.create( + undefined, + passModifiers([]), + passVariableDeclarationKind(flags), + passNodeArray(declarations), + false + ) + ) } // @api @@ -215,8 +239,15 @@ export function createNodeFactory() { node: VariableDeclarationList, declarations: readonly VariableDeclaration[] ): VariableDeclarationList { - const updated = createVariableDeclarationList(declarations) - return new VariableDeclarationList(updateNode(updated.peer, node.peer)) + return new VariableDeclarationList( + arkts.VariableDeclaration.create( + node.node, + passModifiers([]), + passVariableDeclarationKind(node.flags), + passNodeArray(declarations), + false + ) + ) } // @api @@ -228,13 +259,16 @@ export function createNodeFactory() { modifiers: readonly Modifier[] | undefined, declarationList: VariableDeclarationList | readonly VariableDeclaration[] ): VariableStatement { - const peer = withNodeArray((declarationList instanceof VariableDeclarationList) ? declarationList.declarations : declarationList, _declarators => { - // TODO: fix (const only now) - return nativeModule._CreateVariableDeclaration(global.context, Es2pandaVariableDeclarationKind.CONST, _declarators, _declarators.length, false) - }) - // TODO: fix flags - // setModifierFlags(peer, Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC | Es2pandaModifierFlags.MODIFIER_FLAGS_CONST) - return new VariableStatement(updateChildren(updateModifiers(peer, modifiers))) + const node: arkts.VariableDeclaration = (declarationList instanceof VariableDeclarationList) ? declarationList.node : createVariableDeclarationList(declarationList, undefined).node + return new VariableStatement( + arkts.VariableDeclaration.create( + undefined, + passModifiers(modifiers), + node.declarationKind, + node.declarators, + false + ) + ) } // @api @@ -248,8 +282,15 @@ export function createNodeFactory() { modifiers: readonly Modifier[] | undefined, declarationList: VariableDeclarationList ): VariableStatement { - const updated = createVariableStatement(modifiers, declarationList) - return new VariableStatement(updateNode(updated.peer, updateModifiers(node.peer, modifiers))) + return new VariableStatement( + arkts.VariableDeclaration.create( + node.node, + passModifiers(modifiers), + declarationList.node.declarationKind, + declarationList.node.declarators, + false + ) + ) } // @api @@ -260,23 +301,20 @@ export function createNodeFactory() { // initializer: Expression | undefined // ): VariableDeclaration function createVariableDeclaration( - name: Identifier, + name: string | Identifier, exclamationToken: undefined, type: TypeNode | undefined, initializer: Expression | undefined ): VariableDeclaration { - const ident = identifierUpdateTypeAnnotation(name, type) - updateChildren(ident.peer) - // TODO: fix (const only now) - const peer = nativeModule._CreateVariableDeclarator( - global.context, - VariableDeclaratorFlag.CONST, - ident.peer + return new VariableDeclaration( + arkts.VariableDeclarator.create( + undefined, + // TODO: maybe incorrect + Es2pandaVariableDeclaratorFlag.UNKNOWN, + passIdentifier(name, type), + passNode(initializer) + ) ) - if (initializer !== undefined) { - nativeModule._VariableDeclaratorSetInit(global.context, peer, initializer.peer) - } - return new VariableDeclaration(updateChildren(peer)) } // @api @@ -294,10 +332,16 @@ export function createNodeFactory() { type: TypeNode | undefined, initializer: Expression | undefined ): VariableDeclaration { - const updated = createVariableDeclaration(name, exclamationToken, type, initializer) - return new VariableDeclaration(updateNode(updated.peer, node.peer)) + return new VariableDeclaration( + arkts.VariableDeclarator.create( + node.node, + // TODO: maybe incorrect + Es2pandaVariableDeclaratorFlag.UNKNOWN, + passIdentifier(name, type), + passNode(initializer) + ) + ) } -*/ // @api // createFunctionDeclaration( @@ -320,14 +364,16 @@ export function createNodeFactory() { ): FunctionDeclaration { return new FunctionDeclaration( arkts.FunctionDeclaration.create( + undefined, arkts.ScriptFunction.create( + undefined, body?.node, arkts.FunctionSignature.create( passTypeParams(typeParameters), passNodeArray(parameters), type?.node ), - passModifiersToScriptFunction(modifiers), + 0, passModifiers(modifiers) | Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, body === undefined, passIdentifier(name) @@ -359,15 +405,23 @@ export function createNodeFactory() { body: Block | undefined ): FunctionDeclaration { return new FunctionDeclaration( - createFunctionDeclaration( - modifiers, - undefined, - name, - typeParameters, - parameters, - type, - body - ).node.updateNode(node.node) + arkts.FunctionDeclaration.create( + node.node, + arkts.ScriptFunction.create( + node.node.scriptFunction, + body?.node, + arkts.FunctionSignature.create( + passTypeParams(typeParameters), + passNodeArray(parameters), + type?.node + ), + 0, + passModifiers(modifiers) | Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + body === undefined, + passIdentifier(name) + ), + false + ) ) } @@ -390,7 +444,8 @@ export function createNodeFactory() { ): ParameterDeclaration { return new ParameterDeclaration( arkts.ETSParameterExpression.create( - arkts.Identifier.create( + undefined, + arkts.factory.createIdentifier( (name instanceof Identifier) ? name.node.name : name, type?.node ), @@ -419,14 +474,14 @@ export function createNodeFactory() { initializer?: Expression ): ParameterDeclaration { return new ParameterDeclaration( - createParameterDeclaration( - modifiers, - dotDotDotToken, - name, - questionToken, - type, - initializer - ).node.updateNode(node.node) + arkts.ETSParameterExpression.create( + node.node, + arkts.factory.createIdentifier( + (name instanceof Identifier) ? name.node.name : name, + type?.node + ), + initializer?.node + ) ) } @@ -445,6 +500,7 @@ export function createNodeFactory() { ): TypeParameterDeclaration { return new TypeParameterDeclaration( arkts.TSTypeParameter.create( + undefined, passIdentifier(name), constraint?.node, defaultType?.node, @@ -469,12 +525,13 @@ export function createNodeFactory() { defaultType?: TypeNode ): TypeParameterDeclaration { return new TypeParameterDeclaration( - createTypeParameterDeclaration( - modifiers, - name, - constraint, - defaultType - ).node.updateNode(node.node) + arkts.TSTypeParameter.create( + node.node, + passIdentifier(name), + constraint?.node, + defaultType?.node, + passModifiers(modifiers) + ) ) } @@ -487,6 +544,7 @@ export function createNodeFactory() { ): UnionTypeNode { return new UnionTypeNode( arkts.ETSUnionType.create( + undefined, passNodeArray(types) ) ) @@ -502,10 +560,12 @@ export function createNodeFactory() { types: readonly TypeNode[] ): UnionTypeNode { return new UnionTypeNode( - createUnionTypeNode( - types - ).node.updateNode(node.node) + arkts.ETSUnionType.create( + node.node, + passNodeArray(types) + ) ) + } // @api @@ -518,7 +578,10 @@ export function createNodeFactory() { typeArguments?: undefined ): TypeReferenceNode { return new TypeReferenceNode( - arkts.ETSTypeReference.create(typeName.node) + arkts.ETSTypeReference.create( + undefined, + typeName.node + ) ) } @@ -533,30 +596,14 @@ export function createNodeFactory() { typeName: Identifier, typeArguments?: undefined ): TypeReferenceNode { - const updated = createTypeReferenceNode(typeName, typeArguments) - return new TypeReferenceNode(updateNode(updated.node, node.node)) - } - - // @internal - function createKeywordTypeNodeFromString( - keyword: string - ): KeywordTypeNode { - return new KeywordTypeNode( + return new TypeReferenceNode( arkts.ETSTypeReference.create( - arkts.Identifier.create(keyword) + node.node, + typeName.node ) ) } - // @internal - function createKeywordTypeNodeFromKind( - kind: number - ): KeywordTypeNode { - return new KeywordTypeNode( - arkts.ETSPrimitiveType.create(kind) - ) - } - // @api // createKeywordTypeNode( // kind: TKind @@ -564,13 +611,37 @@ export function createNodeFactory() { function createKeywordTypeNode( TKind: ts.KeywordTypeSyntaxKind ): KeywordTypeNode { + function createKeywordTypeNodeFromString( + keyword: string + ): KeywordTypeNode { + return new KeywordTypeNode( + arkts.ETSTypeReference.create( + undefined, + arkts.factory.createIdentifier( + keyword + ) + ) + ) + } + + function createKeywordTypeNodeFromKind( + kind: number + ): KeywordTypeNode { + return new KeywordTypeNode( + arkts.ETSPrimitiveType.create( + undefined, + kind + ) + ) + } + const keywords = new Map([ [ts.SyntaxKind.NumberKeyword, createKeywordTypeNodeFromString("number")], [ts.SyntaxKind.StringKeyword, createKeywordTypeNodeFromString("string")], [ts.SyntaxKind.AnyKeyword, createKeywordTypeNodeFromString("any")], [ts.SyntaxKind.VoidKeyword, createKeywordTypeNodeFromKind(8)], ]) - return keywords.get(TKind) ?? global.throwError('unsupported keyword') + return keywords.get(TKind) ?? throwError('unsupported keyword') } // @api @@ -583,7 +654,10 @@ export function createNodeFactory() { multiline?: boolean ): Block { return new Block( - arkts.Block.create(passNodeArray(statements)) + arkts.BlockStatement.create( + undefined, + passNodeArray(statements) + ) ) } @@ -596,8 +670,12 @@ export function createNodeFactory() { node: Block, statements: readonly Statement[] ): Block { - const updated = createBlock(statements) - return new Block(updateNode(updated.node, node.node)) + return new Block( + arkts.BlockStatement.create( + node.node, + passNodeArray(statements) + ) + ) } // @api @@ -608,7 +686,9 @@ export function createNodeFactory() { expression: Expression ): ExpressionStatement { return new ExpressionStatement( - arkts.ExpressionStatement.create(expression.node) + arkts.factory.createExpressionStatement( + expression.node + ) ) } @@ -621,8 +701,12 @@ export function createNodeFactory() { node: ExpressionStatement, expression: Expression ): ExpressionStatement { - const updated = createExpressionStatement(expression) - return new ExpressionStatement(updateNode(updated.node, node.node)) + return new ExpressionStatement( + arkts.factory.updateExpressionStatement( + node.node, + expression.node + ) + ) } // @api @@ -633,7 +717,10 @@ export function createNodeFactory() { expression: Expression ): ReturnStatement { return new ReturnStatement( - arkts.ReturnStatement.create(expression.node) + arkts.ReturnStatement.create( + undefined, + expression.node + ) ) } @@ -646,8 +733,12 @@ export function createNodeFactory() { node: ReturnStatement, expression: Expression ): ReturnStatement { - const updated = createReturnStatement(expression) - return new ReturnStatement(updateNode(updated.node, node.node)) + return new ReturnStatement( + arkts.ReturnStatement.create( + node.node, + expression.node + ) + ) } // @api @@ -660,7 +751,7 @@ export function createNodeFactory() { name: string | Identifier ): PropertyAccessExpression { return new PropertyAccessExpression( - arkts.MemberExpression.create( + arkts.factory.createMemberExpression( expression.node, passIdentifier(name), Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, @@ -681,8 +772,16 @@ export function createNodeFactory() { expression: Expression, name: Identifier ): PropertyAccessExpression { - const updated = createPropertyAccessExpression(expression, name) - return new PropertyAccessExpression(updateNode(updated.node, node.node)) + return new PropertyAccessExpression( + arkts.factory.updateMemberExpression( + node.node, + expression.node, + passIdentifier(name), + Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + ) } // @api @@ -697,13 +796,10 @@ export function createNodeFactory() { argumentsArray: readonly Expression[] | undefined ): CallExpression { return new CallExpression( - arkts.CallExpression.create( + arkts.factory.createCallExpression( expression.node, (typeArguments !== undefined) ? - arkts.TSTypeParameterDeclaration.create( - passNodeArray(typeArguments) - ) : - undefined, + arkts.TSTypeParameterDeclaration.create(undefined, passNodeArray(typeArguments)) : undefined, passNodeArray(argumentsArray) ) ) @@ -722,8 +818,15 @@ export function createNodeFactory() { typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined ): CallExpression { - const updated = createCallExpression(expression, typeArguments, argumentsArray) - return new CallExpression(updateNode(updated.node, node.node)) + return new CallExpression( + arkts.factory.updateCallExpression( + node.node, + expression.node, + (typeArguments !== undefined) ? + arkts.TSTypeParameterDeclaration.create(undefined, passNodeArray(typeArguments)) : undefined, + passNodeArray(argumentsArray) + ) + ) } // @api @@ -739,6 +842,7 @@ export function createNodeFactory() { ): IfStatement { return new IfStatement( arkts.IfStatement.create( + undefined, passNode(expression), passNode(thenStatement), passNode(elseStatement), @@ -758,8 +862,14 @@ export function createNodeFactory() { thenStatement: Statement, elseStatement?: undefined ): IfStatement { - const updated = createIfStatement(expression, thenStatement, elseStatement) - return new IfStatement(updateNode(updated.node, node.node)) + return new IfStatement( + arkts.IfStatement.create( + node.node, + passNode(expression), + passNode(thenStatement), + passNode(elseStatement), + ) + ) } // TODO: rewrite maybe @@ -786,6 +896,7 @@ export function createNodeFactory() { ): BinaryExpression { return new BinaryExpression( arkts.BinaryExpression.create( + undefined, passNode(left), passToken(operator), passNode(right), @@ -806,8 +917,14 @@ export function createNodeFactory() { operator: BinaryOperatorToken, right: Expression ): BinaryExpression { - const updated = createBinaryExpression(left, operator, right) - return new BinaryExpression(updateNode(updated.node, node.node)) + return new BinaryExpression( + arkts.BinaryExpression.create( + node.node, + passNode(left), + passToken(operator), + passNode(right), + ) + ) } // @api @@ -824,12 +941,14 @@ export function createNodeFactory() { typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, - equalsGreaterThanToken: undefined, + equalsGreaterThanToken: Token | undefined, body: Block ) { return new ArrowFunction( arkts.ArrowFunctionExpression.create( + undefined, arkts.ScriptFunction.create( + undefined, passNode(body), arkts.FunctionSignature.create( passTypeParams(typeParameters), @@ -861,11 +980,27 @@ export function createNodeFactory() { typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: undefined, - equalsGreaterThanToken: undefined, + equalsGreaterThanToken: Token | undefined, body: Block, ): ArrowFunction { - const updated = createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) - return new ArrowFunction(updateNode(updated.node, node.node)) + return new ArrowFunction( + arkts.ArrowFunctionExpression.create( + node.node, + arkts.ScriptFunction.create( + node.node.scriptFunction, + passNode(body), + arkts.FunctionSignature.create( + passTypeParams(typeParameters), + passNodeArray(parameters), + passNode(type) + ), + passModifiersToScriptFunction(modifiers) | Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + passModifiers(modifiers) | Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + false, + undefined + ) + ) + ) } // @api @@ -880,17 +1015,21 @@ export function createNodeFactory() { modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, - heritageClauses: undefined, + heritageClauses: readonly TypeParameterDeclaration[] | undefined, members: readonly ClassElement[] - ) { + ): ClassDeclaration { return new ClassDeclaration( arkts.ClassDeclaration.create( + undefined, arkts.ClassDefinition.create( + undefined, passIdentifier(name), passNodeArray(members), - passModifiers(modifiers) | Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + // passModifiers(modifiers) | es2panda_ModifierFlags.MODIFIER_FLAGS_PUBLIC | es2panda_ModifierFlags.MODIFIER_FLAGS_STATIC, + Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, // TODO: pass through modifiers Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_NONE, + passTypeParams(typeParameters), undefined ) ) @@ -910,45 +1049,24 @@ export function createNodeFactory() { node: ClassDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, - typeParameters: undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: undefined, members: readonly ClassElement[] - ) { - // TODO: rewrite like this (impossible now because of Language param) - - const _classDefinition = nativeModule._ClassDeclarationDefinition( - global.context, - node.node.peer - ) - const _lang = nativeModule._ClassDefinitionLanguageConst( - global.context, - _classDefinition - ) - const _members = arkts.passNodeArray(passNodeArray(members)) - const _newClassDefinition = - arkts.unpackNonNullableNode( - nativeModule._UpdateClassDefinition1( - global.context, - _classDefinition, - // TODO: maybe this is wrong - arkts.passNode(passIdentifier(name)), - _members, - _members.length, - Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_NONE, + ): ClassDeclaration { + return new ClassDeclaration( + arkts.ClassDeclaration.create( + node.node, + arkts.ClassDefinition.create( + node.node.definition, + passIdentifier(name), + passNodeArray(members), + // passModifiers(modifiers) | es2panda_ModifierFlags.MODIFIER_FLAGS_PUBLIC | es2panda_ModifierFlags.MODIFIER_FLAGS_STATIC, Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - _lang + // TODO: pass through modifiers + Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_NONE, + passTypeParams(typeParameters) ) ) - nativeModule._ClassDefinitionSetTypeParams(global.context, _newClassDefinition.peer, arkts.passNode(passTypeParams(typeParameters))) - _newClassDefinition.modifiers = passModifiers(modifiers) - return new ClassDeclaration( - arkts.unpackNonNullableNode( - nativeModule._UpdateClassDeclaration( - global.context, - node.node.peer, - _newClassDefinition.updateNode(arkts.unpackNonNullableNode(_classDefinition)).peer - ) - ).updateModifiers(Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC) as arkts.ClassDeclaration ) } @@ -964,7 +1082,8 @@ export function createNodeFactory() { type: TypeNode ): FunctionTypeNode { return new FunctionTypeNode( - arkts.FunctionTypeNode.create( + arkts.ETSFunctionType.create( + undefined, arkts.FunctionSignature.create( passTypeParams(typeParameters), passNodeArray(parameters), @@ -989,11 +1108,15 @@ export function createNodeFactory() { type: TypeNode ): FunctionTypeNode { return new FunctionTypeNode( - createFunctionTypeNode( - typeParameters, - parameters, - type - ).node.updateNode(node.node) + arkts.ETSFunctionType.create( + node.node, + arkts.FunctionSignature.create( + passTypeParams(typeParameters), + passNodeArray(parameters), + passNode(type) + ), + Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE + ) ) } @@ -1022,17 +1145,20 @@ export function createNodeFactory() { const _name = passIdentifier(name) return new MethodDeclaration( arkts.MethodDefinition.create( + undefined, Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, _name, arkts.FunctionExpression.create( + undefined, arkts.ScriptFunction.create( + undefined, passNode(body), arkts.FunctionSignature.create( passTypeParams(typeParameters), passNodeArray(parameters), passNode(type) ), - passModifiersToScriptFunction(modifiers) | Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + 0, passModifiers(modifiers) | Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC || Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, false, _name @@ -1067,17 +1193,32 @@ export function createNodeFactory() { type: undefined, body: Block | undefined ): MethodDeclaration { + const _name = passIdentifier(name) return new MethodDeclaration( - createMethodDeclaration( - modifiers, - asteriskToken, - name, - questionToken, - typeParameters, - parameters, - type, - body - ).node.updateNode(node.node) + arkts.MethodDefinition.create( + node.node, + Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, + _name, + arkts.FunctionExpression.create( + // TODO: maybe fix + undefined, + arkts.ScriptFunction.create( + node.node.scriptFunction, + passNode(body), + arkts.FunctionSignature.create( + passTypeParams(typeParameters), + passNodeArray(parameters), + passNode(type) + ), + 0, + passModifiers(modifiers) | Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC || Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + false, + _name + ) + ), + passModifiers(modifiers), + false + ) ) } @@ -1092,13 +1233,18 @@ export function createNodeFactory() { parameters: readonly ParameterDeclaration[], body: Block | undefined ): ConstructorDeclaration { - const _name = arkts.Identifier.create("constructor") + const _name = arkts.factory.createIdentifier( + "constructor" + ) return new ConstructorDeclaration( arkts.MethodDefinition.create( + undefined, Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, _name, arkts.FunctionExpression.create( + undefined, arkts.ScriptFunction.create( + undefined, passNode(body), arkts.FunctionSignature.create( undefined, @@ -1131,8 +1277,134 @@ export function createNodeFactory() { parameters: readonly ParameterDeclaration[], body: Block | undefined ): ConstructorDeclaration { - const updated = createConstructorDeclaration(modifiers, parameters, body) - return new ConstructorDeclaration(updateNode(updated.node, node.node)) + const _name = arkts.factory.updateIdentifier( + node.node.name, + "constructor" + ) + return new ConstructorDeclaration( + arkts.MethodDefinition.create( + node.node, + Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, + _name, + arkts.FunctionExpression.create( + // TODO: maybe fix + undefined, + arkts.ScriptFunction.create( + node.node.scriptFunction, + passNode(body), + arkts.FunctionSignature.create( + undefined, + passNodeArray(parameters), + // TODO: change to void maybe + undefined + ), + passModifiersToScriptFunction(modifiers) | Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR, + passModifiers(modifiers) | Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, + false, + _name + ) + ), + passModifiers(modifiers) | Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, + false + ) + ) + + } + + // @api + // tsc: createSuper( + // ): SuperExpression; + function createSuper( + ): SuperExpression { + return new SuperExpression( + arkts.SuperExpression.create( + undefined, + ) + ) + } + + // @api + // tsc: updateSuper( + // node: SuperExpression + // ): SuperExpression; + function updateSuper( + node: SuperExpression + ): SuperExpression { + return new SuperExpression( + arkts.SuperExpression.create( + node.node, + ) + ) + } + + // @api + // tsc: createParenthesizedExpression( + // expression: Expression + // ): ParenthesizedExpression; + function createParenthesizedExpression( + expression: Expression + ): ParenthesizedExpression { + return expression + // TODO: + // return new ParenthesizedExpression( + // expression + // ) + } + + // @api + // tsc: updateParenthesizedExpression( + // node: ParenthesizedExpression, + // expression: Expression + // ): ParenthesizedExpression; + function updateParenthesizedExpression( + node: ParenthesizedExpression, + expression: Expression + ): ParenthesizedExpression { + return expression + // TODO: + // return new ParenthesizedExpression( + // expression + // ) + } + + // // @api + // // createImportDeclaration( + // // decorators: readonly Decorator[] | undefined, + // // modifiers: readonly Modifier[] | undefined, + // // importClause: ImportClause | undefined, + // // moduleSpecifier: Expression, + // // assertClause?: AssertClause + // // ): ImportDeclaration; + // function createImportDeclaration( + // decorators: undefined, + // modifiers: readonly Modifier[] | undefined, + // importClause: ImportClause | undefined, + // moduleSpecifier: StringLiteral, + // assertClause?: undefined + // ): ImportDeclaration { + // return new ImportDeclaration( + // arkts.EtsImportDeclaration.create( + // undefined, + // arkts.ImportSource.create(moduleSpecifier.node), + + // ) + // ) + // } + + // @api + // createImportSpecifier( + // isTypeOnly: boolean, + // propertyName: Identifier | undefined, + // name: Identifier + // ): ImportSpecifier; + function createImportSpecifier( + isTypeOnly: boolean, + propertyName: Identifier | undefined, + name: Identifier + ): ImportSpecifier { + return new ImportSpecifier( + name.node + ) } } diff --git a/arkoala-arkts/libarkts/src/api/factory/nodeTests.ts b/arkoala-arkts/libarkts/src/ts-api/factory/nodeTests.ts similarity index 61% rename from arkoala-arkts/libarkts/src/api/factory/nodeTests.ts rename to arkoala-arkts/libarkts/src/ts-api/factory/nodeTests.ts index fb4274b56..eed8a6703 100644 --- a/arkoala-arkts/libarkts/src/api/factory/nodeTests.ts +++ b/arkoala-arkts/libarkts/src/ts-api/factory/nodeTests.ts @@ -28,15 +28,15 @@ import { ClassElement, MethodDeclaration, FunctionExpression, - // VariableDeclaration, - // VariableDeclarationList, - // PropertyDeclaration, - // PropertySignature, - // MethodSignature, - // GetAccessorDeclaration, - // SetAccessorDeclaration, - // VariableStatement, -} from "../layers/ts/types" + VariableDeclaration, + VariableDeclarationList, + PropertyDeclaration, + PropertySignature, + MethodSignature, + GetAccessorDeclaration, + SetAccessorDeclaration, + VariableStatement, +} from "../types" export function isIdentifier(node: Node): node is Identifier { return node.kind === SyntaxKind.Identifier @@ -86,38 +86,38 @@ export function isParameter(node: Node): node is ParameterDeclaration { return node.kind === SyntaxKind.Parameter } -// export function isVariableDeclaration(node: Node): node is VariableDeclaration { -// return node.kind === SyntaxKind.VariableDeclaration -// } +export function isVariableDeclaration(node: Node): node is VariableDeclaration { + return node.kind === SyntaxKind.VariableDeclaration +} -// export function isVariableDeclarationList(node: Node): node is VariableDeclarationList { -// return node.kind === SyntaxKind.VariableDeclarationList -// } +export function isVariableDeclarationList(node: Node): node is VariableDeclarationList { + return node.kind === SyntaxKind.VariableDeclarationList +} -// export function isPropertyDeclaration(node: Node): node is PropertyDeclaration { -// return node.kind === SyntaxKind.PropertyDeclaration -// } +export function isPropertyDeclaration(node: Node): node is PropertyDeclaration { + return node.kind === SyntaxKind.PropertyDeclaration +} -// export function isPropertySignature(node: Node): node is PropertySignature { -// return node.kind === SyntaxKind.PropertySignature -// } +export function isPropertySignature(node: Node): node is PropertySignature { + return node.kind === SyntaxKind.PropertySignature +} export function isFunctionTypeNode(node: Node): node is FunctionTypeNode { return node.kind === SyntaxKind.FunctionType } -// export function isMethodSignature(node: Node): node is MethodSignature { -// return node.kind === SyntaxKind.MethodSignature -// } +export function isMethodSignature(node: Node): node is MethodSignature { + return node.kind === SyntaxKind.MethodSignature +} -// export function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration { -// return node.kind === SyntaxKind.GetAccessor -// } +export function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration { + return node.kind === SyntaxKind.GetAccessor +} -// export function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration { -// return node.kind === SyntaxKind.SetAccessor -// } +export function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration { + return node.kind === SyntaxKind.SetAccessor +} -// export function isVariableStatement(node: Node): node is VariableStatement { -// return node.kind === SyntaxKind.VariableStatement -// } +export function isVariableStatement(node: Node): node is VariableStatement { + return node.kind === SyntaxKind.VariableStatement +} diff --git a/arkoala-arkts/libarkts/src/api/index.ts b/arkoala-arkts/libarkts/src/ts-api/index.ts similarity index 67% rename from arkoala-arkts/libarkts/src/api/index.ts rename to arkoala-arkts/libarkts/src/ts-api/index.ts index 4b90c66f0..24a7d7f2b 100644 --- a/arkoala-arkts/libarkts/src/api/index.ts +++ b/arkoala-arkts/libarkts/src/ts-api/index.ts @@ -13,18 +13,23 @@ * limitations under the License. */ -export * from "./layers/ts/types" -export * from "./utilities/utilitiesPublic" -// TODO: remove this export -export * from "./utilities/utilities" +// TODO: remove private export +export * from "./utilities/private" +export * from "./utilities/public" +export * from "./types" export * from "./factory/nodeFactory" export * from "./factory/nodeTests" -export * from "./static/global" export { visitEachChild, } from "./visitor/visitor" export { SyntaxKind, - ContextState, - Es2pandaPrimitiveType, + NodeFlags, } from "./static/enums" + +// from ArkTS api +export * from "../arkts-api/static/global" +export { + Es2pandaContextState as ContextState, + Es2pandaPrimitiveType as Es2pandaPrimitiveType, +} from "../arkts-api/static/enums" diff --git a/arkoala-arkts/libarkts/src/api/layers/arkts/index.ts b/arkoala-arkts/libarkts/src/ts-api/static/enums.ts similarity index 81% rename from arkoala-arkts/libarkts/src/api/layers/arkts/index.ts rename to arkoala-arkts/libarkts/src/ts-api/static/enums.ts index f7237d2d9..78dc895df 100644 --- a/arkoala-arkts/libarkts/src/api/layers/arkts/index.ts +++ b/arkoala-arkts/libarkts/src/ts-api/static/enums.ts @@ -13,5 +13,6 @@ * limitations under the License. */ -export * from "./types" -export * from "./utilities" +export { SyntaxKind } from "@koalaui/ets-tsc" +export { TokenSyntaxKind } from "@koalaui/ets-tsc" +export { NodeFlags } from "@koalaui/ets-tsc" diff --git a/arkoala-arkts/libarkts/src/api/layers/ts/types.ts b/arkoala-arkts/libarkts/src/ts-api/types.ts similarity index 65% rename from arkoala-arkts/libarkts/src/api/layers/ts/types.ts rename to arkoala-arkts/libarkts/src/ts-api/types.ts index ded166dfe..46ae232f2 100644 --- a/arkoala-arkts/libarkts/src/api/layers/ts/types.ts +++ b/arkoala-arkts/libarkts/src/ts-api/types.ts @@ -1,7 +1,7 @@ -import global from "../../static/global" import * as ts from "@koalaui/ets-tsc" -import * as arkts from "../arkts/types" +import * as arkts from "../arkts-api/types" +import { throwError } from "../utils" import { todo, @@ -13,10 +13,11 @@ import { passModifiers, unpackModifiers, -} from "./utilities" + unpackVariableDeclarationKind, +} from "./utilities/private" import { SyntaxKind, -} from "../../static/enums" +} from "./static/enums" // TODO: write implementation export interface TransformationContext {} @@ -37,24 +38,24 @@ export abstract class Node(cbNode: (node: ts.Node) => T | undefined, cbNodeArray?: ((nodes: ts.NodeArray) => T | undefined) | undefined): T | undefined { throw new Error("Method not implemented.") } getSourceFile(): ts.SourceFile { throw new Error("Method not implemented.") } getChildCount(sourceFile?: ts.SourceFile | undefined): number { throw new Error("Method not implemented.") } getChildAt(index: number, sourceFile?: ts.SourceFile | undefined): ts.Node { throw new Error("Method not implemented.") } getChildren(sourceFile?: ts.SourceFile | undefined): ts.Node[] { throw new Error("Method not implemented.") } + getStart(sourceFile?: ts.SourceFile | undefined, includeJsDocComment?: boolean | undefined): number { throw new Error("Method not implemented.") } getFullStart(): number { throw new Error("Method not implemented.") } getEnd(): number { throw new Error("Method not implemented.") } @@ -80,7 +83,6 @@ export abstract class Node(cbNode: (node: ts.Node) => T | undefined, cbNodeArray?: ((nodes: ts.NodeArray) => T | undefined) | undefined): T | undefined { throw new Error("Method not implemented.") } get symbol(): ts.Symbol { return todo() } get flags(): ts.NodeFlags { return todo() } @@ -93,6 +95,8 @@ export type BinaryOperator = | ts.SyntaxKind.PlusToken | ts.SyntaxKind.MinusToken + | ts.SyntaxKind.AsteriskToken + export type BinaryOperatorToken = Token; // TODO: rethink maybe (temporary solution) @@ -130,7 +134,7 @@ export class Modifier extends Node { } public toString(): string { - return `${global.modifierFlags.get(this.kind)}` + return `${this.kind}` } kind: ModifierSyntaxKind @@ -139,17 +143,15 @@ export class Modifier extends Node { export abstract class Expression extends Node implements ts.Expression { // TODO: support minimal interface _expressionBrand: any - kind: any } -// export class FunctionDeclaration extends Node implements ts.FunctionDeclaration, FunctionLikeDeclarationBase { -export class FunctionDeclaration extends Node implements ts.FunctionDeclaration { +export class FunctionDeclaration extends Node implements ts.FunctionDeclaration, FunctionLikeDeclarationBase { constructor(node: arkts.FunctionDeclaration) { super(node) this.name = unpackNode(node.name) this.body = unpackNode(node.body) this.typeParameters = unpackNodeArray(node.typeParamsDecl?.parameters) - this.type = unpackNode(node.type) + this.type = unpackNode(node.returnType) this.parameters = unpackNodeArray(node.parameters) } @@ -160,31 +162,21 @@ export class FunctionDeclaration extends Node impleme readonly parameters: NodeArray readonly kind: ts.SyntaxKind.FunctionDeclaration = ts.SyntaxKind.FunctionDeclaration - // TODO: support minimal interface - asteriskToken?: ts.AsteriskToken | undefined + // brands _functionLikeDeclarationBrand: any _declarationBrand: any _statementBrand: any - questionToken?: ts.QuestionToken | undefined - exclamationToken?: ts.ExclamationToken | undefined - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined } -// export class FunctionExpression extends Node implements ts.FunctionExpression, FunctionLikeDeclarationBase { -export class FunctionExpression extends Node implements ts.FunctionExpression { +export class FunctionExpression extends Node implements ts.FunctionExpression, FunctionLikeDeclarationBase { constructor(node: arkts.FunctionExpression) { super(node) this.name = unpackNode(node.scriptFunction.ident) if (node.scriptFunction.body === undefined) { - global.throwError('body expected to be not undefined') + throwError('body expected to be not undefined') } this.body = unpackNode(node.scriptFunction.body) - if (node.scriptFunction.signature === undefined) { - global.throwError('node.scriptFunction.signature not expected to be undefined') - } - this.parameters = unpackNodeArray(node.scriptFunction.signature.parameters) + this.parameters = unpackNodeArray(node.scriptFunction.parameters) } readonly name?: Identifier @@ -192,22 +184,14 @@ export class FunctionExpression extends Node implement readonly parameters: NodeArray readonly kind: ts.SyntaxKind.FunctionExpression = ts.SyntaxKind.FunctionExpression - // TODO: support minimal interface + // brands _primaryExpressionBrand: any _memberExpressionBrand: any _leftHandSideExpressionBrand: any _updateExpressionBrand: any _unaryExpressionBrand: any _expressionBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined _functionLikeDeclarationBrand: any - asteriskToken?: ts.AsteriskToken | undefined - questionToken?: ts.QuestionToken | undefined - exclamationToken?: ts.ExclamationToken | undefined - typeParameters?: NodeArray | undefined - type?: TypeNode | undefined _declarationBrand: any } @@ -220,13 +204,10 @@ export class Identifier extends Node implements ts.Identifier, readonly text: string readonly kind: ts.SyntaxKind.Identifier = ts.SyntaxKind.Identifier - // TODO: support minimal interface + // TODO: get escapedText(): ts.__String { return todo() } - originalKeywordKind?: ts.SyntaxKind | undefined - isInJSDocNamespace?: boolean | undefined - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined + + // brands _primaryExpressionBrand: any _memberExpressionBrand: any _leftHandSideExpressionBrand: any @@ -241,15 +222,17 @@ export class PrivateIdentifier extends Node implements ts.Priv super(node) this.text = node.name if (!node.isPrivate) { - global.throwError('identifier expected to be private') + throwError('identifier expected to be private') } } readonly text: string readonly kind: ts.SyntaxKind.PrivateIdentifier = ts.SyntaxKind.PrivateIdentifier - // TODO: support minimal interface + // TODO: get escapedText(): ts.__String { return todo() } + + // brands _primaryExpressionBrand: any _memberExpressionBrand: any _leftHandSideExpressionBrand: any @@ -259,28 +242,26 @@ export class PrivateIdentifier extends Node implements ts.Priv _declarationBrand: any } -// TODO: should be interface, not abstract class export abstract class Statement extends Node implements ts.Statement { + // brands _statementBrand: any - kind: any } -export class Block extends Node implements ts.Block { - constructor(node: arkts.Block) { +export class Block extends Node implements ts.Block { + constructor(node: arkts.BlockStatement) { super(node) - this.statements = unpackNodeArray(node.statements) } readonly statements: NodeArray readonly kind: ts.SyntaxKind.Block = ts.SyntaxKind.Block - // TODO: support minimal interface + // brands _statementBrand: any } -export class SourceFile extends Node implements ts.SourceFile { - constructor(node: arkts.Program) { +export class SourceFile extends Node implements ts.SourceFile { + constructor(node: arkts.EtsScript) { super(node) this.statements = unpackNodeArray(this.node.statements) @@ -289,8 +270,7 @@ export class SourceFile extends Node implements ts.SourceFile { readonly statements: NodeArray readonly kind: ts.SyntaxKind.SourceFile = ts.SyntaxKind.SourceFile - // TODO: support minimal interface - moduleName: string | undefined + // TODO: getLineAndCharacterOfPosition(pos: number): ts.LineAndCharacter { throw new Error("Method not implemented.") } getLineEndOfPosition(pos: number): number { throw new Error("Method not implemented.") } getLineStarts(): readonly number[] { throw new Error("Method not implemented.") } @@ -307,20 +287,17 @@ export class SourceFile extends Node implements ts.SourceFile { get isDeclarationFile(): boolean { return todo() } get hasNoDefaultLib(): boolean { return todo() } get languageVersion(): ts.ScriptTarget { return todo() } + + // brands _declarationBrand: any - impliedNodeFormat?: ts.ModuleKind.CommonJS | ts.ModuleKind.ESNext | undefined - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined } export abstract class LeftHandSideExpression extends Node implements ts.LeftHandSideExpression, Expression { - // TODO: support minimal interface + // brands _leftHandSideExpressionBrand: any _updateExpressionBrand: any _unaryExpressionBrand: any _expressionBrand: any - kind: any } export class ExpressionStatement extends Node implements ts.ExpressionStatement, Statement { @@ -332,7 +309,7 @@ export class ExpressionStatement extends Node impleme readonly expression: Expression readonly kind: ts.SyntaxKind.ExpressionStatement = ts.SyntaxKind.ExpressionStatement - // TODO: support minimal interface + // brands _statementBrand: any } @@ -347,7 +324,7 @@ export class CallExpression extends Node implements ts.Cal readonly arguments: NodeArray readonly kind: ts.SyntaxKind.CallExpression = ts.SyntaxKind.CallExpression - // TODO: support minimal interface + // brands _leftHandSideExpressionBrand: any _updateExpressionBrand: any _unaryExpressionBrand: any @@ -366,7 +343,7 @@ export class PropertyAccessExpression extends Node imple readonly name: Identifier readonly kind: ts.SyntaxKind.PropertyAccessExpression = ts.SyntaxKind.PropertyAccessExpression - // TODO: support minimal interface + // brands _memberExpressionBrand: any _leftHandSideExpressionBrand: any _updateExpressionBrand: any @@ -385,7 +362,7 @@ export class StringLiteral extends Node implements ts.Strin readonly text: string readonly kind: ts.SyntaxKind.StringLiteral = ts.SyntaxKind.StringLiteral - // TODO: support minimal interface + // brands _literalExpressionBrand: any _primaryExpressionBrand: any _memberExpressionBrand: any @@ -409,18 +386,15 @@ export class ClassDeclaration extends Node implements ts readonly typeParameters?: NodeArray readonly kind: ts.SyntaxKind.ClassDeclaration = ts.SyntaxKind.ClassDeclaration - // TODO: support minimal interface + // brands _declarationBrand: any _statementBrand: any } export abstract class ClassElement extends Node implements ts.ClassElement { - readonly name?: PropertyName - - // TODO: support minimal interface + // brands _declarationBrand: any _classElementBrand: any - kind: any } export type MemberName = Identifier | PrivateIdentifier; @@ -438,72 +412,47 @@ export type DeclarationName = // | BindingPattern // | EntityNameExpression; -export interface Declaration extends Node { - _declarationBrand: any -} - +export interface Declaration extends Node {} export abstract class NamedDeclaration extends Node implements ts.NamedDeclaration, Declaration { - name?: DeclarationName + readonly name?: DeclarationName; + + // brands _declarationBrand: any } -/* -export type SignatureDeclaration = ts.CallSignatureDeclaration | ts.ConstructSignatureDeclaration | MethodSignature | ts.IndexSignatureDeclaration | FunctionTypeNode | ts.ConstructorTypeNode | ts.JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | ts.AccessorDeclaration | FunctionExpression | ArrowFunction; -export interface SignatureDeclarationBase extends NamedDeclaration { - readonly kind: SignatureDeclaration["kind"]; - readonly name?: PropertyName; - readonly typeParameters?: NodeArray | undefined; - readonly parameters: NodeArray; - readonly type?: TypeNode | undefined; -} // constructor(peer: KNativePointer) { - // super(peer) - - // this._scriptFunction = nativeModule._MethodDefinitionFunction(global.context, peer) - // this.name = util.nodeByPeer(nativeModule._ScriptFunctionId(global.context, this._scriptFunction)) as Identifier - // this.parameters = util.unpack(nativeModule._ScriptFunctionParams(global.context, this._scriptFunction)) as NodeArray - // if (util.scriptFunctionHasBody(this._scriptFunction)) { - // this.body = util.nodeByPeer(nativeModule._ScriptFunctionBody(global.context, this._scriptFunction)) as Block - // } - // } +export type SignatureDeclaration = ts.CallSignatureDeclaration | ts.ConstructSignatureDeclaration | MethodSignature | ts.IndexSignatureDeclaration | FunctionTypeNode | ts.ConstructorTypeNode | ts.JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | ts.AccessorDeclaration | FunctionExpression | ArrowFunction; +export interface SignatureDeclarationBase extends NamedDeclaration {} export type VariableLikeDeclaration = ts.VariableDeclaration | ParameterDeclaration | ts.BindingElement | PropertyDeclaration | ts.PropertyAssignment | PropertySignature | ts.JsxAttribute | ts.ShorthandPropertyAssignment | ts.EnumMember | ts.JSDocPropertyTag | ts.JSDocParameterTag; export interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { + // brands _functionLikeDeclarationBrand: any; - readonly asteriskToken?: ts.AsteriskToken | undefined; - readonly questionToken?: ts.QuestionToken | undefined; - readonly exclamationToken?: ts.ExclamationToken | undefined; - readonly body?: Block | Expression | undefined; } // TODO: support // export type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; export type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; -export class MethodSignature extends NodeBase implements ts.MethodSignature, SignatureDeclarationBase { - constructor(peer: KNativePointer) { - super(peer) +export class MethodSignature extends Node implements ts.MethodSignature, SignatureDeclarationBase { + constructor(node: arkts.Node) { + super(node) } - // TODO: support minimal interface - get parent(): any { return todo() } - // name: PropertyName + // readonly name: PropertyName + // readonly parameters: NodeArray + readonly kind: ts.SyntaxKind.MethodSignature = ts.SyntaxKind.MethodSignature + + // TODO: name: any - typeParameters?: NodeArray | undefined - // parameters: NodeArray parameters: any - type?: TypeNode | undefined + + // brands _declarationBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined _typeElementBrand: any - questionToken?: ts.QuestionToken | undefined - kind: ts.SyntaxKind.MethodSignature = ts.SyntaxKind.MethodSignature } -*/ // export class MethodDeclaration extends Node implements ts.MethodDeclaration, FunctionLikeDeclarationBase, ClassElement { export class MethodDeclaration extends Node implements ts.MethodDeclaration, ClassElement { @@ -521,8 +470,7 @@ export class MethodDeclaration extends Node implements t readonly body?: Block | undefined readonly kind: ts.SyntaxKind.MethodDeclaration = ts.SyntaxKind.MethodDeclaration - // TODO: support minimal interface - get parent(): any { return todo() } + // brands _functionLikeDeclarationBrand: any _classElementBrand: any _objectLiteralBrand: any @@ -545,99 +493,87 @@ export class ConstructorDeclaration extends Node impleme readonly body?: Block readonly kind: ts.SyntaxKind.Constructor = ts.SyntaxKind.Constructor - // TODO: support minimal interface - get parent(): any { return todo() } + // brands _functionLikeDeclarationBrand: any _classElementBrand: any _objectLiteralBrand: any _declarationBrand: any } -/* -export class PropertySignature extends NodeBase implements ts.TypeElement { - constructor(peer: KNativePointer) { - super(peer) + +// TODO: specify arkts.Node type +export class PropertySignature extends Node implements ts.TypeElement { + constructor(node: arkts.Node) { + super(node) } - // TODO: support minimal interface + readonly name?: PropertyName + readonly kind: ts.SyntaxKind.PropertySignature = ts.SyntaxKind.PropertySignature + + // brands _typeElementBrand: any - name?: PropertyName | undefined - questionToken?: ts.QuestionToken | undefined _declarationBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined - kind: ts.SyntaxKind.PropertySignature = ts.SyntaxKind.PropertySignature } -export class PropertyDeclaration extends NodeBase implements ts.PropertyDeclaration, ClassElement { - constructor(peer: KNativePointer) { - super(peer) +// TODO: specify arkts.Node type +export class PropertyDeclaration extends Node implements ts.PropertyDeclaration, ClassElement { + constructor(node: arkts.Node) { + super(node) } - // TODO: support minimal interface - get parent(): any { return todo() } - get name(): PropertyName { return todo() } + readonly kind: ts.SyntaxKind.PropertyDeclaration = ts.SyntaxKind.PropertyDeclaration + + // TODO: + name: any + + // brands _classElementBrand: any _declarationBrand: any - kind: ts.SyntaxKind.PropertyDeclaration = ts.SyntaxKind.PropertyDeclaration } -export class GetAccessorDeclaration extends NodeBase implements ts.GetAccessorDeclaration, FunctionLikeDeclarationBase, ClassElement { - constructor(peer: KNativePointer) { - super(peer) +// TODO: specify arkts.Node type +export class GetAccessorDeclaration extends Node implements ts.GetAccessorDeclaration, FunctionLikeDeclarationBase, ClassElement { + constructor(node: arkts.Node) { + super(node) } - // TODO: support minimal interface - get parent(): any { return todo() } - // name: PropertyName + // readonly name: PropertyName + // readonly parameters: NodeArray + readonly kind: ts.SyntaxKind.GetAccessor = ts.SyntaxKind.GetAccessor + + // TODO: name: any - body?: Block | undefined - _functionLikeDeclarationBrand: any - asteriskToken?: ts.AsteriskToken | undefined - questionToken?: ts.QuestionToken | undefined - exclamationToken?: ts.ExclamationToken | undefined - typeParameters?: NodeArray | undefined - // parameters: NodeArray parameters: any - type?: TypeNode | undefined + + // brands + _functionLikeDeclarationBrand: any _declarationBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined _classElementBrand: any _typeElementBrand: any _objectLiteralBrand: any - kind: ts.SyntaxKind.GetAccessor = ts.SyntaxKind.GetAccessor } -export class SetAccessorDeclaration extends NodeBase implements ts.SetAccessorDeclaration, FunctionLikeDeclarationBase, ClassElement { - constructor(peer: KNativePointer) { - super(peer) +// TODO: specify arkts.Node type +export class SetAccessorDeclaration extends Node implements ts.SetAccessorDeclaration, FunctionLikeDeclarationBase, ClassElement { + constructor(node: arkts.Node) { + super(node) } - // TODO: support minimal interface - get parent(): any { return todo() } - // name: PropertyName + // readonly name: PropertyName + // readonly parameters: NodeArray + readonly kind: ts.SyntaxKind.SetAccessor = ts.SyntaxKind.SetAccessor + + // TODO: name: any - body?: Block | undefined - _functionLikeDeclarationBrand: any - asteriskToken?: ts.AsteriskToken | undefined - questionToken?: ts.QuestionToken | undefined - exclamationToken?: ts.ExclamationToken | undefined - typeParameters?: NodeArray | undefined - // parameters: NodeArray parameters: any - type?: TypeNode | undefined + + // brands + _functionLikeDeclarationBrand: any _declarationBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined _classElementBrand: any _typeElementBrand: any _objectLiteralBrand: any - kind: ts.SyntaxKind.SetAccessor = ts.SyntaxKind.SetAccessor } -*/ + export class ParameterDeclaration extends Node implements ts.ParameterDeclaration, NamedDeclaration { constructor(node: arkts.ETSParameterExpression) { super(node) @@ -645,58 +581,52 @@ export class ParameterDeclaration extends Node imp readonly kind: ts.SyntaxKind.Parameter = ts.SyntaxKind.Parameter - // TODO: support minimal interface - get name(): Identifier { return todo() } + // TODO: + name: any + + // brands _declarationBrand: any - dotDotDotToken?: ts.DotDotDotToken | undefined - questionToken?: ts.QuestionToken | undefined - type?: ts.TypeNode | undefined - initializer?: ts.Expression | undefined - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined -} -/* -export type BindingName = Identifier | ts.BindingPattern; +} -// ets: VariableDeclaratorId -export class VariableDeclaration extends NodeBase implements ts.VariableDeclaration, NamedDeclaration { - constructor(peer: KNativePointer) { - super(peer) +export type BindingName = Identifier | ts.BindingPattern; - this.name = util.nodeByPeer(nativeModule._VariableDeclaratorId(global.context, this.peer)) as Identifier +export class VariableStatement extends Node implements ts.VariableStatement { + constructor(node: arkts.VariableDeclaration) { + super(node) + this.declarationList = new VariableDeclarationList(node) } - name: Identifier + readonly declarationList: VariableDeclarationList + readonly kind: ts.SyntaxKind.VariableStatement = ts.SyntaxKind.VariableStatement - // TODO: support minimal interface - get parent(): any { return todo() } - exclamationToken?: ts.ExclamationToken | undefined - type?: ts.TypeNode | undefined - initializer?: ts.Expression | undefined - _declarationBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined - kind: ts.SyntaxKind.VariableDeclaration = ts.SyntaxKind.VariableDeclaration + // brands + _statementBrand: any } -export class VariableDeclarationList extends NodeBase implements ts.VariableDeclarationList { - constructor(peer: KNativePointer) { - super(peer) - - this.declarations = util.unpack(nativeModule._VariableDeclarationDeclaratorsConst(global.context, this.peer)) as NodeArray +export class VariableDeclarationList extends Node implements ts.VariableDeclarationList { + constructor(node: arkts.VariableDeclaration) { + super(node) + this.declarations = unpackNodeArray(node.declarators) } - // TODO: support minimal interface - get parent(): any { return todo() } readonly declarations: NodeArray - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined - kind: ts.SyntaxKind.VariableDeclarationList = ts.SyntaxKind.VariableDeclarationList + get flags(): ts.NodeFlags { return unpackVariableDeclarationKind(this.node.declarationKind) } + readonly kind: ts.SyntaxKind.VariableDeclarationList = ts.SyntaxKind.VariableDeclarationList +} + +export class VariableDeclaration extends Node implements ts.VariableDeclaration, NamedDeclaration { + constructor(node: arkts.VariableDeclarator) { + super(node) + this.name = unpackNode(node.name) + } + + readonly name: Identifier + readonly kind: ts.SyntaxKind.VariableDeclaration = ts.SyntaxKind.VariableDeclaration + + // brands + _declarationBrand: any } -*/ + export class TypeParameterDeclaration extends Node implements ts.TypeParameterDeclaration { constructor(node: arkts.TSTypeParameter) { super(node) @@ -706,21 +636,13 @@ export class TypeParameterDeclaration extends Node implem readonly name: Identifier readonly kind: ts.SyntaxKind.TypeParameter = ts.SyntaxKind.TypeParameter - // TODO: support minimal interface - constraint?: ts.TypeNode | undefined - default?: ts.TypeNode | undefined - expression?: ts.Expression | undefined + // brands _declarationBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined } -// TODO: should be interface, not abstract class export abstract class TypeNode extends Node implements ts.TypeNode { - // TODO: support minimal interface + // brands _typeNodeBrand: any - kind: any } export class KeywordTypeNode extends Node implements ts.KeywordTypeNode, TypeNode { @@ -730,7 +652,7 @@ export class KeywordTypeNode extends Node implements ts.TypeRefere readonly kind: ts.SyntaxKind.TypeReference = ts.SyntaxKind.TypeReference - // TODO: support minimal interface - _typeNodeBrand: any + // TODO: typeName: any + + // brands + _typeNodeBrand: any } -// export class FunctionTypeNode extends Node implements ts.FunctionTypeNode, TypeNode, SignatureDeclarationBase { -export class FunctionTypeNode extends Node implements ts.FunctionTypeNode, TypeNode { +export class FunctionTypeNode extends Node implements ts.FunctionTypeNode, TypeNode, SignatureDeclarationBase { constructor(node: arkts.Node) { super(node) } + readonly name?: DeclarationName readonly kind: ts.SyntaxKind.FunctionType = ts.SyntaxKind.FunctionType // TODO: support minimal interface - readonly name?: PropertyName; - get parameters(): NodeArray { return todo() } + parameters: any type: any + + // brands _typeNodeBrand: any _declarationBrand: any } @@ -771,11 +696,8 @@ export class UnionTypeNode extends Node implements ts.UnionT readonly types: NodeArray readonly kind: ts.SyntaxKind.UnionType = ts.SyntaxKind.UnionType - // TODO: support minimal interface + // brands _typeNodeBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined } export class ReturnStatement extends Node implements ts.ReturnStatement, Statement { @@ -787,7 +709,7 @@ export class ReturnStatement extends Node implements ts.R readonly expression: Expression | undefined readonly kind: ts.SyntaxKind.ReturnStatement = ts.SyntaxKind.ReturnStatement - // TODO: support minimal interface + // brands _statementBrand: any } @@ -798,9 +720,11 @@ export class IfStatement extends Node implements ts.IfStateme readonly kind: ts.SyntaxKind.IfStatement = ts.SyntaxKind.IfStatement - // TODO: support minimal interface + // TODO: thenStatement: any expression: any + + // brands _statementBrand: any } @@ -811,50 +735,55 @@ export class BinaryExpression extends Node implements ts readonly kind: ts.SyntaxKind.BinaryExpression = ts.SyntaxKind.BinaryExpression - // TODO: support minimal interface + // TODO: left: any right: any operatorToken: any + + // brands _expressionBrand: any _declarationBrand: any } -/* -export class AssignmentExpression extends NodeBase implements ts.AssignmentExpression { - constructor(peer: KNativePointer) { - super(peer) + +export class AssignmentExpression extends Node implements ts.AssignmentExpression { + constructor(node: arkts.AssignmentExpression) { + super(node) } - // TODO: support minimal interface + readonly kind: ts.SyntaxKind.BinaryExpression = ts.SyntaxKind.BinaryExpression + + // TODO: right: any + left: any + operatorToken: any + + // brands _expressionBrand: any _declarationBrand: any - readonly left: any - readonly operatorToken: any - kind: ts.SyntaxKind.BinaryExpression = ts.SyntaxKind.BinaryExpression } -*/ + export class ArrowFunction extends Node implements ts.ArrowFunction { constructor(node: arkts.ArrowFunctionExpression) { super(node) if (node.scriptFunction.body === undefined) { - global.throwError('node.scriptFunction.body not expected to be undefined') + throwError('node.scriptFunction.body not expected to be undefined') } this.body = unpackNode(node.scriptFunction.body) this.parameters = unpackNodeArray(node.scriptFunction.parameters) } + get name(): never { return throwError(`name doesn't exist for ArrowFunction`) } readonly body: Block readonly parameters: NodeArray readonly kind: ts.SyntaxKind.ArrowFunction = ts.SyntaxKind.ArrowFunction - // TODO: support minimal interface + // TODO: equalsGreaterThanToken: any + + // brands _expressionBrand: any _functionLikeDeclarationBrand: any _declarationBrand: any - get name(): never { - return global.throwError(`name doesn't exist for ArrowFunction`) - } } export class NumericLiteral extends Node implements ts.NumericLiteral, Declaration { @@ -865,8 +794,9 @@ export class NumericLiteral extends Node implements ts.Nume } readonly text: string + readonly kind: ts.SyntaxKind.NumericLiteral = ts.SyntaxKind.NumericLiteral - // TODO: support minimal interface + // brands _literalExpressionBrand: any _declarationBrand: any _primaryExpressionBrand: any @@ -875,31 +805,123 @@ export class NumericLiteral extends Node implements ts.Nume _updateExpressionBrand: any _unaryExpressionBrand: any _expressionBrand: any - readonly kind: ts.SyntaxKind.NumericLiteral = ts.SyntaxKind.NumericLiteral } -/* -// ets: VariableDeclaration -export class VariableStatement extends NodeBase implements ts.VariableStatement { - constructor(peer: KNativePointer) { - super(peer) - this.declarationList = factory.createVariableDeclarationList(util.unpack(nativeModule._VariableDeclarationDeclaratorsConst(global.context, this.peer)) as NodeArray) +export class SuperExpression extends Node implements ts.SuperExpression { + constructor(node: arkts.SuperExpression) { + super(node) } - // TODO: support minimal interface - readonly declarationList: VariableDeclarationList; + readonly kind: ts.SyntaxKind.SuperKeyword = ts.SyntaxKind.SuperKeyword + + // brands + _primaryExpressionBrand: any + _memberExpressionBrand: any + _leftHandSideExpressionBrand: any + _updateExpressionBrand: any + _unaryExpressionBrand: any + _expressionBrand: any +} + +export class HeritageClause extends Node implements ts.HeritageClause { + constructor(node: arkts.SuperExpression) { + super(node) + } + + readonly kind: ts.SyntaxKind.HeritageClause = ts.SyntaxKind.HeritageClause + // token: ts.SyntaxKind.ExtendsKeyword | ts.SyntaxKind.ImplementsKeyword + // types: ts.NodeArray + + // TODO: + token: any + types: any +} + + +// TODO: there is no ParenthesizedExpression in ArkTS, +// so for temporary solution we're just gonna ignore this type of nodes +// and replace it with Expression underneath +export type ParenthesizedExpression = Expression +// export class ParenthesizedExpression extends Node implements ts.ParenthesizedExpression { +// constructor(expression: Expression) { +// super(undefined) +// this.expression = expression +// } + +// readonly expression: Expression +// readonly kind: ts.SyntaxKind.ParenthesizedExpression = ts.SyntaxKind.ParenthesizedExpression + +// // brands +// _primaryExpressionBrand: any +// _memberExpressionBrand: any +// _leftHandSideExpressionBrand: any +// _updateExpressionBrand: any +// _unaryExpressionBrand: any +// _expressionBrand: any +// } + +// TODO: +export class ImportDeclaration extends Node implements ts.ImportDeclaration { + constructor(node: arkts.UnsupportedNode) { + super(node) + } + + readonly kind: ts.SyntaxKind.ImportDeclaration = ts.SyntaxKind.ImportDeclaration + + // TODO: + moduleSpecifier: any + + // brands _statementBrand: any - locals?: ts.SymbolTable | undefined - skipCheck?: boolean | undefined - decorators?: undefined - readonly kind: ts.SyntaxKind.VariableStatement = ts.SyntaxKind.VariableStatement } -*/ + +// TODO: +export class ImportClause extends Node implements ts.ImportClause { + constructor(node: arkts.UnsupportedNode) { + super(node) + } + + readonly kind: ts.SyntaxKind.ImportClause = ts.SyntaxKind.ImportClause + + // TODO: + isTypeOnly: any + + // brands + _declarationBrand: any +} + +// TODO: +export class NamedImports extends Node implements ts.NamedImports { + constructor(node: arkts.UnsupportedNode) { + super(node) + } + + readonly kind: ts.SyntaxKind.NamedImports = ts.SyntaxKind.NamedImports + + // TODO: + elements: any +} + +export class ImportSpecifier extends Node implements ts.ImportSpecifier { + constructor(node: arkts.Identifier) { + super(node) + this.name = unpackNode(this.node) + } + + readonly name: Identifier + readonly kind: ts.SyntaxKind.ImportSpecifier = ts.SyntaxKind.ImportSpecifier + + // TODO: + isTypeOnly: any + + // brands + _declarationBrand: any +} export class UnsupportedNode extends Node implements ts.Node { constructor(node: arkts.Node) { super(node) } - kind: ts.SyntaxKind = SyntaxKind.Unknown + readonly kind: ts.SyntaxKind = SyntaxKind.Unknown } diff --git a/arkoala-arkts/libarkts/src/api/layers/ts/utilities.ts b/arkoala-arkts/libarkts/src/ts-api/utilities/private.ts similarity index 36% rename from arkoala-arkts/libarkts/src/api/layers/ts/utilities.ts rename to arkoala-arkts/libarkts/src/ts-api/utilities/private.ts index 4a7fea601..d37bced87 100644 --- a/arkoala-arkts/libarkts/src/api/layers/ts/utilities.ts +++ b/arkoala-arkts/libarkts/src/ts-api/utilities/private.ts @@ -13,26 +13,36 @@ * limitations under the License. */ -import * as ts from "./types" -import * as arkts from "../arkts/types" -import global from "../../static/global" +import global from "../../arkts-api/static/global" +import { throwError } from "../../utils" +import { nativeModule } from "../../nativeModule" +import { KNativePointer, withString } from "@koalaui/interop" + +import * as ts from "../" +import * as arkts from "../../arkts-api" import { KInt } from "@koalaui/interop" import { - es2pandaKind, + SyntaxKind, + TokenSyntaxKind, + NodeFlags, +} from "../static/enums" +import { + Es2pandaAstNodeType, Es2pandaModifierFlags, Es2pandaScriptFunctionFlags, - TokenSyntaxKind, -} from "../../static/enums" + Es2pandaTokenType, + Es2pandaVariableDeclarationKind, +} from "../../arkts-api/static/enums" export function todo(): any { - global.throwError("Not yet implemented") + throwError("Not yet implemented") } type kindTypes = | { new (node: arkts.Node): ts.Node } | { new (node: arkts.Identifier): ts.Identifier } - | { new (node: arkts.Program): ts.SourceFile } + | { new (node: arkts.EtsScript): ts.SourceFile } | { new (node: arkts.StringLiteral): ts.StringLiteral } | { new (node: arkts.NumberLiteral): ts.NumericLiteral } | { new (node: arkts.ExpressionStatement): ts.ExpressionStatement } @@ -40,7 +50,7 @@ type kindTypes = | { new (node: arkts.ReturnStatement): ts.ReturnStatement } | { new (node: arkts.ETSParameterExpression): ts.ParameterDeclaration } | { new (node: arkts.CallExpression): ts.CallExpression } - | { new (node: arkts.Block): ts.Block } + | { new (node: arkts.BlockStatement): ts.Block } | { new (node: arkts.TSTypeParameter): ts.TypeParameterDeclaration} | { new (node: arkts.MemberExpression): ts.PropertyAccessExpression} | { new (node: arkts.IfStatement): ts.IfStatement} @@ -51,35 +61,42 @@ type kindTypes = | { new (node: arkts.ArrowFunctionExpression): ts.ArrowFunction } | { new (node: arkts.ClassDeclaration): ts.ClassDeclaration } | { new (node: arkts.MethodDefinition): ts.MethodDeclaration } + | { new (node: arkts.VariableDeclarator): ts.VariableDeclaration } + | { new (node: arkts.VariableDeclaration): ts.VariableStatement } export function classByEtsNode(node: arkts.Node) { - const kinds = - new Map([ - // [es2pandaKind.UnsupportedNode, ets.UnsupportedNode], - - [es2pandaKind.Program, ts.SourceFile], - [es2pandaKind.Identifier, ts.Identifier], - [es2pandaKind.StringLiteral, ts.StringLiteral], - [es2pandaKind.NumberLiteral, ts.NumericLiteral], - [es2pandaKind.ExpressionStatement, ts.ExpressionStatement], - [es2pandaKind.FunctionDeclaration, ts.FunctionDeclaration], - [es2pandaKind.ReturnStatement, ts.ReturnStatement], - [es2pandaKind.ETSParameterExpression, ts.ParameterDeclaration], - [es2pandaKind.CallExpression, ts.CallExpression], - [es2pandaKind.Block, ts.Block], - [es2pandaKind.ETSTypeReference, ts.TypeReferenceNode], - [es2pandaKind.TSTypeParameter, ts.TypeParameterDeclaration], - [es2pandaKind.MemberExpression, ts.PropertyAccessExpression], - [es2pandaKind.IfStatement, ts.IfStatement], - [es2pandaKind.ETSPrimitiveType, ts.KeywordTypeNode], - [es2pandaKind.BinaryExpression, ts.BinaryExpression], - [es2pandaKind.ETSUnionType, ts.UnionTypeNode], - [es2pandaKind.ArrowFunctionExpression, ts.ArrowFunction], - [es2pandaKind.ClassDeclaration, ts.ClassDeclaration], - [es2pandaKind.MethodDefinition, ts.MethodDeclaration], + const types = + new Map([ + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_SCRIPT, ts.SourceFile], + [Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER, ts.Identifier], + [Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL, ts.StringLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL, ts.NumericLiteral], + [Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT, ts.ExpressionStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION, ts.FunctionDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT, ts.ReturnStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, ts.ParameterDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION, ts.CallExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, ts.Block], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, ts.TypeReferenceNode], + [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER, ts.TypeParameterDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION, ts.PropertyAccessExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT, ts.IfStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE, ts.KeywordTypeNode], + [Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION, ts.BinaryExpression], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE, ts.UnionTypeNode], + [Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, ts.ArrowFunction], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION, ts.ClassDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION, ts.MethodDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION, ts.VariableStatement], + [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR, ts.VariableDeclaration], + [Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION, ts.SuperExpression], + + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK, ts.UnsupportedNode], + [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY, ts.UnsupportedNode], + [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION, ts.UnsupportedNode], ]) - return kinds.get(node.kind) ?? global.throwError(`UNSUPPORTED NODE (ts): ${es2pandaKind[node.kind]}`) + return types.get(node.type) ?? throwError(`UNSUPPORTED NODE (ts): ${Es2pandaAstNodeType[node.type]}`) } // TODO: add checks for casts in functions below @@ -99,7 +116,7 @@ export function passNode(node: ts.Node | undefined): T if (node === undefined) { return undefined } - return (node.node as T) ?? global.throwError('trying to pass non-compatible node') + return (node.node as T) ?? throwError('trying to pass non-compatible node') } export function unpackNodeArray >(nodes: readonly U[]): ts.NodeArray @@ -114,29 +131,105 @@ export function passNodeArray(nodes: readonly ts.Node[] return nodes?.map((node: ts.Node) => passNode(node)) } -function* bits(flags: KInt) { - let bit: KInt = 1 - while (flags >= bit) { - if ((flags & bit) > 0) { - yield bit - } - bit <<= 1 +export function passIdentifier(node: ts.Identifier | string, typeAnnotation?: ts.TypeNode): arkts.Identifier +export function passIdentifier(node: ts.Identifier | string | undefined, typeAnnotation?: ts.TypeNode): arkts.Identifier | undefined +export function passIdentifier(node: ts.Identifier | string | undefined, typeAnnotation?: ts.TypeNode): arkts.Identifier | undefined { + if (node === undefined) { + return undefined + } + if (node instanceof ts.Identifier) { + if (typeAnnotation === undefined) { + return node.node + } + return arkts.Identifier.create( + node.node.name, + passNode(typeAnnotation) + ) + } + return arkts.Identifier.create( + node, + passNode(typeAnnotation) + ) +} + +// TODO: support unrequired params (with ?) +export function passTypeParams(params: readonly ts.TypeParameterDeclaration[] | undefined): arkts.TSTypeParameterDeclaration | undefined { + if (params === undefined) { + return undefined } + return arkts.TSTypeParameterDeclaration.create( + undefined, + passNodeArray(params) + ) } -// TODO: rewrite export function unpackModifiers(modifiers: KInt | undefined): ts.NodeArray { + const translation = new Map([ + // [Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, SyntaxKind.UnknownKeyword], + // [Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, SyntaxKind.ConstructorKeyword], + + [Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT, SyntaxKind.AbstractKeyword], + // TODO: unsupported + // [Es2pandaModifierFlags. , SyntaxKind.AccessorKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_ASYNC, SyntaxKind.AsyncKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_CONST, SyntaxKind.ConstKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE, SyntaxKind.DeclareKeyword], + // TODO: choose one + // [Es2pandaModifierFlags.MODIFIER_FLAGS_DEFAULT_EXPORT, SyntaxKind.DefaultClause], + // [Es2pandaModifierFlags.MODIFIER_FLAGS_DEFAULT_EXPORT, SyntaxKind.DefaultKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT, SyntaxKind.ExportKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_IN, SyntaxKind.InKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, SyntaxKind.PrivateKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_PROTECTED, SyntaxKind.ProtectedKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, SyntaxKind.PublicKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_OUT, SyntaxKind.OutKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE, SyntaxKind.OverrideKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_READONLY, SyntaxKind.ReadonlyKeyword], + [Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, SyntaxKind.StaticKeyword], + ]) + + const bits = function*(flags: KInt) { + let bit: KInt = 1 + while (flags >= bit) { + if ((flags & bit) > 0) { + yield bit + } + bit <<= 1 + } + } if (modifiers === undefined) { return [] as ReadonlyArray as ts.NodeArray } let mods: ts.Modifier[] = [] for (const bit of bits(modifiers)) { - mods.push(new ts.Modifier(global.translateModifiers.get(bit) ?? global.throwError(`Unsupported modifier: ${bit}`))) + mods.push(new ts.Modifier(translation.get(bit) ?? throwError(`Unsupported modifier: ${bit}`))) } return mods as ReadonlyArray as ts.NodeArray } export function passModifiers(modifiers: ReadonlyArray | undefined): KInt { + const translation = new Map([ + // [SyntaxKind.UnknownKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_NONE], + // [SyntaxKind.ConstructorKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR], + + [SyntaxKind.AbstractKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_ABSTRACT], + // TODO: unsupported + // [SyntaxKind.AccessorKeyword, Es2pandaModifierFlags.], + [SyntaxKind.AsyncKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_ASYNC], + [SyntaxKind.ConstKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_CONST], + [SyntaxKind.DeclareKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE], + [SyntaxKind.DefaultKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_DEFAULT_EXPORT], + [SyntaxKind.ExportKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT], + [SyntaxKind.InKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_IN], + [SyntaxKind.PrivateKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE], + [SyntaxKind.ProtectedKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_PROTECTED], + [SyntaxKind.PublicKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC], + [SyntaxKind.OutKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_OUT], + [SyntaxKind.OverrideKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE], + [SyntaxKind.ReadonlyKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_READONLY], + [SyntaxKind.StaticKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC], + ]) + if (modifiers === undefined) { return Es2pandaModifierFlags.MODIFIER_FLAGS_NONE } @@ -146,7 +239,7 @@ export function passModifiers(modifiers: ReadonlyArray(token: ts.Token): KInt { - return global.tokenKinds.get(token.kind) ?? global.throwError('unsupported token') -} + const translation = new Map([ + [SyntaxKind.PlusToken, Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS], + [SyntaxKind.MinusToken, Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_MINUS], + [SyntaxKind.AsteriskToken, Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_MULTIPLY], + ]) -function passScriptFuncModifier(modifierToken: ts.Modifier): Es2pandaScriptFunctionFlags { - return global.scriptFunctionFlags.get(modifierToken.kind) ?? global.throwError(`Unsupported ScriptFunction flag: ${modifierToken.kind}`) + return translation.get(token.kind) ?? throwError('unsupported token') } export function passModifiersToScriptFunction(modifiers: readonly ts.Modifier[] | undefined): KInt { + const translation = new Map([ + [SyntaxKind.StaticKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_STATIC_BLOCK], + [SyntaxKind.AsyncKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC], + [SyntaxKind.PublicKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE], + ]) + return modifiers?.reduce( - (prev, curr) => prev | passScriptFuncModifier(curr), + (prev, curr) => prev | (translation.get(curr.kind) ?? throwError(`Unsupported ScriptFunction flag: ${curr.kind}`)), Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE ) ?? Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE } -// export function passModifier(modifierToken: arkts.Modifier): Es2pandaModifierFlags { -// return global.modifierFlags.get(modifierToken.kind) ?? global.throwError(`Unsupported Modifier flag: ${modifierToken.kind}`) -// } +export function passVariableDeclarationKind(flags: NodeFlags): Es2pandaVariableDeclarationKind { + const translation = new Map([ + [NodeFlags.Const, Es2pandaVariableDeclarationKind.CONST], + [NodeFlags.Let, Es2pandaVariableDeclarationKind.LET], + [NodeFlags.None, Es2pandaVariableDeclarationKind.VAR], + ]) -// export function passModifiers(modifiers: readonly arkts.Modifier[] | undefined): KInt { -// return modifiers?.reduce( -// (prev, curr) => prev | passModifier(curr), -// Es2pandaModifierFlags.MODIFIER_FLAGS_NONE -// ) ?? Es2pandaModifierFlags.MODIFIER_FLAGS_NONE -// } + return translation.get(flags) ?? throwError('unsupported VariableDeclarationKind') +} + +export function unpackVariableDeclarationKind(kind: Es2pandaVariableDeclarationKind): NodeFlags { + const translation = new Map([ + [Es2pandaVariableDeclarationKind.CONST, NodeFlags.Const], + [Es2pandaVariableDeclarationKind.LET, NodeFlags.Let], + [Es2pandaVariableDeclarationKind.VAR, NodeFlags.None], + ]) + + return translation.get(kind) ?? throwError('unsupported VariableDeclarationKind') +} diff --git a/arkoala-arkts/libarkts/src/ts-api/utilities/public.ts b/arkoala-arkts/libarkts/src/ts-api/utilities/public.ts new file mode 100644 index 000000000..7ffe8302f --- /dev/null +++ b/arkoala-arkts/libarkts/src/ts-api/utilities/public.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 global from "../../arkts-api/static/global" +import { throwError } from "../../utils" +import * as ts from "../." +import * as arkts from "../../arkts-api" +import { nativeModule } from "../../nativeModule" +import { KNativePointer, withString, withStringArray, withStringResult } from "@koalaui/interop" + +import { createConfig } from "../../arkts-api/utilities/public" +export { createConfig } + +import { createContextFromString } from "../../arkts-api/utilities/public" +export { createContextFromString } + +import { proceedToState } from "../../arkts-api/utilities/public" +export { proceedToState } + +import { startChecker } from "../../arkts-api/utilities/public" +export { startChecker } + +// TODO: like in arkts utils +export function getDecl(node: ts.Node): ts.Node | undefined { + if (node.node === undefined) { + throwError('there is no arkts pair of ts node (unable to getDecl)') + } + let decl: KNativePointer = node.node.peer + decl = nativeModule._AstNodeVariableConst(global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + decl = nativeModule._VariableDeclaration(global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + decl = nativeModule._DeclNode(global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + return ts.unpackNode(arkts.unpackNonNullableNode(decl)) +} + +// TODO: like in arkts utils +export function getOriginalNode(node: ts.Node): ts.Node { + if (node.node === undefined) { + // TODO: fix this + throwError('there is no arkts pair of ts node (unable to getOriginalNode)') + } + if (node.node.originalPeer === arkts.NULLPTR) { + return node + } + return ts.unpackNode(arkts.unpackNonNullableNode(node.node.originalPeer)) +} diff --git a/arkoala-arkts/libarkts/src/api/visitor/visitor.ts b/arkoala-arkts/libarkts/src/ts-api/visitor/visitor.ts similarity index 84% rename from arkoala-arkts/libarkts/src/api/visitor/visitor.ts rename to arkoala-arkts/libarkts/src/ts-api/visitor/visitor.ts index 9940cbd74..7790966af 100644 --- a/arkoala-arkts/libarkts/src/api/visitor/visitor.ts +++ b/arkoala-arkts/libarkts/src/ts-api/visitor/visitor.ts @@ -1,6 +1,7 @@ -import global from "../static/global" +import global from "../../arkts-api/static/global" +import { throwError } from "../../utils" -import * as ts from "../layers/ts" +import * as ts from "../." import { factory } from "../factory/nodeFactory" import { SyntaxKind } from "../static/enums" @@ -34,8 +35,8 @@ type HasChildren = | ts.ClassDeclaration | ts.MethodDeclaration | ts.Block - // | ts.VariableStatement - // | ts.VariableDeclarationList + | ts.VariableStatement + | ts.VariableDeclarationList type VisitEachChildTable = { [TNode in HasChildren as TNode["kind"]]: VisitEachChildFunction } @@ -109,19 +110,19 @@ const visitEachChildTable: VisitEachChildTable = { nodesVisitor(node.statements, visitor), ) }, - // [SyntaxKind.VariableStatement]: function (node: ts.VariableStatement, visitor: Visitor) { - // return factory.updateVariableStatement( - // node, - // undefined, - // nodeVisitor(node.declarationList, visitor), - // ) - // }, - // [SyntaxKind.VariableDeclarationList]: function (node: ts.VariableDeclarationList, visitor: Visitor) { - // return factory.updateVariableDeclarationList( - // node, - // nodesVisitor(node.declarations, visitor), - // ) - // }, + [SyntaxKind.VariableStatement]: function (node: ts.VariableStatement, visitor: Visitor) { + return factory.updateVariableStatement( + node, + undefined, + nodeVisitor(node.declarationList, visitor), + ) + }, + [SyntaxKind.VariableDeclarationList]: function (node: ts.VariableDeclarationList, visitor: Visitor) { + return factory.updateVariableDeclarationList( + node, + nodesVisitor(node.declarations, visitor), + ) + }, } function nodeHasChildren(node: ts.Node): node is HasChildren { @@ -134,7 +135,7 @@ export function visitEachChild( ): T { const visitFunc = (visitEachChildTable as Record | undefined>)[node.kind]; if (nodeHasChildren(node) && visitFunc === undefined) { - global.throwError('Unsupported node kind: ' + node.kind) + throwError('Unsupported node kind: ' + node.kind) } return (visitFunc === undefined) ? node : visitFunc(node, visitor); } diff --git a/arkoala-arkts/libarkts/src/utils.ts b/arkoala-arkts/libarkts/src/utils.ts new file mode 100644 index 000000000..e13114bb7 --- /dev/null +++ b/arkoala-arkts/libarkts/src/utils.ts @@ -0,0 +1,22 @@ +/* + * 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. + */ + +export function throwError(error: string): never { + throw new Error(error) +} + +export function webpackUnoptimizableImport(path: string): any { + return require(/* webpackIgnore: true */ path) +} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/arkts-api/expressions/call-expression.test.ts b/arkoala-arkts/libarkts/test/arkts-api/expressions/call-expression.test.ts new file mode 100644 index 000000000..412fd5a3d --- /dev/null +++ b/arkoala-arkts/libarkts/test/arkts-api/expressions/call-expression.test.ts @@ -0,0 +1,53 @@ +import * as util from "../../test-util" +import * as arkts from "../../../src/arkts-api" +import { factory } from "../../../src/arkts-api/factory/nodeFactory" + +suite(util.getSuiteTitle(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + function _() {}; + ` + + const sample_out = + ` + function _() {}; + console.log('out') + ` + + let script = arkts.EtsScript.create(sample_in) + + script = arkts.EtsScript.update( + script, + [ + script.statements[0], + factory.createExpressionStatement( + factory.createCallExpression( + factory.createMemberExpression( + factory.createIdentifier( + 'console' + ), + arkts.Identifier.create( + 'log' + ), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.StringLiteral.create(undefined, + 'out' + ) + ] + ) + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + sample_out + ) + }) +}) diff --git a/arkoala-arkts/libarkts/test/arkts-api/functions/create.test.ts b/arkoala-arkts/libarkts/test/arkts-api/functions/create.test.ts new file mode 100644 index 000000000..8b4be488f --- /dev/null +++ b/arkoala-arkts/libarkts/test/arkts-api/functions/create.test.ts @@ -0,0 +1,212 @@ +import * as util from "../../test-util" +import * as arkts from "../../../src/arkts-api" +import { factory } from "../../../src/arkts-api/factory/nodeFactory" + +suite(util.getSuiteTitle(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + function _() {}; + ` + + const sample_out = + ` + function _() {}; + function foo() { + console.log("AAA") + } + foo() + ` + + let script = arkts.EtsScript.create(sample_in) + + script = arkts.EtsScript.update( + script, + [ + script.statements[0], + arkts.FunctionDeclaration.create(undefined, + arkts.ScriptFunction.create(undefined, + arkts.BlockStatement.create(undefined, + [ + factory.createExpressionStatement( + factory.createCallExpression( + factory.createMemberExpression( + factory.createIdentifier( + 'console' + ), + factory.createIdentifier( + 'log' + ), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + arkts.StringLiteral.create(undefined, + 'AAA' + ) + ] + ) + ) + ] + ), + arkts.FunctionSignature.create(undefined, + [], + undefined + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + false, + factory.createIdentifier( + 'foo' + ) + ), + false + ), + factory.createExpressionStatement( + factory.createCallExpression( + 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.EtsScript.create(sample_in) + + script = arkts.EtsScript.update( + script, + [ + script.statements[0], + arkts.FunctionDeclaration.create(undefined, + arkts.ScriptFunction.create(undefined, + arkts.BlockStatement.create(undefined, + [ + factory.createExpressionStatement( + factory.createCallExpression( + factory.createMemberExpression( + factory.createIdentifier( + 'console' + ), + factory.createIdentifier( + 'log' + ), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + factory.createIdentifier( + 'x' + ) + ] + ) + ), + factory.createExpressionStatement( + factory.createCallExpression( + factory.createMemberExpression( + factory.createIdentifier( + 'console' + ), + factory.createIdentifier( + 'log' + ), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + factory.createIdentifier( + 'y' + ) + ] + ) + ) + ] + ), + arkts.FunctionSignature.create(undefined, + [ + arkts.ETSParameterExpression.create(undefined, + factory.createIdentifier( + 'x', + arkts.ETSPrimitiveType.create(undefined, + arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_INT + ) + ), + undefined + ), + arkts.ETSParameterExpression.create(undefined, + factory.createIdentifier( + 'y', + arkts.ETSTypeReference.create(undefined, + factory.createIdentifier( + 'string' + ) + ) + ), + arkts.StringLiteral.create(undefined, + 'bbb' + ) + ) + ], + undefined + ), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + false, + factory.createIdentifier( + 'foo' + ) + ), + false + ), + factory.createExpressionStatement( + factory.createCallExpression( + factory.createIdentifier( + 'foo' + ), + undefined, + [ + arkts.NumberLiteral.create(undefined, + '0' + ) + ] + ) + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + sample_out + ) + }) +}) diff --git a/arkoala-arkts/libarkts/test/arkts-api/general/basic.test.ts b/arkoala-arkts/libarkts/test/arkts-api/general/basic.test.ts new file mode 100644 index 000000000..fbed1255a --- /dev/null +++ b/arkoala-arkts/libarkts/test/arkts-api/general/basic.test.ts @@ -0,0 +1,33 @@ +import * as util from "../../test-util" +import * as arkts from "../../../src/arkts-api" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/arkts-api/factory/nodeFactory" + +suite(util.getSuiteTitle(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + ` + + let script = arkts.EtsScript.create(sample_in) + + script = arkts.EtsScript.update( + script, + [ + factory.createExpressionStatement( + factory.createIdentifier( + 'abc' + ) + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + abc + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) +}) diff --git a/arkoala-arkts/libarkts/test/arkts-api/import-export/import.test.ts b/arkoala-arkts/libarkts/test/arkts-api/import-export/import.test.ts new file mode 100644 index 000000000..3c2c13dd3 --- /dev/null +++ b/arkoala-arkts/libarkts/test/arkts-api/import-export/import.test.ts @@ -0,0 +1,209 @@ +import * as util from "../../test-util" +import * as arkts from "../../../src/arkts-api" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/arkts-api/factory/nodeFactory" + +suite(util.getSuiteTitle(__filename), () => { + test("sample-1", function() { + const sample_in = + ` + ` + + let script = arkts.EtsScript.create(sample_in) + + script = arkts.EtsScript.update( + script, + [ + arkts.EtsImportDeclaration.create( + undefined, + arkts.StringLiteral.create( + undefined, + './variable' + ), + [ + arkts.ImportSpecifier.create( + undefined, + factory.createIdentifier( + 'X' + ), + factory.createIdentifier( + 'X' + ) + ) + ], + arkts.Es2pandaImportKinds.VALUE, + true + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + import { X } from "./variable" + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) + + test("sample-2-rewrite", function() { + const sample_in = + ` + import { Y } from "./variable" + ` + + let script = arkts.EtsScript.create(sample_in) + const importDeclaration = script.statements[0] as arkts.EtsImportDeclaration + + script = arkts.EtsScript.update( + script, + [ + arkts.EtsImportDeclaration.create( + importDeclaration, + importDeclaration.importSource, + [ + arkts.ImportSpecifier.create( + undefined, + factory.createIdentifier( + 'X' + ), + factory.createIdentifier( + 'X' + ) + ) + ], + arkts.Es2pandaImportKinds.VALUE, + importDeclaration.hasDecl + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + import { X } from "./variable" + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + }) + + test("rewrite-imported-variable", function() { + const sample_in = + ` + import { Y } from "./variable" + + function main() { + console.log(X) + } + ` + + let script = arkts.EtsScript.create(sample_in) + const importDeclaration = script.statements[0] as arkts.EtsImportDeclaration + + script = arkts.EtsScript.update( + script, + [ + arkts.EtsImportDeclaration.create( + importDeclaration, + importDeclaration.importSource, + [ + arkts.ImportSpecifier.create( + undefined, + factory.createIdentifier( + 'X' + ), + factory.createIdentifier( + 'X' + ) + ) + ], + arkts.Es2pandaImportKinds.VALUE, + importDeclaration.hasDecl + ), + script.statements[1] + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + import { X } from "./variable" + + function main() { + console.log(X) + } + `, + ts.ContextState.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.EtsScript.create(sample_in) + const functionDeclaration: arkts.FunctionDeclaration = script.statements[1] as arkts.FunctionDeclaration + const scriptFunction: arkts.ScriptFunction = functionDeclaration.scriptFunction + + script = arkts.EtsScript.update( + script, + [ + script.statements[0], + arkts.FunctionDeclaration.create( + functionDeclaration, + arkts.ScriptFunction.create( + scriptFunction, + arkts.BlockStatement.create( + undefined, + [ + factory.createExpressionStatement( + arkts.CallExpression.create( + factory.createIdentifier( + 'f' + ), + undefined, + [] + ) + ) + ] + ), + arkts.FunctionSignature.create( + undefined, + [], + undefined + ), + scriptFunction.scriptFunctionFlags, + scriptFunction.modifiers, + scriptFunction.declare, + scriptFunction.ident + ), + false + ) + ] + ) + + util.ARKTS_TEST_ASSERTION( + script, + ` + import { f } from "./f" + function main() { + f() + } + `, + ts.ContextState.ES2PANDA_STATE_PARSED + ) + + // util.cleanGenerated() + // util.fileToAbc(`./input/f.sts`, true) + // util.contextToAbc() + // util.runAbc(`./generated/main.abc`, ['./generated/f.abc']) + }) +}) diff --git a/arkoala-arkts/libarkts/test/es2panda/function-rewrite.test.ts b/arkoala-arkts/libarkts/test/es2panda/function-rewrite.test.ts deleted file mode 100644 index a69aa515e..000000000 --- a/arkoala-arkts/libarkts/test/es2panda/function-rewrite.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import * as util from "../test-util" -import * as ts from "../../src/api" -// import { FunctionTransformer } from "../../compatible/src/function-transformer" - -// TODO: update scopes (transforming after check) -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() - ` - - // util.getDefaultSetup(sample_in) - - // arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_CHECKED) - - // let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) - - // sourceFile = new FunctionTransformer().visitor(sourceFile) - - // util.assertAstEqualsAfter( - // sourceFile, - // arkts.ContextState.ES2PANDA_STATE_CHECKED, - // ` - // const x: string = "A" - - // function foo(x: string) { - // console.log("FUNC CALLED: " + x) - // } - - // foo("SAMPLE") - // ` - // ) - - // util.nativeModule._VarBinderInitTopScope(arkts.Global.context) - // util.nativeModule._VarBinderIdentifierAnalysis(arkts.Global.context) - // arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_BIN_GENERATED) - }) -}) diff --git a/arkoala-arkts/libarkts/test/es2panda/literal-declarations.test.ts b/arkoala-arkts/libarkts/test/es2panda/literal-declarations.test.ts deleted file mode 100644 index 8ad947830..000000000 --- a/arkoala-arkts/libarkts/test/es2panda/literal-declarations.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -/* -import * as util from "../test-util" -import * as arkts from "../../src/arkts" -import { factory } from "../../src/arkts" - -suite(util.getSuiteTitle(__filename), () => { - // TODO: change 0 -> 777 (waiting fix) - test("const-number", function() { - const sample_in = - ` - function f() {} - ` - - util.getDefaultSetup(sample_in) - - let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) - util.assert(arkts.isSourceFile(sourceFile)) - - const varDecl = factory.createVariableStatement( - undefined, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - factory.createIdentifier("x"), - undefined, - factory.createKeywordTypeNode(arkts.SyntaxKind.NumberKeyword), - factory.createNumericLiteral("0") - )] - ) - ) - - const f = sourceFile.statements[0] - util.assert(arkts.isFunctionDeclaration(f)) - - sourceFile = factory.updateSourceFile( - sourceFile, - [ - factory.updateFunctionDeclaration( - f, - f.modifiers, - undefined, - f.name, - f.typeParameters, - f.parameters, - f.type, - factory.createBlock([ - varDecl - ]) - ) - ] - ) - - util.assertEqualsAfter( - 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` - - util.getDefaultSetup(sample_in) - - let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) - util.assert(arkts.isSourceFile(sourceFile)) - - const varStatement = sourceFile.statements[0] - util.assert(arkts.isVariableStatement(varStatement)) - - sourceFile = arkts.factory.updateSourceFile( - sourceFile, - [ - factory.updateVariableStatement( - varStatement, - [ - // TODO: not ok maybe (not my fault) - factory.createToken(arkts.SyntaxKind.PublicKeyword), - factory.createToken(arkts.SyntaxKind.StaticKeyword), - factory.createToken(arkts.SyntaxKind.ConstKeyword), - ], - factory.createVariableDeclarationList( - [ - factory.createVariableDeclaration( - factory.createIdentifier("x"), - undefined, - factory.createKeywordTypeNode(arkts.SyntaxKind.NumberKeyword), - factory.createNumericLiteral("0") - ), - factory.createVariableDeclaration( - factory.createIdentifier("y"), - undefined, - factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword), - factory.createStringLiteral("a") - ), - factory.createVariableDeclaration( - factory.createIdentifier("z"), - undefined, - undefined, - factory.createNumericLiteral("0") - ) - ], - undefined - ) - ) - ] - ) - - util.assertEqualsAfter( - sourceFile, - ` - const x: number = 0, y: string = "a", z = 0 - ` - ) - }) -}) -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/es2panda/simple-transformations.test.ts b/arkoala-arkts/libarkts/test/es2panda/simple-transformations.test.ts deleted file mode 100644 index 3f0e79fba..000000000 --- a/arkoala-arkts/libarkts/test/es2panda/simple-transformations.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -/* -import * as util from "../test-util" -import * as ts from "../../src/api" - -suite(util.getSuiteTitle(__filename), () => { - test("sample-1", 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.createTypeReferenceNode( - ts.factory.createIdentifier("A") - ), - undefined - )] - ) - ), - sourceFile.statements[2] - ] - ) - - util.assertEqualsBinaryOuptut('ok', this) - }) -}) -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/test-util.ts b/arkoala-arkts/libarkts/test/test-util.ts index 7a132c42b..349284244 100644 --- a/arkoala-arkts/libarkts/test/test-util.ts +++ b/arkoala-arkts/libarkts/test/test-util.ts @@ -13,24 +13,22 @@ * limitations under the License. */ -import global from "../src/api/static/global" -import * as arkts from "../src/api" +import global from "../src/arkts-api/static/global" +import * as ts from "../src/ts-api" +import * as arkts from "../src/arkts-api" -import * as path from "path" -import { KNativePointer } from "@koalaui/interop" -import { nativeModule } from "../src/NativeModule" -import { NativePtrDecoder } from "../src/node/Platform" +import * as pth from "path" +import { nativeModule } from "../src/nativeModule" import { assert } from "chai" -// import { PrintVisitor } from "../compatible/src/print-visitor" -import { exec } from "child_process" +import { exec, execSync } from "child_process" -export { nativeModule } from "../src/NativeModule" +export { nativeModule } from "../src/nativeModule" export { assert } from "chai" -class defaultTransformationContext implements arkts.TransformationContext { +class defaultTransformationContext implements ts.TransformationContext { } -export function getDefaultTransformationContext(): arkts.TransformationContext { +export function getDefaultTransformationContext(): ts.TransformationContext { return new defaultTransformationContext() } @@ -54,12 +52,8 @@ export function alignText(text: string): string { return lines.map(str => str.slice((shift === -1) ? 0 : shift)).join('\n').trim() } -// export function printVisitorOutput(node: arkts.Node): string { -// return (new PrintVisitor(getDefaultTransformationContext())).astToString(node) -// } - export function getSuiteTitle(fileName: string) { - return path.basename(fileName).split('.')[0] + return pth.basename(fileName).split('.')[0] } export function assertEqualsSource(sourceResult: string, sourceExpect: string, message?: string) { @@ -70,65 +64,62 @@ export function assertEqualsSource(sourceResult: string, sourceExpect: string, m ) } -export function assertEqualsAfter(node: arkts.SourceFile, source: string, state?: arkts.ContextState) { - const finalState: arkts.ContextState = (() => { +export function TS_TEST_ASSERTION(node: ts.SourceFile, source: string, state?: ts.ContextState) { + ARKTS_TEST_ASSERTION(node.node, source, state) +} + +export function ARKTS_TEST_ASSERTION(node: arkts.EtsScript, source: string, state?: ts.ContextState) { + const finalState: ts.ContextState = (() => { if (state !== undefined) { return state } if (process.env.STATE_CHECKED !== undefined) { - return arkts.ContextState.ES2PANDA_STATE_CHECKED + return ts.ContextState.ES2PANDA_STATE_CHECKED } - return arkts.ContextState.ES2PANDA_STATE_PARSED + return ts.ContextState.ES2PANDA_STATE_PARSED })() - arkts.proceedToState(finalState) - const ast = node.node.dumpJson() - const src = node.node.dumpSrc() - const mods = node.node.dumpModifiers() - + const ast = node.dumpJson() + const src = node.dumpSrc() + const dump = node.dump() nativeModule._DestroyContext(global.context) - const sourceFile = arkts.factory.createSourceFile(source) - arkts.proceedToState(finalState) - const root = sourceFile.node + try { - assert.equal(ast, root.dumpJson(), 'Error on JSON comparison') - assertEqualsSource(src, root.dumpSrc(), 'Error on SOURCE comparison') - assert.equal(mods, root.dumpModifiers(), 'Error on MODIFIERS comparison') + const script = arkts.EtsScript.create(source, finalState) + assert.equal(dump, script.dump(), 'Error on DUMP comparison') + assertEqualsSource(src, script.dumpSrc(), 'Error on SOURCE comparison') + assert.equal(ast, script.dumpJson(), 'Error on JSON comparison') } finally { nativeModule._DestroyContext(global.context) } } -// export function dumpFirst() { -// return arkts.dumpJson(getStatement(0)) -// } - -export function addMemoParamsToFunctionDeclaration(func: arkts.FunctionDeclaration): arkts.FunctionDeclaration { - return arkts.factory.updateFunctionDeclaration( +export function addMemoParamsToFunctionDeclaration(func: ts.FunctionDeclaration): ts.FunctionDeclaration { + return ts.factory.updateFunctionDeclaration( func, undefined, undefined, func.name, undefined, [ - arkts.factory.createParameterDeclaration( + ts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier("__memo_context"), + ts.factory.createIdentifier("__memo_context"), undefined, - arkts.factory.createTypeReferenceNode( - arkts.factory.createIdentifier("__memo_context_type") + ts.factory.createTypeReferenceNode( + ts.factory.createIdentifier("__memo_context_type") ), undefined ), - arkts.factory.createParameterDeclaration( + ts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier("__memo_id"), + ts.factory.createIdentifier("__memo_id"), undefined, - arkts.factory.createTypeReferenceNode( - arkts.factory.createIdentifier("__memo_id_type") + ts.factory.createTypeReferenceNode( + ts.factory.createIdentifier("__memo_id_type") ), undefined ), @@ -139,19 +130,37 @@ export function addMemoParamsToFunctionDeclaration(func: arkts.FunctionDeclarati ) } -export function generateBin(): void { - arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_BIN_GENERATED) - exec('rm ./native/main.abc') - exec('mv ./main.abc ./native/main.abc') +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(`./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(ts.ContextState.ES2PANDA_STATE_BIN_GENERATED) + // TODO: get name of file + execSync('mkdir -p ./generated') + execSync('mv ./main.abc ./generated/main.abc') +} + + +export function disasmAbc(path: string): void { + const file = pth.basename(path).split('.')[0] + execSync(`node_modules/@panda/sdk/linux_host_tools/bin/ark_disasm --debug ${path} ./generated/${file}_asm.txt`) } -export function runAbc(): void { - exec( - 'npm run run:abc', +export function runAbc(path: string = './generated/main.abc', modules?: readonly string[]): void { + const modulesStr: string = (modules === undefined) ? '' : (':' + modules.join(':')) + exec(`node_modules/@panda/sdk/linux_host_tools/bin/ark --load-runtimes=ets --boot-panda-files=node_modules/@panda/sdk/ets/etsstdlib.abc${modulesStr} ${path} ETSGLOBAL::main`, (error: any, stdout: string, stderr: string) => { - if (error) { - console.log('failed to run abc') - return; + if (error !== null) { + assert(false, `failed to run abc: ${error}`) } console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); @@ -164,13 +173,12 @@ export function assertEqualsBinaryOuptut(output: string, ctx: Mocha.Context): vo ctx.skip() } try { - generateBin() + contextToAbc() exec( 'npm run run:abc', (error: any, stdout: string, stderr: string) => { - if (error) { - console.log('failed to run abc') - return; + if (error !== null) { + assert(false, `failed to run abc: ${error}`) } const lines = stdout.trim().split('\n') assert(lines.length >= 2) diff --git a/arkoala-arkts/libarkts/test/ts-api/classes/heritage/extends.test.ts b/arkoala-arkts/libarkts/test/ts-api/classes/heritage/extends.test.ts new file mode 100644 index 000000000..d8c110c00 --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/classes/heritage/extends.test.ts @@ -0,0 +1,59 @@ +import * as util from "../../../test-util" +import * as ts from "../../../../src/ts-api" +import { factory } from "../../../../src/ts-api" + +// TODO: +suite.skip(util.getSuiteTitle(__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/arkoala-arkts/libarkts/test/ts-api/cross/cross.test.ts b/arkoala-arkts/libarkts/test/ts-api/cross/cross.test.ts new file mode 100644 index 000000000..c6b257575 --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/cross/cross.test.ts @@ -0,0 +1,42 @@ +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" + +suite.skip(util.getSuiteTitle(__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/arkoala-arkts/libarkts/test/ts-api/demo-playground/classes.test.ts b/arkoala-arkts/libarkts/test/ts-api/demo-playground/classes.test.ts new file mode 100644 index 000000000..5a1ccf9da --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/demo-playground/classes.test.ts @@ -0,0 +1,40 @@ +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { MemoTransformer } from "../../../compatible/src/memo-transformer" + +suite(util.getSuiteTitle(__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/arkoala-arkts/libarkts/test/ts-api/demo-playground/main.sts b/arkoala-arkts/libarkts/test/ts-api/demo-playground/main.sts new file mode 100644 index 000000000..464b0be3c --- /dev/null +++ b/arkoala-arkts/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/arkoala-arkts/libarkts/test/ts-api/demo-playground/memo-rewrites.test.ts b/arkoala-arkts/libarkts/test/ts-api/demo-playground/memo-rewrites.test.ts new file mode 100644 index 000000000..1041cfb03 --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/demo-playground/memo-rewrites.test.ts @@ -0,0 +1,45 @@ +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { MemoTransformer } from "../../../compatible/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/arkoala-arkts/libarkts/test/es2panda/create-function-declaration.test.ts b/arkoala-arkts/libarkts/test/ts-api/functions/function-declaration/create-function-declaration.test.ts similarity index 94% rename from arkoala-arkts/libarkts/test/es2panda/create-function-declaration.test.ts rename to arkoala-arkts/libarkts/test/ts-api/functions/function-declaration/create-function-declaration.test.ts index 79d3e2ba5..06766042b 100644 --- a/arkoala-arkts/libarkts/test/es2panda/create-function-declaration.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/functions/function-declaration/create-function-declaration.test.ts @@ -1,6 +1,6 @@ -import * as util from "../test-util" -import * as ts from "../../src/api" -import { factory } from "../../src/api" +import * as util from "../../../test-util" +import * as ts from "../../../../src/ts-api" +import { factory } from "../../../../src/ts-api" suite(util.getSuiteTitle(__filename), () => { test("empty-function", function() { @@ -33,7 +33,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function test_func() {} @@ -78,7 +78,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function test_func(x: number) {} @@ -127,7 +127,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function test_func(x: string) {} @@ -166,7 +166,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` async function test_func() {} @@ -175,12 +175,7 @@ suite(util.getSuiteTitle(__filename), () => { ) }) - test("empty-method-with-public-static-modifiers", function() { - // class A { - // static test_func() { - // } - // } - + test.skip("empty-method-with-public-static-modifiers", function() { const sample_in = ` class A { @@ -236,7 +231,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` class A { @@ -293,7 +288,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function test_func(): void {} @@ -349,8 +344,6 @@ suite(util.getSuiteTitle(__filename), () => { ) ) - // console.log(funcDecl.node.dumpJson()) - sourceFile = factory.updateSourceFile( sourceFile, [ @@ -359,7 +352,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function foo(x: number = 0, y: string = "abc"): number | string { @@ -374,7 +367,6 @@ suite(util.getSuiteTitle(__filename), () => { test("sample-2", function() { const sample_in = ` - // console.log("OK") ` let sourceFile = ts.factory.createSourceFile(sample_in) @@ -422,13 +414,12 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function foo(x: number = 0, y: string = "abc"): number { return x } - // console.log("OK") `, ts.ContextState.ES2PANDA_STATE_PARSED ) diff --git a/arkoala-arkts/libarkts/test/es2panda/update-function-declaration.test.ts b/arkoala-arkts/libarkts/test/ts-api/functions/function-declaration/update-function-declaration.test.ts similarity index 78% rename from arkoala-arkts/libarkts/test/es2panda/update-function-declaration.test.ts rename to arkoala-arkts/libarkts/test/ts-api/functions/function-declaration/update-function-declaration.test.ts index 46eba9d13..6bd340853 100644 --- a/arkoala-arkts/libarkts/test/es2panda/update-function-declaration.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/functions/function-declaration/update-function-declaration.test.ts @@ -1,5 +1,5 @@ -import * as util from "../test-util" -import * as ts from "../../src/api" +import * as util from "../../../test-util" +import * as ts from "../../../../src/ts-api" suite(util.getSuiteTitle(__filename), () => { // adding y: string to signature @@ -49,7 +49,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function new_test_func(x: number, y: string) {} @@ -86,7 +86,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number) {} @@ -142,7 +142,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function foo(x: string) { @@ -204,7 +204,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function foo() { @@ -271,7 +271,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function foo() { @@ -344,7 +344,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function foo() { @@ -448,7 +448,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type) { @@ -462,4 +462,91 @@ suite(util.getSuiteTitle(__filename), () => { 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/arkoala-arkts/libarkts/test/es2panda/builder-lambda-rewrite.test.ts b/arkoala-arkts/libarkts/test/ts-api/functions/lambda-function/builder-lambda.test.ts similarity index 52% rename from arkoala-arkts/libarkts/test/es2panda/builder-lambda-rewrite.test.ts rename to arkoala-arkts/libarkts/test/ts-api/functions/lambda-function/builder-lambda.test.ts index f6eb521c5..0801e3cc7 100644 --- a/arkoala-arkts/libarkts/test/es2panda/builder-lambda-rewrite.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/functions/lambda-function/builder-lambda.test.ts @@ -1,9 +1,7 @@ -import * as util from "../test-util" -import * as ts from "../../src/api" -import { factory } from "../../src/api" -import { BuilderLambdaTransformer } from "../../compatible/src/builder-lambda-transformer" +import * as util from "../../../test-util" +import * as ts from "../../../../src/ts-api" -suite(util.getSuiteTitle(__filename), () => { +suite.skip(util.getSuiteTitle(__filename), () => { test("adding-lambda-param-to-signature", function() { // _Foo((instance: string) => { // // empty @@ -18,7 +16,7 @@ suite(util.getSuiteTitle(__filename), () => { } ` - let sourceFile = factory.createSourceFile(sample_in) + let sourceFile = ts.factory.createSourceFile(sample_in) util.assert(ts.isSourceFile(sourceFile)) const newName = "_Foo" @@ -67,7 +65,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` _Foo(((instance: string) => {}), "label") @@ -86,7 +84,7 @@ suite(util.getSuiteTitle(__filename), () => { Foo(instance.bar().qux(), "label1", "label2") ` - let sourceFile = factory.createSourceFile(sample_in) + let sourceFile = ts.factory.createSourceFile(sample_in) util.assert(ts.isSourceFile(sourceFile)) const newName = "_Foo" @@ -140,7 +138,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` _Foo(((instance: string) => { @@ -150,103 +148,4 @@ suite(util.getSuiteTitle(__filename), () => { ts.ContextState.ES2PANDA_STATE_PARSED, ) }) - - 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.assertEqualsAfter( - 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.assertEqualsAfter( - 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.assertEqualsAfter( - 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/arkoala-arkts/libarkts/test/es2panda/lambda-param-memoization.test.ts b/arkoala-arkts/libarkts/test/ts-api/functions/lambda-function/lambda-param-memoization.test.ts similarity index 97% rename from arkoala-arkts/libarkts/test/es2panda/lambda-param-memoization.test.ts rename to arkoala-arkts/libarkts/test/ts-api/functions/lambda-function/lambda-param-memoization.test.ts index 7d0dabf7a..32d566ba0 100644 --- a/arkoala-arkts/libarkts/test/es2panda/lambda-param-memoization.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/functions/lambda-function/lambda-param-memoization.test.ts @@ -1,5 +1,5 @@ -import * as util from "../test-util" -import * as ts from "../../src/api" +import * as util from "../../../test-util" +import * as ts from "../../../../src/ts-api" suite(util.getSuiteTitle(__filename), () => { // full memo rewrite @@ -137,7 +137,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + 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)) { diff --git a/arkoala-arkts/libarkts/test/es2panda/abc-gen.test.ts b/arkoala-arkts/libarkts/test/ts-api/general/abc-gen.test.ts similarity index 62% rename from arkoala-arkts/libarkts/test/es2panda/abc-gen.test.ts rename to arkoala-arkts/libarkts/test/ts-api/general/abc-gen.test.ts index b4b78d084..8b13ee28a 100644 --- a/arkoala-arkts/libarkts/test/es2panda/abc-gen.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/general/abc-gen.test.ts @@ -1,7 +1,7 @@ -import * as util from "../test-util" -import * as ts from "../../src/api" +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" -// tests for abc generation +// tests for abc generation (now failing on CI) suite(util.getSuiteTitle(__filename), () => { test("updating-expression-statement", function() { const sample_in = @@ -112,4 +112,64 @@ suite(util.getSuiteTitle(__filename), () => { util.assertEqualsBinaryOuptut('', 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.createTypeReferenceNode( + ts.factory.createIdentifier("A") + ), + undefined + )], + undefined + ) + ), + sourceFile.statements[2] + ] + ) + + util.assertEqualsBinaryOuptut('ok', this) + }) + + test.skip("function-expression", function() { + const sample_in = + ` + const foo = function() { console.log("abc"); }; + foo(); + ` + + ts.factory.createSourceFile(sample_in) + util.assertEqualsBinaryOuptut('abc', this) + }) }) diff --git a/arkoala-arkts/libarkts/test/es2panda/basic.test.ts b/arkoala-arkts/libarkts/test/ts-api/general/basic.test.ts similarity index 95% rename from arkoala-arkts/libarkts/test/es2panda/basic.test.ts rename to arkoala-arkts/libarkts/test/ts-api/general/basic.test.ts index 7fbfae8af..ceb3c9038 100644 --- a/arkoala-arkts/libarkts/test/es2panda/basic.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/general/basic.test.ts @@ -1,6 +1,6 @@ -import * as util from "../test-util" -import * as ts from "../../src/api" -import { factory } from "../../src/api" +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" suite(util.getSuiteTitle(__filename), () => { test("sample-1", function() { @@ -20,7 +20,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` abc @@ -55,7 +55,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function test() {} @@ -103,7 +103,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function test(x: string): number { @@ -163,7 +163,7 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsAfter( + util.TS_TEST_ASSERTION( sourceFile, ` function test(x: T): string { diff --git a/arkoala-arkts/libarkts/test/es2panda/import.test.ts b/arkoala-arkts/libarkts/test/ts-api/general/import.test.ts similarity index 95% rename from arkoala-arkts/libarkts/test/es2panda/import.test.ts rename to arkoala-arkts/libarkts/test/ts-api/general/import.test.ts index 42979123b..dd29b9a77 100644 --- a/arkoala-arkts/libarkts/test/es2panda/import.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/general/import.test.ts @@ -1,5 +1,5 @@ -import * as util from "../test-util" -import * as ts from "../../src/api" +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" suite.skip(util.getSuiteTitle(__filename), () => { // TODO: doesn't running now, but compiles (config gets only one file) diff --git a/arkoala-arkts/libarkts/test/ts-api/import-export/import.test.ts b/arkoala-arkts/libarkts/test/ts-api/import-export/import.test.ts new file mode 100644 index 000000000..08ef9fc15 --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/import-export/import.test.ts @@ -0,0 +1,48 @@ +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" + +// TODO: +suite.skip(util.getSuiteTitle(__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/arkoala-arkts/libarkts/test/ts-api/keyword-super/in-constructor.test.ts b/arkoala-arkts/libarkts/test/ts-api/keyword-super/in-constructor.test.ts new file mode 100644 index 000000000..d735fbd23 --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/keyword-super/in-constructor.test.ts @@ -0,0 +1,94 @@ +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" + +// TODO: +suite.skip(util.getSuiteTitle(__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.createTypeReferenceNode( + // 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.createTypeReferenceNode( + // 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/arkoala-arkts/libarkts/test/ts-api/variables/create-variable.test.ts b/arkoala-arkts/libarkts/test/ts-api/variables/create-variable.test.ts new file mode 100644 index 000000000..7b715a88a --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/variables/create-variable.test.ts @@ -0,0 +1,249 @@ +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" + +suite(util.getSuiteTitle(__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("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/arkoala-arkts/libarkts/test/es2panda/analysis-visitor.test.ts b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/analysis-visitor.test.ts similarity index 46% rename from arkoala-arkts/libarkts/test/es2panda/analysis-visitor.test.ts rename to arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/analysis-visitor.test.ts index e1df89b02..bb66b9f8a 100644 --- a/arkoala-arkts/libarkts/test/es2panda/analysis-visitor.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/analysis-visitor.test.ts @@ -1,9 +1,8 @@ -/* -import * as util from "../test-util" -import * as arkts from "../../src/arkts" -import { AnalysisVisitor } from "../../compatible/src/analysis-visitor" -import { Tracer } from "../../compatible/src/util" -import { Rewrite } from "../../compatible/src/transformation-context" +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { AnalysisVisitor } from "../../../compatible/src/analysis-visitor" +import { Tracer } from "../../../compatible/src/util" +import { Rewrite } from "../../../compatible/src/transformation-context" suite(util.getSuiteTitle(__filename), () => { test("sample-1", function() { @@ -16,23 +15,21 @@ suite(util.getSuiteTitle(__filename), () => { _memo_foo() ` - util.getDefaultSetup(sample_in) + let sourceFile = ts.factory.createSourceFile(sample_in) + util.assert(ts.isSourceFile(sourceFile)) - // arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_CHECKED) - - let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) - util.assert(arkts.isSourceFile(sourceFile)) + // ts.proceedToState(ts.ContextState.ES2PANDA_STATE_CHECKED) const options = {} const tracer = new Tracer(options) const rewrite = new Rewrite(sourceFile, options) - sourceFile = new AnalysisVisitor(tracer, rewrite).visitor(sourceFile) + 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) }) }) -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/builder-lambda-rewrite.test.ts b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/builder-lambda-rewrite.test.ts new file mode 100644 index 000000000..945f0bd1a --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/builder-lambda-rewrite.test.ts @@ -0,0 +1,105 @@ +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { factory } from "../../../src/ts-api" +import { BuilderLambdaTransformer } from "../../../compatible/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/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/function-rewrite.test.ts b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/function-rewrite.test.ts new file mode 100644 index 000000000..5a893911c --- /dev/null +++ b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/function-rewrite.test.ts @@ -0,0 +1,51 @@ +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import global from "src/arkts-api/static/global" +import { FunctionTransformer } from "../../../compatible/src/function-transformer" +import { PrintVisitor } from "../../../compatible/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/arkoala-arkts/libarkts/test/es2panda/memo-rewrite.test.ts b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/memo-rewrite.test.ts similarity index 80% rename from arkoala-arkts/libarkts/test/es2panda/memo-rewrite.test.ts rename to arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/memo-rewrite.test.ts index ba23e21cd..96a76f4fa 100644 --- a/arkoala-arkts/libarkts/test/es2panda/memo-rewrite.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/memo-rewrite.test.ts @@ -1,7 +1,6 @@ -/* -import * as util from "../test-util" -import * as arkts from "../../src/arkts" -import { MemoTransformer } from "../../compatible/src/memo-transformer" +import * as util from "../../test-util" +import * as ts from "../../../src/ts-api" +import { MemoTransformer } from "../../../compatible/src/memo-transformer" suite(util.getSuiteTitle(__filename), () => { test("memo-transformer-sample-1", function() { @@ -26,4 +25,3 @@ suite(util.getSuiteTitle(__filename), () => { // console.log(arkts.dumpSrcNode(sourceFile)) }) }) -*/ \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/es2panda/print-visitor.test.ts b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/print-visitor.test.ts similarity index 93% rename from arkoala-arkts/libarkts/test/es2panda/print-visitor.test.ts rename to arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/print-visitor.test.ts index d817e6aeb..f391b4358 100644 --- a/arkoala-arkts/libarkts/test/es2panda/print-visitor.test.ts +++ b/arkoala-arkts/libarkts/test/ts-api/visitors-and-transformers/print-visitor.test.ts @@ -1,6 +1,6 @@ -import * as ts from "../../src/api" -import * as util from "../test-util" -import { PrintVisitor } from "../../compatible/src/print-visitor" +import * as ts from "../../../src/ts-api" +import * as util from "../../test-util" +import { PrintVisitor } from "../../../compatible/src/print-visitor" suite.skip(util.getSuiteTitle(__filename), () => { test("sample-1", function() { diff --git a/arkoala-arkts/libarkts/test/tsconfig.json b/arkoala-arkts/libarkts/test/tsconfig.json index 7a261faad..abc41fa14 100644 --- a/arkoala-arkts/libarkts/test/tsconfig.json +++ b/arkoala-arkts/libarkts/test/tsconfig.json @@ -4,11 +4,6 @@ "rootDir": "../", "baseUrl": "../", "outDir": "build/test", - "paths": { - "api": [ - "src/arkts/index.ts" - ] - }, "module": "CommonJS" }, "include": [ diff --git a/arkoala-arkts/libarkts/src/api/utilities/utilities.ts b/arkoala-arkts/libarkts/tools/issue_gen.mjs similarity index 47% rename from arkoala-arkts/libarkts/src/api/utilities/utilities.ts rename to arkoala-arkts/libarkts/tools/issue_gen.mjs index 9d512d7fc..86c18af19 100644 --- a/arkoala-arkts/libarkts/src/api/utilities/utilities.ts +++ b/arkoala-arkts/libarkts/tools/issue_gen.mjs @@ -13,24 +13,54 @@ * limitations under the License. */ -import { nativeModule } from "../../NativeModule" -import { KNativePointer, withString } from "@koalaui/interop" -import global from "../static/global" - -export function todo(): any { - global.throwError("Not yet implemented") -} - -export function contextProgram(): KNativePointer { - return nativeModule._ContextProgram(global.context) -} - -// export function programAst(program: KNativePointer) { -// return nodeByPeer(nativeModule._ProgramAst(program)) -// } - -export function createAstDumper(peer: KNativePointer, source: string): KNativePointer { - return withString(source, (_source: string) => { - return nativeModule._CreateAstDumper(global.context, peer, _source) - }) -} +import * as fs from 'fs' +import * as path from 'path' + +process.chdir(path.resolve('./')) + +const issue_src = fs.readFileSync('../playground/src/playground.cc', { encoding: 'utf8', flag: 'r' }) + +const component_src = +` +### Component + +Plugin API + +` + +const revision_src = +` +### Revision + +"@panda/sdk": "1.5.0-dev.9184" + +` + +const reproduction_src = +` +### Reproduction + +\`\`\` +${issue_src} +\`\`\` + +` + +// TODO: +const log = `` + +const log_src = +` +### Log + +\`\`\` +${log} +\`\`\` +` + +console.log( + component_src + + revision_src + + reproduction_src + + log_src +) diff --git a/arkoala-arkts/libarkts/es2panda.webpack.config.js b/arkoala-arkts/libarkts/webpack.config.js similarity index 80% rename from arkoala-arkts/libarkts/es2panda.webpack.config.js rename to arkoala-arkts/libarkts/webpack.config.js index 5dda6871f..d5840ecc8 100644 --- a/arkoala-arkts/libarkts/es2panda.webpack.config.js +++ b/arkoala-arkts/libarkts/webpack.config.js @@ -6,7 +6,7 @@ const makeConfig = () => ({ entry: `./src/es2panda.ts`, output: { filename: "es2panda.js", - path: path.resolve(__dirname, "build/api") + path: path.resolve(__dirname, "build") }, resolve: { extensions: ['.ts', '...'], @@ -15,6 +15,7 @@ const makeConfig = () => ({ rules: [ { test: /\.ts$/, + // exclude: /node_modules/, use: [{ loader: 'ts-loader', options: { @@ -24,6 +25,7 @@ const makeConfig = () => ({ }, { test: /\.node$/, + // exclude: /node_modules/, loader: "node-loader" } ], @@ -39,6 +41,4 @@ const makeConfig = () => ({ } }) -module.exports = env => { - return makeConfig() -} +module.exports = _ => makeConfig() diff --git a/arkoala-arkts/package.json b/arkoala-arkts/package.json index 58938cd52..c5cba0344 100644 --- a/arkoala-arkts/package.json +++ b/arkoala-arkts/package.json @@ -5,6 +5,7 @@ "./arkui", "./loader", "./har", + "./libarkts", "../arkoala/arkui-common", "../arkoala/ets-plugin", "../incremental/build-common", @@ -13,10 +14,16 @@ "../incremental/runtime", "../interop" ], - "devDependencies": { + "dependencies": { "@koalaui/ets-tsc": "4.9.5-r4", "@koalaui/memo-tsc": "4.9.5", "@koalaui/fast-arktsc": "next", + "@panda/sdk": "1.5.0-dev.9184", + "@types/chai": "^4.3.1", + "@types/mocha": "^9.1.0", + "typescript": "4.9.5" + }, + "devDependencies": { "bin-links": "^4.0.4", "chai": "^4.3.6", "chalk": "^4.1.2", @@ -25,11 +32,9 @@ "rimraf": "^6.0.1", "ts-node": "^10.7.0", "tslib": "^2.3.1", - "typescript": "4.9.5", "webpack": "^5.93.0", "webpack-cli": "^5.1.4", - "copy-webpack-plugin": "^10.2.4", - "ts-loader": "^9.2.8" + "copy-webpack-plugin": "^10.2.4" }, "scripts": { "panda:sdk:install": "npm run panda:sdk:install --prefix ../incremental/tools/panda", diff --git a/interop/src/cpp/dynamic-loader.h b/interop/src/cpp/dynamic-loader.h index c7ade0fa4..f1585b3f4 100644 --- a/interop/src/cpp/dynamic-loader.h +++ b/interop/src/cpp/dynamic-loader.h @@ -44,7 +44,12 @@ inline std::string libName(const char* lib) { #include inline void* loadLibrary(const std::string& libPath) { - return dlopen(libPath.c_str(), RTLD_LOCAL | RTLD_NOW); + void* handle = dlopen(libPath.c_str(), RTLD_LOCAL | RTLD_NOW); + if (!handle) { + fprintf(stderr, "failed to load library: %s\n", dlerror()); + exit(EXIT_FAILURE); + } + return handle; } inline const char* libraryError() { -- Gitee